0
votes

I'm making a C# Win forms app that reads data from an arduino over serial port, parses it and displays it in a textbox.

My problem is that the value in the textbox is always a few seconds older than the value being sent by arduino even if I slow down the arduino to send the data once per second.

I know the problem must be in my C# code because when I read the serial port using a serial monitor everything's fine.

my code:

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    string msgType;
    string serialMsg;
    serialMsg = port.ReadLine();

    if(serialMsg.Substring(0, 1) != "#")
    {
        return;
    }

    msgType = serialMsg.Substring(1, 4);

    if(msgType == "VOLT") // recieve supply voltage reading
    {
        textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = serialMsg.Substring(5, serialMsg.Length - 5); });
    }
    if (msgType == "AMPS") // recieve supply current reading
    {
        textBox2.Invoke((MethodInvoker)delegate { textBox2.Text = serialMsg.Substring(5, serialMsg.Length - 5); });
    }
    if (msgType == "LOAD") // recieve load current reading
    {
        textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = serialMsg.Substring(5, serialMsg.Length - 5); });
    }
}

The messages coming from the arduino are in this format: # + TYPE + DATA

Can you tell me what's slowing it down?

1
It's odd to have serialMsg = port.ReadLine(); inside an event handler method, and the event object e is not being used at all.Loathing
How was the timing when you used //Console.WriteLine("amps"); ? instead of the textboxes?Mong Zhu
@Loathing " and the event object e is not being used at all" how would you use it?Mong Zhu
"The messages coming from the arduino are in this format: # + TYPE + DATA" is there a "\r\n" at the end of every Arduino message? because you use ReadLine (which is blocking) and will wait until it finds a newline in the received message.Mong Zhu
@MongZhu Usually when a specific class is created for an event object then it will contain additional properties that contain the needed information to respond to the event. I don't know which properties the SerialDataReceivedEventArgs contains, but was pointing out it was strange that it wasn't used in his code.Loathing

1 Answers

0
votes

I was sending the messages from the arduino too quickly so I put a 50ms delay between them I also used ReadExisting instead of ReadLine

This solved all the lagging