I'm attempting to read from a serial port a byte at a time. I've got the following code in my Console app:
// Open the serial port in 115200,8N1
using (SerialPort serialPort = new SerialPort("COM1", 115200,
Parity.None, 8,
StopBits.One))
{
serialPort.Open();
for (; ; )
{
int result = serialPort.ReadByte();
if (result < 0)
break;
Console.WriteLine(result);
}
}
I'm expecting this to loop round, dumping the bytes received to the screen (ignore for a moment that they'll be printed as integers; I'll deal with that later).
However, it just blocks on the ReadByte call and nothing happens.
I know that my serial device is working: if I use Tera Term, I see the data. If I use the DataReceived
event, and call SerialPort.ReadExisting
, then I can see the data.
However, I'm not bothered about performance (at least, not yet), and the protocol I'm implementing works better when dealt with synchronously.
So: what am I doing wrong? Why doesn't ReadByte
return?