C# Receive and transmit serial bytes at the same time bug -
i working app when realized error serial port transmit byte @ time reading 1 in. started testing , within 5 seconds, bingo. did not mis received byte. program stop working properly. use protocol , when receives strange bytes can stuck. similar happens.
to send byte use pushbuttons, pushbutton event calls function sends byte.
serial.write(tosend, 0, 1)
to read in use serial event calls backgroundworker processes data.
private void serial_datareceived(object sender, serialdatareceivedeventargs e) { lock (_lock) { rxbuffer += serial.readexisting(); } try { backgroundworker1.runworkerasync(); } catch { } }
console output
bullseye set @ (0,1) 9:44:52 << 0x80 9:44:52 << 0x3 9:44:52 << 0xa bullseye set @ (1,1) 9:44:52 << 0x80 9:44:52 << 0x3 9:44:52 << 0xb bullseye set @ (2,1) 9:44:52 << 0x80 9:44:52 0x95 >> 9:44:52 << 0x3 9:44:52 << 0xc <-- bullseye didn't set 9:44:53 << 0x80
the background worker use lock function.
private void backgroundworker1_dowork(object sender, system.componentmodel.doworkeventargs e) { //private void serialreceived(object s, eventargs e) //{ while (rxbuffer.length > 0) { lock (_lock) { // textbox1.text += rxbuffer[0]; byte b = convert.tobyte(rxbuffer[0]); string hexvalue = b.tostring("x"); rxbuffer = rxbuffer.remove(0, 1);
i don't know why pushbutton events interferes background worker. see have bytes received
i have solved of problems. took me many hours of googling i've found how can use begininvoke(). unlike regular invoke begininvoke seems not te slow. when machines sends many bytes target device, still freezes up
so got rid of background worker , use this. still prefer use background worker seems faster me. cannot, don't know how to.
private void serial_datareceived(object sender, serialdatareceivedeventargs e) // main serial receiving event. { lock (_lock) { rxbuffer += serial.readexisting(); } serialreceived(rxbuffer); } private void serialreceived(string value) { if (this.invokerequired) { this.begininvoke(new serialreceiveddelegate(serialreceived), new object[] { value }); } else { lock (_lock) {
Comments
Post a Comment