Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - SerialPort.ReadLine() freezes my program

I'm trying to read messages sent form my Arduino over a Serial port using baud rate 9600.

My Arduino code is programmed to send a "1" whenever I press a button and a "0" when I release my finger off the button.

So it's not constantly sending data.

My C# Program is to read that message and add it to a ListBox. But whenever I start it, the program hangs.

private void button1_Click(object sender, EventArgs e)
{
    SerialPort port = new SerialPort();
    port.BaudRate = 9600;
    port.PortName = "COM4";
    port.ReadTimeout = 1000;
    port.Open();


    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    try
    {
        ee = port.ReadLine();
        listBox1.Items.Add(ee);
    }
    catch (Exception)
    {
        timer1.Stop();
    }
}

I guess, maybe the reason is that my program should check if there's data available to be received before receiving?

like image 513
SunAwtCanvas Avatar asked Jan 28 '23 10:01

SunAwtCanvas


1 Answers

Try something like this instead. It will at least not hang, and then you can sort out what sort of data your are getting via DataReceived

From there you can determine how to better write your app

private void button1_Click(object sender, EventArgs e)
{
    SerialPort port = new SerialPort();
    port.BaudRate = 9600;
    port.PortName = "COM4";
    port.ReadTimeout = 1000;

   // Attach a method to be called when there
   // is data waiting in the port's buffer
   port.DataReceived += new
      SerialDataReceivedEventHandler(port_DataReceived);

   // Begin communications
   port.Open();
}

private void port_DataReceived(object sender,
                                 SerialDataReceivedEventArgs e)
{
   // Show all the incoming data in the port's buffer in the output window
   Debug.WriteLine("data : " + port.ReadExisting());
}

SerialPort.DataReceived Event

Indicates that data has been received through a port represented by the SerialPort object.

SerialPort.ReadExisting Method ()

Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.

like image 177
TheGeneral Avatar answered Feb 05 '23 16:02

TheGeneral