I am writing a C# program to poll data from Arduino serial port which generates data through "serial.println". In C# program, I found "port.BytesToRead" sometimes returns 0 even though the "port.dataReceived" is called. As a result, it prints out the error message that I requested it to print. However, if the "port.BytesToRead" returns 0, it stops me from polling the data from the main polling loop when I should. Any suggestions to the cause of the error and how to fix that?
_serialPort = new SerialPort();
_serialPort.PortName = "COM7";//Set your board COM
_serialPort.BaudRate = 9600;
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
_serialPort.DataReceived += Watch_BLE_DataReceived;
private void Watch_BLE_DataReceived(object sender, EventArgs arg)
{
SerialPort port = sender as SerialPort;
if (port == null)
{
return;
}
if (!(port.BytesToRead > 0))
{
// print error
}
}
In the main function, I write a polling loop like:
while (true)
{
try
{
if (!_serialPort.IsOpen)
{
_serialPort.Open();
}
}
catch (Exception e)
{
continue;
}
try
{
if (_serialPort.BytesToRead > 0) {
// process read data
}
}
}