Serial Port Complete - Latest Microcontroller projects

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

 int numberOfBytesToRead;


// Get the number of bytes available to read.

numberOfBytesToRead = myComPort.BytesToRead;

// Create a byte array large enough to hold the bytes to be read.

Byte[] newReceivedData = new Byte[numberOfBytesToRead];

// Read the bytes into the byte array.

myComPort.Read(newReceivedData, 0, numberOfBytesToRead);

// Add the bytes to the end of the list.

portBuffer.AddRange(newReceivedData);

// Call a routine to process the data.

ProcessData();
The routine below illustrates how to use a List(Of T) object to collect data. The
routine waits for eight bytes to arrive, removes the bytes from the list, and dis-
plays the bytes as text characters.

 Private Sub ProcessData()


' When eight bytes have arrived, display them and remove them from the buffer.

Dim count As Integer
Dim numberOfBytesToRead As Integer = 8

If portBuffer.Count >= numberOfBytesToRead Then

For count = 0 To numberOfBytesToRead - 1
Console.WriteLine(ChrW(portBuffer(count)))
Next count

' Remove the bytes read from the list.
portBuffer.RemoveRange(0, numberOfBytesToRead)
End If
End Sub
Free download pdf