Serial Port Complete - Latest Microcontroller projects

(lily) #1
Managing Ports and Transfers in .NET

To avoid waits and timeouts, an application can read the BytesToRead property
and attempt to read data from the port only if data is available:

 Dim receivedData As Integer


If myComPort.BytesToRead > 0 Then
receivedData = myComPort.ReadByte
Console.WriteLine(ChrW(receivedData))
Else
Console.WriteLine("No data available.")
End If

 int receivedData;


if (myComPort.BytesToRead > 0)
{
receivedData = myComPort.ReadByte();
Console.WriteLine((char)receivedData);
}
else
{
Console.WriteLine("No data available.");
}
If using a method such as BinaryReader’s ReadInt32, which reads multi-byte
values, be sure to check for the needed number of bytes in the buffer.
For reading strings, the ReadExisting method always returns immediately,
returning an empty string if the buffer is empty. For the blocking read methods,
setting the ReadTimeout property determines how long the method waits if no
data is available.
Free download pdf