Read bytes from serial port

18,375

Solution 1

  serialPort1.WriteLine(textBox1.Text);
  int bytes = serialPort1.BytesToRead;

The bytes value will always be zero. Unless you debug this code and single-step it to slow it down. It takes time for the bytes you've written with WriteLine() to be transmitted. And it takes time for the device to process them. And it takes time for the response to be received. This adds up to many milliseconds.

You'll need to fix this by looping, repeated calling the Read() method until you get the full response. If you set the SerialPort.NewLine property correctly then you'll have some odds that simply calling ReadLine() is enough to solve your problem.

Solution 2

You are going about this the wrong way.

Clicking a button will open serialPort1; sure. It will then try to read the buffer. But you only opened the port in the same method!

Take a look at this tutorial: http://www.dreamincode.net/forums/topic/35775-serial-port-communication-in-c%23/

It takes you through the entirety of serial communications in C#. You certainly don't want to be opening and reading the port only on a button press event handler.

Solution 3

Use button2 event to send the data to the port. Put the needed code (for sending the data) into a SynchronizationContext (use SynchronizationContext.Post method).

Next, register on the DataReceived event of the SerialPort class and do the reading there (again enclosed into the same SynchronicationContext object, otherwise you'll get a timeout on serial port reading/writing)

Cheers,

Share:
18,375
Mr. Nobody
Author by

Mr. Nobody

Updated on June 04, 2022

Comments

  • Mr. Nobody
    Mr. Nobody almost 2 years

    I have written code to read data as a byte array from a serial port and show it in a textbox. The code compiles fine, but doesn't work properly:

    private void button2_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen == false)
            serialPort1.Open();
        serialPort1.WriteLine(textBox1.Text);
        int bytes = serialPort1.BytesToRead;
        byte[] byte_buffer = new byte[bytes];
        serialPort1.Read(byte_buffer, 0, bytes);
        //textBox2.Text = " ";
        for (int t = 0; t < bytes; t++)
        {
            textBox2.Text += (byte_buffer[t]).ToString();
        }
    }