Reading from a SerialPort isn't always easy. Your code may fail to work reliably for several reasons:
The SerialPort.DataReceived event is fired when one or more characters have been received; there is no strict definition of when it fires. And it is not synchronized to anything, it is not aware of what you consider a message (such as a piece of text terminated by a newline).
SerialPort.ReadLine() returns one line of text assuming a newline has been received; if not a timeout exception will occur.
You are using two threads, and communicating between them using a single string (in_data). It is conceivable that two DataReceived events occur before the other thread manages to execute displaydata_event(). In that case, you would loose data.
If you are in charge of software on both sides, the simplest approach would be like this:
1. don't let the peripheral send data at will, make it a slave that doesn't have the initiative, instead it executes commands when it receives them
2. send a command to the peripheral requesting (a measurement and) the return of data
3. wait a short time
4. read the data synchronously
So basically that would be:
port.WriteLine("T"); // the command to measure and send a temperature
Thread.Sleep(100); // wait for measurement and transmission
string temp=port.ReadLine(); // receive the result
The delay should be sufficient for the peripheral to perform the measurement, and the serial port to transmit and receive the data. Since 9600 Baud would correspond to approx 1 msec per character, delaying for 100 msec seems reasonable, and not too harmful for your GUI interface.
Of course, the proper way to do communication is asynchronous, but then you need to take care of proper synchronisation and data transfer; that would include:
1. reading the port with ReadExisting, not ReadLine;
2. collecting the incoming characters;
3. identifying message boundaries;
4. passing results to another thread, using some real data structure (possibly a queue).
Hope this helps.
modified 19-Apr-19 17:08pm.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.