Serial Port Complete - Latest Microcontroller projects

(lily) #1

Chapter 9


.    


To access a COM port, an application creates a SerialPort object, sets the com-
munication parameters, and opens a connection to the port.

  


The SerialPort class’s GetPortNames method returns an array of the names of all
of the system’s COM ports. The array’s elements aren’t guaranteed to be in
alphabetical order, but the Array.Sort method can sort if needed.

 Dim nameArray() As String


nameArray = SerialPort.GetPortNames
Array.Sort(nameArray)

 string[] nameArray = null;


nameArray = SerialPort.GetPortNames();
Array.Sort( nameArray );
Because users can attach and remove virtual COM ports while an application is
running, an application may need to look for ports more than once. Also be
aware that the array index isn’t the same thing as a port’s COM-port number.
For example, if a PC’s only port is COM4, the port’s SerialPort object will be at
index zero in the array.

  


Before accessing a port or setting port parameters, the application must create a
SerialPort object:

 Friend myComPort as New SerialPort


 internal SerialPort myComPort = new SerialPort();


The SerialPort object has properties for setting port parameters. The default
parameters are 9600 bps, no parity, one Stop bit, and no flow control.
Free download pdf