0

I developed a Windows Form application, using C#, that receives data through the serial port sent by a microcontroller. I'm receiving the data using the serialPort_DataReceived event in which I use ReadLine() to read the serial port. Then I use the Invoke method to call a function that will print the received string into a textBox. The problem is that the app can't keep up with the rate at which it receives the strings, for example, the string that I send from the microcontroller has the time at which it was sent and even though it has already passed 2 or 3 seconds the app is still printing the strings that were sent at the 0.2 second. And when I send a string to the microcontroller to stop sending data, the app onlys stops ptinting the data after a while, this is, it keeps printing the values stored in the receiving buffer.

I believe that is happens given the large amount of data that the app receives and the rate (I'm using a baud rate of 115200), one string for every millisecond. This is, I think that the app is always being interrupted by the DataReceived event and it doesn't has time to print the data and starts falling behind.

One way I though of overcome this problem was with multi-threading but I can't figure it out how. I already tried a few examples using the BackgroundWorker but I didn't manage to make it work at all. I'm still a noob in terms of programming Windows Form apps and even C#.

Can anyone confirm the cause of the problem? And how do I make a thread to print the received data?

msantos
  • 3
  • 5

1 Answers1

0

You can utilize SerialPort.ReceivedBytesThreshold property and SerialPort.ReadExisting() method (or a StringBuilder instance) to update UI with a batch of strings at once rather than a single string.

For more information check:

Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50
  • Thanks for answering, changing from ReadLine() to ReadExisting() solved the problem. But now I have another problem that is how do I split the string, to plot in a chart, given that now instead of having one string I have multiple strings stored in just one. The string has following format: "value time \n" where value goes from 0 to 1024 and time is in seconds and has 4 decimal places. Before I just had one string at each time so I used .Split(' ') but now given that the string changed I can't make it work, I already tried to do in a loop but with no success. Any suggestion? – msantos Dec 29 '18 at 21:39
  • String parsing problem seems unrelated to the initial question. If the answer solved your initial problem please consider accepting it and asking a new question to keep discussions of unrelated questions separate. – Leonid Vasilev Dec 30 '18 at 10:31