Serial Port Complete - Latest Microcontroller projects

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

You can also set some of the parameters when initializing a SerialPort object:

 myComPort = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One)


 myComPort = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);


Before communicating with a port, the application must open a connection to
the SerialPort object. The Open method uses the specified parameters or
default parameters if values haven’t been specified:

 myComPort.Open()


 myComPort.Open();


 In Visual Basic, an alternate way to open a connection uses the My.Com-
puter.Ports object. Note that the object uses the OpenSerialPort (not Open)
method:


myComPort = My.Computer.Ports.OpenSerialPort( )
The OpenSerialPort method can also accept parameters:

myComPort = _
My.Computer.Ports.OpenSerialPort("COM6", 9600, Parity.None, 8, StopBits.One)
Other .NET languages don’t support the My object and thus can’t open a
COM port in this way.
Opening a port tests that the port is available and that the parameters are valid.
After opening a port, the application has exclusive use of the port. No other
application or resource can open the same port until the port is closed. An
application can change port parameters such as bit rate and parity while the
port is open.
Attempting to open a port that is in use raises an UnauthorizedAccessExcep-
tion. To prevent the exception, application code can read the port’s IsOpen
property to verify that the port is closed before attempting to open it:

 If (Not myComPort.IsOpen) Then


myComPort.Open()

End If
Free download pdf