Reputation: 2802
I have a program which write data to a USB HID device. When data is received from the USB device I get a callback from the usblib
library through a delegate event DataRecievedEventHandler
.
I am used to programming on firmware with interrupts, so that I can do
while(!flag); // Will continue when interrupt triggers and change the flag
I want to write an array element by element to the USB and wait for a return from the device after each array element
for (int i = 0; i > 16; i++)
{
sendUsbData(array[i]);
while(!receivedComplete);
// Wait for response from USB before transmitting next iteration
}
The problem is that the callback will not get triggered when I'm spooling in that while
loop. Any suggestion on how to do these kind of operations?
The library I am using for USB communication is the same as this one. In SpecifiedDevice.cs there is a method called public void SendData(byte[] data)
which I am using to send arrays of bytes.
Transmit method:
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);
}
Upon received data from USB, the callback usb_OnDataRecieved
is called.
private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
{
this.ParseReceivePacket(args.data); // Format to string and print to textbox
/*public bool*/receiveComplete = true;
}
Upvotes: 0
Views: 333
Reputation: 3280
You could switch to using a AutoResetEvent
wait handle:
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();
}
And then in your for loop:
for (int i = 0; i > 16; i++)
{
sendUsbData(array[i]);
// wait for member wait handle to be set
waitHandle.WaitOne();
}
Upvotes: 1