我有一个程序将数据写入USB HID设备。当从USB设备接收数据时,我通过委托事件usblib
从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通信的库与this one相同。在 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;
}
答案 0 :(得分: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();
}