I'm currently working on IO board. The serial object has been initialized and listen for incoming data. I'm reading incoming data using SerialPort1.ReadExisting();
as the incoming string expected to arrive as {X000000}5E +
in every reading.
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
TextBox2.Invoke(new EventHandler(delegate
{
TextBox2.AppendText(SerialPort1.ReadExisting());
}));
}
catch
{
MessageBox.Show("Couldn't open Port", "Error");
}
}
When using ReadExisting() just like that, I got the result like I wanted and I will get the value of between "{X" and "}", but when I do a split char, I always got error regarding index out of bound. I change the way of reading by adding Environment.NewLine
when reading to get whether the data is receive in a complete or not. The result will be like below image as expected.
I also try like below based from SO answer but incoming string data will be same as image above:-
var end = '
';
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
string RxString = System.Text.Encoding.ASCII.GetString(data);
LogEvents($"Serial port data: {RxString}");
It's like the full set of {X000000}5E is coming in 1-3 times in split to SerialDataReceivedEventArgs
.
Am I reading the wrong way? I have also increase the baudrate from 9600 to 19200 but the incoming data still same as provided image. Do it has to do with the IO board program? I'm not so sure about this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…