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?
ReadLine
reads until there is line terminator (\n
) in stream. From your description it seems like your device never outputs such terminator, soReadLine
blocks forever. - EvkReadLine
from stream devices (like serial port) is not a good idea, exactly because it freezes the program (when there is no finished 'line', or no data at all). UseDataReceived
event to ensure there are data andReadExisting
instead. - Julo