Serial Port Complete - Latest Microcontroller projects

(lily) #1
Using .NET’s SerialPort Class

 byte[] byteBuffer = new byte[4] {0, 0, 0, 0};
Int32 count;
Int32 numberOfReceivedBytes;


myComPort.Read(byteBuffer, 1, 3);
for (count = 0; count <= 3; count++)
{
Console.WriteLine(byteBuffer[count].ToString() );
}
If the remote port sends bytes with values 10, 20, and 30, the output is this:
0
10
20
30
The Read method doesn’t wait for the specified number of bytes to arrive. The
method returns if there is at least one received byte in the buffer. For example, if
the remote port has sent a single byte with a value of 10, the Read method in
the example above returns on receiving the byte and the output is this:
0
10
0
0
Reading a byte removes the byte from the receive buffer. If no bytes arrive, the
method times out as specified by the ReadTimeout property.
Another option for reading bytes is the ReadByte method, which reads one byte
at a time:

 Dim receivedByte As Integer


receivedByte = myComPort.ReadByte
Console.WriteLine(receivedByte)

 Int32 receivedByte;


receivedByte = myComPort.ReadByte();
Console.WriteLine(receivedByte);
Note that the ReadByte method reads a byte but returns an Integer with its
high bytes set to zero. If no byte is available, the method waits up to the time
specified in the ReceiveTimeout property.
Free download pdf