c# Serial port losing trailing character -
i have modbus interface in project. have 2 serial ports on pc, 1 on board , 1 usb serial. if use on board serial port miss last character of return string, if use usb serial port whole return string.
//onboard--------
tx: 01 03 02 00 00 12 c4 7f
rx: 01 03 24 00 00 00 64 00 00 00 0c 00 00 00 00 06 fa 02 d0 d9 54 00 00 00 00 00 04 00 0c 00 00 00 0c 00 00 00 00 00 00 c6
//usb serial--------------
tx: 01 03 02 00 00 12 c4 7f
rx: 01 03 24 00 00 00 64 00 00 00 0c 00 00 00 00 06 fa 02 d0 d9 54 00 00 00 00 00 04 00 0c 00 00 00 0c 00 00 00 00 00 00 c6 e9
if using datareceivedhandler event:
private void datareceivedhandler(object sender, serialdatareceivedeventargs e) { int rxcnt = 0; serialport sp = (serialport)sender; (rxcnt = 0; rxcnt < _serialport.bytestoread; rxcnt++) { rx_buffer[rx_buffer_len++] = (byte)_serialport.readbyte(); } }
same code running on 2 different ports different results, ideas? regards richard
something found... flush in & out buffers before transmit modbus message. if don't flush rx_buffer see missing character @ start of next received packet: tx: 01 03 02 00 00 12 c4 7f rx: 01 03 24 00 00 00 64 00 00 00 0c 00 00 00 00 06 fa 02 d0 d9 54 00 00 00 00 00 04 00 0c 00 00 00 0c 00 00 00 00 00 00 c6
tx: 01 03 02 00 00 12 c4 7f rx: e9 01 03 24 00 00 00 64 00 00 00 0c 00 00 00 00 06 fa 02 d0 d9 54 00 00 00 00 00 04 00 0c 00 00 00 0c 00 00 00 00 00 00 c6
i don't understand why character comes through next message because there 1000ms delay between 2 messages
_serialport = new serialport();
_serialport.portname = ports.elementat(0); _serialport.baudrate = 9600; _serialport.parity = parity.none; _serialport.databits = 8; _serialport.stopbits = stopbits.one; _serialport.handshake = handshake.none; _serialport.readbuffersize = 250; _serialport.receivedbytesthreshold = 1; _serialport.datareceived += new serialdatareceivedeventhandler(datareceivedhandler); try { _serialport.open(); } catch { this.close(); }
Comments
Post a Comment