Click here to Skip to main content
Click here to Skip to main content

Communication on a serial port in NET 2.0

, 16 Jan 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple 'How To' to get you started with serial port communiction in ,NET 2.0


A few days ago I said to myself that I wanted to know more about how to communicate via the serial port. When I first started searching the internet about this subject I found out that it’s not many articles that are discussing this subject and those examples that I found was mostly about the earlier VB6 MSComm control and wrappers for this control. Those matters concerning the MSComm control were not very interesting because I had read that in .NET 2.0 Microsoft had come up with a new serial port control.

As a newbie I have been spending some hours of my time to come up with what I now share with you, but as you all know it’s worth every hour when you succeed. It’s actually not a big deal to do it; it’s just a few lines of code.

Fore those of you who are familiar with the serial port communication I want to recommend this article on the Code Project. It is an excellent article about communicating with mobile phones via the serial port, and it is very clear when you fist know the basic.

The task of this example is very simple. We want to send a text string from one computer via the serial port to another computer. First of all you have to bee in the position that you have 2 computers and second you got to have a “null modem cable”. Another option is that you have 2 serial ports on the computer and connecting them with a “null modem cable”

If you don’t know what a “null modem cable” is then search the internet to see how it is configured.

First of all we want to write to the serial port, and here is the basic.

If you have 2 computers have this one on the first computer. If you have one computer make this a separate project.

In this example you got to have a Button control called btnSendText and a textBox control called txtSendText on your form on computer nr1. Just type in some text in the btnSendText control and Click Button send to send it to COM1.

Imports System
Imports System.IO.Ports

Public Class Form1
    Dim WithEvents Port As SerialPort = _
                 New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
    Private Sub btnSendText_Click(ByVal sender As System.Object, _
                  ByVal e As System.EventArgs) Handles btnSendText.Click
        Port.Write(txtSendText.Text & "!%")
    End Sub
End Class

This is just how simple it is to send a text string to the serial port.

And now how to receive the text string on the other computer.

If you have 2 computers have the next example one on the second computer. If you have one computer make this a separate project, and then run both projects at the same time.

In this example you got to have a Text control called TextBox1 and a listbox control called ListBox1 on your form on computer nr2. When clicking send on computer nr1 you will receive it in the textbox1 control on computer nr 2. When the buffer is 0 it will be added to the Listbox1 control, and ListBox1 is empty to receive the next incoming text string.

Imports System
Imports System.IO.Ports

Public Class Form1
    Dim WithEvents port As SerialPort = New _ 
     System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As _
                           System.EventArgs) Handles Me.Load
       CheckForIllegalCrossThreadCalls = False
       If port.IsOpen = False Then port.Open()
    End Sub

    Private Sub port_DataReceived(ByVal sender As Object, ByVal e As _
       System.IO.Ports.SerialDataReceivedEventArgs) Handles port.DataReceived
       TextBox1.Text = (port.ReadTo("!%"))
       If port.ReadExisting.Length = 0 Then
           TextBox1.Text = ""
       End If
    End Sub
End Class

The important thing to notice is that you have to declare the port like this “Dim WithEvents port ...

You also got to have a “CheckForIllegalCrossThreadCalls = False” declaration in the in the form load procedure to prevent it from raising an error when a thread other than the creating thread of a control tries to access one of that control's methods or properties. You also have to check if the port is open, and if it’s not open you have to open it.

As you may see that I have some special characters in both the write and the read statement.

port.Write(txtSendText.Text & "!%") and port.ReadTo("!%").

This is because if I put some special characters in the write statement stream I can ask the readTo statement to read everything until the special character and that is quiet convenient. Just test it.

There are many other options to the serial port communication, and this is only one of them.

I hope it can be of any help to somebody.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sigurd Johansen
Web Developer
Norway Norway
No Biography provided

Comments and Discussions

GeneralMy vote of 5 PinmemberEmadSaber201218-Sep-12 3:38 
QuestionCross thread calls PinmemberBrad Barnhill1-Jan-12 10:14 
QuestionHelp pls PinmemberMember 42555392-Nov-09 7:23 
AnswerRe: Help pls [modified] PinmemberSigurd Johansen4-Nov-09 12:01 
GeneralSimple and to the point PinmemberWill Mather17-Sep-09 18:48 
Generalserial help Pinmembercamcplace22-Mar-09 0:31 
GeneralMy vote of 1 PinmemberSyed Javed13-Dec-08 18:56 
GeneralRe: My vote of 1 PinmemberSigurd Johansen29-Dec-08 18:02 
This member has voted my article to 1, and that is OK for me, but I found the reason to be fare beyond reasonable. When I was checking the member I found out that he has voted 5 articles to 1 during a 10 days period. As fare as I can see he has been searching for some help, but not been able to find what he was searching for. In his frustration he has voted everything to 1. This kind of behavior get me pissed. I'm aware that not all articles are good articles, but every contribution to the community is done in good faith and with a sincere wish to help somebody. I have noticed that everyone who votes less than 2 -3 have to add a comment, and that is a good thing. Everybody that contributes with an article to the community deserve a feedback about what is wrong to learn for the next article. Not all members are experts in programming, and that may be the reason why we are members of this community. However we may all need some advice in different stages of our progress of learning. I have always been thinking of codeproject as a gentle community where people want to help each other, and it has been a pleasure so far. I must say that this kind of behavior make me reconsider my opinion of the community and I'm considering to just sign out.
GeneralGood Article PinmemberDonsw2-Dec-08 9:29 
QuestionBluetooth instead of serial port? PinmemberMember 47016437-Jul-08 2:26 
AnswerRe: Bluetooth instead of serial port? Pinmembergpraceman10-Jul-08 4:43 
GeneralSerialPort Object Buggy Pinmembergpraceman30-Jun-08 19:40 
GeneralMulti thread safe Pinmemberoferebert12-Jun-08 3:44 
GeneralNeither open nor closed PinmemberMarceRos15-May-08 1:46 
GeneralRe: Neither open nor closed PinmemberSigurd Johansen16-May-08 10:21 
QuestionASP.Net? PinmemberTechnoshaman2-Apr-08 1:57 
AnswerRe: ASP.Net? PinmemberTechnoshaman6-Apr-08 6:24 
GeneralRe: ASP.Net? PinmemberSigurd Johansen6-Apr-08 11:04 
GeneralI have a problem with your program Pinmemberlinamavilla11-Feb-08 9:53 
GeneralRe: I have a problem with your program PinmemberSigurd Johansen12-Feb-08 6:09 
GeneralNeed help ,How To Connect serial with Cach Box PinmemberMujahid10-Feb-08 9:15 
GeneralRe: Need help ,How To Connect serial with Cach Box PinmemberSigurd Johansen10-Feb-08 11:51 
Generalneed help pls, reading from usb port Pinmemberadnanmn23-Jan-08 20:54 
GeneralRequired Help Pinmemberkevinbhavasar10-Sep-07 1:45 
GeneralRe: Required Help PinmemberSigurd Johansen11-Sep-07 4:55 
Generalhelp me on transfer data between modems Pinmembernkcspecial19-Aug-07 2:14 
Generalserial port usb adapter Pinmemberrigidigi30-Jul-07 10:13 
GeneralRe: serial port usb adapter PinmemberSigurd Johansen31-Jul-07 10:36 
GeneralRe: serial port usb adapter PinmemberTorpedoke-be8-Mar-08 12:00 
GeneralRe: serial port usb adapter Pinmemberrigidigi2-Jul-09 9:41 
GeneralRe: serial port usb adapter [modified] Pinmembergpraceman30-Jun-08 19:27 
QuestionText files Pinmemberdb@Jax11-Jul-07 9:21 
Questionc sharp PinmemberPushkar Joshi21-May-07 1:27 
AnswerRe: c sharp PinmemberSigurd Johansen21-May-07 2:25 
GeneralRe: c sharp PinmemberPushkar Joshi21-May-07 19:07 
Questionhow to dial a number with serialport? Pinmembermehrdadsh10-May-07 4:27 
AnswerRe: how to dial a number with serialport? PinmemberSigurd Johansen14-May-07 21:24 
GeneralRe: how to dial a number with serialport? PinmemberVachanC29-Apr-08 21:50 
Questionmessage arrived after port closed PinmemberTaoge8-Apr-07 18:58 
AnswerRe: message arrived after port closed PinmemberSigurd Johansen9-Apr-07 4:47 
QuestionIn Web PinmemberPanda197527-Feb-07 7:19 
GeneralThank you Pinmembervmayzel24-Feb-07 10:42 
Generalevent object Pinmemberkuncung5-Feb-07 22:17 
GeneralRe: event object PinmemberSigurd Johansen6-Feb-07 11:58 
Generalerror in using System.IO.Ports PinmemberMember #374662521-Jan-07 2:29 
GeneralRe: error in using System.IO.Ports PinmemberSyed Muhammad Kamran23-Jan-07 1:49 
GeneralCombine RD & TD to form a loop to test this. PinmemberSyed Muhammad Kamran17-Jan-07 0:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150331.1 | Last Updated 17 Jan 2007
Article Copyright 2007 by Sigurd Johansen
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid