0

我有一个将数据写入 USB HID 设备的程序。usblib当从 USB 设备接收到数据时,我通过委托事件从库中获得回调DataRecievedEventHandler

我习惯于使用中断对固件进行编程,所以我可以做到

while(!flag); // Will continue when interrupt triggers and change the flag

我想将一个数组元素逐个元素写入USB,并在每个数组元素之后等待设备返回

for (int i = 0; i > 16; i++)
{ 
    sendUsbData(array[i]);
    while(!receivedComplete);
    // Wait for response from USB before transmitting next iteration
}

while问题是当我在该循环中进行假脱机时,不会触发回调。关于如何进行此类操作的任何建议?

我用于 USB 通信的库与这个库相同。在SpecifiedDevice.cs中有一个方法public void SendData(byte[] data),我用它来发送字节数组。

传输方式:

public void sendUsbData(byte _txData)
{
    byte[] txData = new byte[this.usb.SpecifiedDevice.OutputReportLength];
    txData[1] = 0x50; // 0x50 = loopback command. Element 0 is always 0x00

    int pos = 2;
    foreach (byte b in _flashData)
    {
        txData[pos] = b;
        pos++;
    }

        this.usb.SpecifiedDevice.SendData(txData);
}

从 USB 接收到数据后,将调用回调usb_OnDataRecieved

private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
{
    this.ParseReceivePacket(args.data); // Format to string and print to textbox
    /*public bool*/receiveComplete = true; 
}
4

1 回答 1

1

您可以切换到使用AutoResetEvent等待句柄:

public void sendUsbData(byte _txData)
{
  byte[] txData = new byte[this.usb.SpecifiedDevice.OutputReportLength];
  txData[1] = 0x50; // 0x50 = loopback command. Element 0 is always 0x00

  int pos = 2;
  foreach (byte b in _flashData)
  {
    txData[pos] = b;
    pos++;
  }

  // reset member wait handle
  waitHandle = new AutoResetEvent(false); 
  this.usb.SpecifiedDevice.SendData(txData);
}

private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
{
  this.ParseReceivePacket(args.data); // Format to string and print to textbox

  // signal member wait handle
  waitHandle.Set();
}

然后在你的 for 循环中:

for (int i = 0; i > 16; i++)
{ 
  sendUsbData(array[i]);

  // wait for member wait handle to be set
  waitHandle.WaitOne();
}
于 2013-09-24T09:03:16.403 回答