Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading varying sized string from serial port

I am reading in a string in C# from an arduino over serial communication. I was using ReadLine() to set a string to the incoming data. However, I noticed that ReadLine() slows down my data reception and when using a console I can see that a delay begins to develop between receiving the data and outputting it.

Question

Is there a fast way to read in one line from serial to a string when the size of the string is variable? I need to be able to process the string and it is important that I don't lose data between reads. My data comes in using the format <ID,Name,Data> and each of these are on their own line. Is there any way I could just read between < and >?

Current Code

private void Form1_Shown(object sender, EventArgs e)
    {
            serialPort1 = new SerialPort(comboPorts.SelectedItem.ToString(), 115200);
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.Open();
    }

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    { 
        string inData = serialPort1.ReadLine();
        Console.WriteLine(inData);

}

like image 386
C Raber Avatar asked Nov 03 '25 17:11

C Raber


1 Answers

The DataReceived event is issued when data is read from the Serial connection, you are expected to read all available data from the buffer when you receive the event.

My guess is that the slow down occurs because you call ReadLine, but there is more than one line in the buffer. You wont read the second line until more data is added. (i.e. the 3rd, 4th or 5th line) You'll constantly be behind.

Perhaps you could re-architect to read lines in a thread, rather than from the event.

private void Form1_Shown(object sender, EventArgs e)
{
    serialPort1 = new SerialPort(comboPorts.SelectedItem.ToString(), 115200);

    serialPort1.Open();
    Thread t = new Thread(ReadThread);
    t.Start(serialPort1);
}

private void ReadThread(object context)
{
    SerialPort serialPort = context as SerialPort;

    while (serialPort.IsOpen)
    {
        string inData = serialPort.ReadLine();
        Console.WriteLine(inData);
    }
}
like image 93
dodald Avatar answered Nov 05 '25 08:11

dodald