0
votes

I have a serial port that recieves some color data from arduino board at 115200 baud rate. At small scale (1-byte request from arduino for pc to send next command, implemented for synchronization) it works fine, but when i request a lot of data (393 bytes) and it sends them, it looks as if serial port just eats data, and BytesToRead usually equals to 5 or 6

Code:

void GetCurrentState()
    {
        int i = 0;
        Color WrittenColor; //Color to write to an array
        byte red;
        byte green;
        byte blue;
        AddToQueue(new byte[] { 6 });  //adds command that requests data to a sender queue
        while (i <= StripLength) //read data until array is read completly
        {
            Console.WriteLine($"Bytes to read: {SerialPort1.BytesToRead}");//Debug
            if (SerialPort1.BytesToRead >= 3) //if we have a color ready to read and construct, do it, else wait for more data
            {
                red = (byte)SerialPort1.ReadByte(); //Read red part
                green = (byte)SerialPort1.ReadByte(); //Read green part
                blue = (byte)SerialPort1.ReadByte(); //Read blue part
                WrittenColor = Color.FromArgb(red, green, blue); //Make a color
                SavedState[i] = WrittenColor; //Write it
                i++; //increment counter
            }
        }
    }
1
Why not use the DataReceived event? Why try to reinvent the wheel when someone already did all the hard work for you. I have a feeling you're not reading everything. See docs.microsoft.com/en-us/dotnet/api/…Baddack

1 Answers

0
votes

You might try buffering the serial port data to another stream in memory, and then read data from that stream. This is because if you are actually transferring enough data to need that high of a baud rate, then it's possible that you are not reading the data fast enough. (I know that's not a massive data rate, but most hobby applications can get away with less)

Have you tried a lower baud rate? Or are you stuck with this one?

You might find this post helpful: Reading serial port faster

I would probably have one thread reading the serial port in a loop, and then queuing the data into a thread-safe ConcurrentQueue. I would have another thread read from that queue and do useful things with the data. And, as you are already doing, use a queue to send commands, but I would use another thread for sending them (you might already be doing this).