2
votes

Hello could someone tell what is the best way to buffer incoming Values on serial port? Because I have the problem that some values are corrupted when written into a textBox. I already asked about that in the following question: Why do I get partly strange values from serial port in C# Someone told me it is because I don't buffer them. When I write the String that I get from serial port in to a text File, I get this:

      12.5 g   

      12.5
 g   


 12.5 g   

      12.
5 g   

      12.5 g   

      12.5 g   

      12.5 g   

      1
2.5 g   


    12.5 g   


12.5 g   

      12.5 g   

      12.5 g   


      12.5 g   


 12.5 g   

      12.5 g   


  12.5 g   

      12.5 g   

Hope someone can help me.

2
I read the previous question and you don't seem to understand what the potential issue is. Say the serial port spits out "12.5g, 12.6g, 12.4g", but you read in each time more than 5 characters without knowing it, so you read in "12.5g, 1" on one read, then the next read reads in "2.6g, 12." or something similar. You writing to a text box is likely unrelated to your issue. - Quantic
I think the problem is somewhere here: int dataLength = _serialPort.BytesToRead; byte[] data = new byte[dataLength]; int nbrDataRead = _serialPort.Read(data, 0, dataLength); if (nbrDataRead == 0) return; string str = Encoding.UTF8.GetString(data); - Sardar Agabejli

2 Answers

1
votes

The best way to approach it is to use 'g' to mark the end of a string:

string leftOver = "";

// Read the data like you have

string str = leftOver + Encoding.UTF8.GetString(data);
int index = str.IndexOf('g');
if (index == -1)
{
    leftOver += str;
}
else
{
    leftOver = str.Substring(index + 1);
    str = str.Substring(0, index + 1);
}
1
votes

OK I got it now!

I have to buffer the values coming via serial port from scale in a file at first. Don't really know why, but then the single values are in right form and can be read out without Problems.

private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{

    if (InvokeRequired)     //<-- Makes sure the function is invoked to work properly in the UI-Thread
        BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself
    else
    {
        int dataLength = _serialPort.BytesToRead;                

        byte[] data = new byte[dataLength];
        int nbrDataRead = _serialPort.Read(data, 0, dataLength);
        if (nbrDataRead == 0)
            return;
        string str = Encoding.UTF8.GetString(data);


        //Buffer Values in a text file at first!
        File.AppendAllText("buffer1.txt", str);
        string strnew = File.ReadLines("buffer1.txt").Last();

        textBox5.Text = strnew;

My next problem is how to keep the buffer file in a appropriate size.