Search code examples
c#.netwinformsserial-porthardware-interface

Receive data from serial port on higher baud rates using C#


I am trying to receive data from a device via virtual COM port over USB. The device is basically a micro controller which continuously transmit few bytes of data. The baud rate is 921600. I can see the data on HyperTerminal as shown in image below:

Screenshot of receiving data

I have written a small code to receive this data:

    char[] charData = new char[1024];
    void ReadData()
    {
        while (true)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1024; i++)
            {
                charData[i] = (char)serialPort1.ReadChar();
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            textBox1.Text = new string(charData);
        }
    }

I have called this code through a Thread. This code works fine when using lower baud rates (i.e 9600, tried using another microcontroller to simulate my desired data using lower baud rate). But is unable to work with higher baud rates. The code just simply doesn't receive any data and also doesn't generate any exception.

Please help my figure out this problem. Code sample is highly appreciated!

Thanks.

EDIT:

Serial Port configuration:

enter image description here

Microcontroller code: (The microcontroller is Arduino Due here is a code for reference):

void setup() 
{
  SerialUSB.begin(921600);
}

void loop() 
{
  SerialUSB.print("#A1G-5G11bng1");
}

Solution

  • Thanks to Ben Voigt idea of not reading data byte by byte, I have successfully managed to figure out the way, Here is my updated code function to read data:

        void ReadData()
        {
            byte[] bytesData = new byte[1024];
            while (true)
            {
                serialPort1.Read(bytesData, 0, 1024);
                char[] c = Encoding.UTF8.GetString(bytesData).ToCharArray();
                textBox1.Text = new string(c);
            }
        }
    

    The code now read entire 1024 bytes of data at once and is efficient and faster then my previous approach of reading single byte of data at a time. All other configuration remained unchanged.