## Wednesday, April 23, 2008

### Using PC Serial Port

Controlling and using PC serial port using Visual Basic programming is discussed. Many computers have a serial port. If your computer does not have one, you can buy a USB to RS232 converter.

There are three topics to be discussed here.
1. Using VB6
2. Using VB2005 (VB.NET2)
3. Serial Port as IO

### Using VB6

MSComm ActiveX contorl can be used in VB6 to communicate through a serial port. Create a New project by selecting Standard Exe. Go to Project Menu and select Components command. Add Microsoft Comm Control 6.0 from Components dialog.

After OK has clicked, there will be MSComm control with a telephone icon in the Toolbox. Double click on this control to add it onto the Form. Its name will be "MSComm1" as shown below and you can change its settings in the Properties box near the bottom right corner.

In this example, its settings will not be changed in its properties box. But they will be changed in "Form_Load()" event. Double click on any blank space on the form to write in Form_Load() event as shown in the following code.

Private Sub Form_Load()MSComm1.Settings = "9600,N,8,1"MSComm1.RThreshold = 1MSComm1.CommPort = 1MSComm1.PortOpen = TrueText1.Text = ""End Sub

The setting "9600,N,8,1" means that we will use Baud rate 9600, No parity, 8 data bit and 1 stop bit. RThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Comm port 1 of PC is used and opened here. A textbox is used to display the receive data. Another textbox and a Command button are added to the form to send data. Caption property of the Command button is changed to 'Send'.

Double click on that button and write the following code in its click event function.

Private Sub Command1_Click()MSComm1.Output = "ABCD"End Sub

Everytime the button is clicked, the data "ABCD" will be sent from the serial port. You can replace ABCD with any data you want to send. To receive data, OnComm event of MSComm control is used. Double click on MSComm control and write the following code in its event function. If OnComm Event is a data received event -comEvReceive, the Textbox will be updated with received data.

Private Sub MSComm1_OnComm()If MSComm1.CommEvent = comEvReceive Then  Text1.Text = Text1.Text & MSComm1.InputEnd IfEnd Sub

After that, program will be as shown in the following figure.

Try to run the program. Data will be sent when the Send button is clicked.

### Using VB2005

In VB2005, using Serial port is easier because SerialPort control is already in the toolbox. Create a Windows Application from File Menu -> New Project command. Double click on SerialPort Control in the Toolbox to add it onto the form.

Select the control and change its properties in the properties box. In the example, Name will be SerialPort1, BaudRates will be 9600, Databits will be 8, Parity will be None and StopBits will be One. ReceivedBytesThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Therefore ReceivedBytesThreshold will be 1. Comm port 1 of PC is used and PortName will be set to COM1.

Double click on the Form and write the following code in the Form Load Event.

CheckForIllegalCrossThreadCalls = FalseSerialPort1.Open()

By doing so, the comm port will be opened at the program start. Normal Encoding of serial port control is ASCII. You can also change Encoding at the Form Load Event as follow.

SerialPort1.Encoding = System.Text.Encoding.Default

Add a Button to send data and a TextBox to display received data. Change Text property of the Button to Send. Double click on the Button and write the following code in its click event.

SerialPort1.Write("ABCD")

Everytime, the button is clicked, the data "ABCD" will be sent. You can replace ABCD with any data you want to send. To receive data, write the following code in the DataReceived event of SerialPort1.

TextBox1.Text &= SerialPort1.ReadExisting()

If you want to read the received data byte by byte, the following code can also be used.

Dim n As Int32Dim i As Int32Dim cmd As StringDim c As Stringn = SerialPort1.BytesToReadFor i = 1 To n  c = Chr(SerialPort1.ReadChar())  cmd &= cNextTextBox1.Text &= cmd

After that, the program will be as follow.

Then, you can try the program to send and receive data.
Sending Binary Data
The example above is for character data. For binary data whose ASCII code number greater than 127 can be manipulated as follow.

Dim a(3) As Bytea(0) = &H41a(1) = &H31a(2) = &HFFa(3) = &H80SerialPort1.Write(a, 0, 4)

Dim n As Int32Dim i As Int32Dim cmd As String = ""Dim c As Stringn = SerialPort1.BytesToReadFor i = 1 To nc = Chr(SerialPort1.ReadByte())cmd &= cNextTextBox1.Text &= cmd

Getting Port List in Your PC
To list the all ports in your PC in a Combo box and to select the port number that had been saved in user setting, you can used the following code.

Dim ports As String() = SerialPort.GetPortNames()Dim port As StringArray.Sort(ports)cmbSerial.Items.Clear()For Each port In portscmbSerial.Items.Add(port)Next portDim index As Integer
index = cmbSerial.FindString(My.Settings.MCOM)cmbSerial.SelectedIndex = index

### Using Serial Port as IO

Besides Tx and Rx to send and receive data, there are two control outputs and four status inputs in a serial. RTS and DTR can be used as outputs. CTS, DSR, CD and RI can be used as inputs. If you don't need a lot of I/O in an application, serial port is a good choice for IO interface.

Related post: