Chapter 9
Byte[] dataToSend = new Byte[5];
dataToSend[0] = (byte)'C';
dataToSend[1] = (byte)'M';
dataToSend[2] = (byte)'D';
dataToSend[3] = (byte)'1';
dataToSend[4] = 10;
myComPort.Write(dataToSend, 0, 5);
But the WriteLine method offers an easier way. The method converts each char-
acter in the String to a code and writes the codes, followed by a LF character, to
the port:
dim dataToSend as String
dataToSend = "CMD1"
myComPort.WriteLine(dataToSend)
String dataToSend;
dataToSend = "CMD1";
myComPort.WriteLine(dataToSend);
The SerialPort class provides methods for reading and writing individual Bytes
or Chars; arrays or portions of arrays of Bytes or Chars; Strings; Strings + New-
Line characters; formatted Strings; Boolean values, numeric types such as Deci-
mal, Int16, and others; and text representations of numeric values. When
reading data, most methods block (don’t return) until at least one byte or Char
is available or a timeout occurs. The ReadExisting method is an exception that
returns immediately whether data is available or not. The BytesToRead prop-
erty provides a way to find out if data is available before attempting a read oper-
ation. Methods that write data also block until the write buffer is empty.
Attempting to read or write to a port that isn’t open raises an InvalidOperation-
Exception. To prevent the exception, code can check to ensure the port is open
and open the port if needed before reading or writing to the port.