Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone.

Iam having some trouble reading data from my serial port.
Iam sending data from two sensors every second as a ;-seperated string and want to read them and update two textboxes continously.

When I try to read data from the Serial port with ReadExcisting() Iam getting more then just the two values. Readline() doesn't seem to work either.

Any help woule be great:-)

Thanks in advance,

Michael

What I have tried:

C#
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string inData = sp.ReadExisting();
    data = inData.Split(delimiterChars);

    if(data.Contains("Temp1"))
    {
        Temp1txt.Invoke(this.myDelegate, new Object[] { data });
    }
    else if (data.Contains("Temp2"))
    {
        Temp2txt.Invoke(this.myDelegate, new Object[] { data });
    }

    richBox1.Invoke(new Action(() => { richBox1.AppendText(data[1]); }));
    richBox1.Invoke(new Action(() => { richBox1.SelectionStart = richBox1.Text.Length; }));            
    richBox1.Invoke(new Action(() => { richBox1.ScrollToCaret(); }));
}
Posted
Updated 10-Jan-17 3:40am
v2
Comments
#realJSOP 10-Jan-17 6:05am    
What is the additional data you're getting that you're not expecting?

ReadExisting reads all data available in the internal input buffer. This might be multiple data sets if the previous read was too long ago and might also be an incomplete last data set.

So you need some kind of detection to differentiate between data sets and if the last data are complete. This depends on the format of your data. Often a data set is terminated by a line feed which can then be used. If so, ReadLine can be used instead (and should be used because it makes processing the data much simpler).

But when ReadLine does not return, there seems to be no or a different end of line indicator. If there is a different indicator, you can set it using the SerialPort.NewLine Property (System.IO.Ports)[^] to let ReadLine return when that character is received.

So it depends on the end of line / data set indicator that is used by your sensors.
 
Share this answer
 
Comments
CPallini 10-Jan-17 6:20am    
5.
Thanks!

I just send a new line character from Microcontroller which works perfectly!

Best regards,

Michael
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900