Serial Port Complete - Latest Microcontroller projects

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

As with BinaryReader and BinaryWriter objects, an application can create
StreamReader and StreamWriter objects using the SerialPort object’s Base-
Stream property:

 serialPortStream = myComPort.BaseStream
streamReader1 = New StreamReader(serialPortStream)
streamWriter1 = New StreamWriter(serialPortStream)


 serialPortStream = myComPort.BaseStream;
streamReader1 = new StreamReader(serialPortStream);
streamWriter1 = new StreamWriter(serialPortStream);
Setting StreamWriter’s AutoFlush property to True causes Write operations to
send data immediately to the port:


 streamWriter1.AutoFlush = True


 streamWriter1.AutoFlush = true;


If the AutoFlush property is False, data written to the stream may be delayed in
the stream’s buffer. When AutoFlush is False, calling the Flush method or clos-
ing the stream sends any buffered data to the port.
The Write and WriteLine methods can write Strings to a port:

 streamWriter1.Write("hello, ")
streamWriter1.WriteLine("world")


 streamWriter1.Write("hello, ");
streamWriter1.WriteLine("world");
In addition to basic Strings, StreamWriter’s Write and WriteLine methods can
write Chars, text representations of numeric and Boolean values, text represen-
tations of objects as defined an object’s ToString property, and strings formatted
as defined by the String.Format property.

Free download pdf