Serial Port Complete - Latest Microcontroller projects

(lily) #1

Chapter 10


 private void ProcessData()
{
// When eight bytes have arrived, display them and remove them from the buffer.


int count;
int numberOfBytesToRead = 8;

if (portBuffer.Count >= numberOfBytesToRead)
{
for (count = 0; count < numberOfBytesToRead; count++)
{
Console.WriteLine((char)(portBuffer[count]));
}
// Remove the bytes read from the list.

portBuffer.RemoveRange(0, numberOfBytesToRead);
}
}
In a similar way, an application can create a list of Chars or Strings for storing
received text. To add a received string to a list, use the Add method.

0 
 
033 
1 3 


Each read operation adds overhead, which can degrade performance of applica-
tions that are reading large amounts of data. For example, an application read-
ing a large file from a port might want to read the file using as few read
operations as possible rather than collecting each byte as it arrives. An applica-
tion can read a port’s BytesToRead property to find out if the needed number of
bytes is available before reading from the port.
When using the ReadExisting method, call the method less often to retrieve
more data on each call. When using the DataReceived event, set Received-
BytesThreshold to a large block size or to the expected number of bytes if
known. A timer can trigger a read of any amount smaller than Received-
BytesThreshold that remains unread in the buffer. When waiting for expected
data, set ReadTimeout long enough to prevent timeouts under normal condi-
tions. Be sure to add in typical delays due to flow control.
An application that must take action in response to received data might need to
read each byte as soon as it arrives at the port. In that case, use the DataRe-
ceived event for fast response and set ReceivedBytesThreshold to 1.
Free download pdf