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 = 1
MSComm1.CommPort = 1
MSComm1.PortOpen = True
Text1.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.Input
End If
End 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 = False
SerialPort1.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 Int32
Dim i As Int32
Dim cmd As String
Dim c As String
n = SerialPort1.BytesToRead
For i = 1 To n
  c = Chr(SerialPort1.ReadChar())
  cmd &= c
Next
TextBox1.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 Byte
a(0) = &H41
a(1) = &H31
a(2) = &HFF
a(3) = &H80
SerialPort1.Write(a, 0, 4)


ReadChar cannot be used to receive binary data. ReadByte can be used instead as in the following example.


Dim n As Int32
Dim i As Int32
Dim cmd As String = ""
Dim c As String
n = SerialPort1.BytesToRead
For i = 1 To n
c = Chr(SerialPort1.ReadByte())
cmd &= c
Next
TextBox1.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 String
Array.Sort(ports)
cmbSerial.Items.Clear()
For Each port In ports
cmbSerial.Items.Add(port)
Next port
Dim 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:

No comments:

Post a Comment

Comments are moderated and don't be surprised if your comment does not appear promptly.