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

Communication on a serial port in NET 2.0

By , 16 Jan 2007
 

Introduction

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.Open()
        Port.Write(txtSendText.Text & "!%")
        Port.Close()
    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
           ListBox1.Items.Add(TextBox1.Text)
           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.

License

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
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberEmadSaber201218 Sep '12 - 2:38 
easy and running..
QuestionCross thread callsmemberBrad Barnhill1 Jan '12 - 9:14 
cross thread calls can be handled with delegates so you can get rid of the CheckForIllegalCrossThreadCalls. This is an improper way to handle cross thread calls.
Brad Barnhill

QuestionHelp plsmemberMember 42555392 Nov '09 - 6:23 
i am trying to real all the data send from a device connected on serial port RS232 on my computer. this is only a part of a large project that i am working on. i want to capture all the data (text) from the device into a richtextbox. and after that to do somenting with the data.
 
My post Read all the data from a serial port[^]
 
can you help me please? contact YM opium_21002100
AnswerRe: Help pls [modified]memberSigurd Johansen4 Nov '09 - 11:01 
Can't you just logg it into a text file and then later read i back into a rich textbox?
Code to read and to logg it to a text file.
 
Imports System.IO
 
Private Sub port_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles port.DataReceived
 
Dim ReadText As String
Dim sw As StreamWriter
 
ReadText = port.ReadTo(vbCr)
 
Dim path As String = "C:/YourPath/YourOwnName.txt"
If File.Exists(path) = False Then
' If you are using Vista this will not work. Then you will have to create the path
' manually befor you can write to it.
' If path doesn't exist create a file to write to.
sw = File.CreateText(path)

else
 
sw = File.AppendText(path)
sw.WriteLine(ReadText)
sw.Flush()
sw.Close()
 
End If
 
ReadText = ""
 
End Sub
 

 
Sigurd Johansen
 
modified on Friday, November 6, 2009 1:07 PM

GeneralSimple and to the pointmemberWill Mather17 Sep '09 - 17:48 
This is good, straight to the point and readable Thumbs Up | :thumbsup:
Generalserial helpmembercamcplace21 Mar '09 - 23:31 
hi i need to communicate from serial
to check a cable continuity from one end to other
i want to send a string from pin2 and receive it from pin3
is your program doing this?
GeneralMy vote of 1memberSyed Javed13 Dec '08 - 17:56 
no code to download
GeneralRe: My vote of 1memberSigurd Johansen29 Dec '08 - 17: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 ArticlememberDonsw2 Dec '08 - 8:29 
This is a good article but you should probably go a little more in depth. Maybe a follow Smile | :) on article that explores threading and receiveing data in the same program.
QuestionBluetooth instead of serial port?memberMember 47016437 Jul '08 - 1:26 
hello Sigurd,
i read your article and it was very useful, im still new to this subject but really intersted so here is my question. can i communicate with external devices such as cellphones via bluetooth through a windows application?
please help
thanks and best regards
 
Ahmad
 
modified on Monday, July 7, 2008 8:20 AM

AnswerRe: Bluetooth instead of serial port?membergpraceman10 Jul '08 - 3:43 
I've used a Bluetooth device to wirelessly communicate with a serial device. The Bluetooth device driver created a COM port which I used with the SerialPort class. I don't know specifically about communicating with cell phones.
GeneralSerialPort Object Buggymembergpraceman30 Jun '08 - 18:40 
I found the SerialPort object in .NET 2.0 to be buggy. I've had threading errors after I close the port, issues with virtual ports for Bluetooth devices, strange characters showing up in the results from GetPortNames, port stops responding, and worst of all a known bug on Vista of unplugging a USB to Serial adapter after opening a port that will plain hang the computer.
 
Has anyone had problems using the serial port object in later versions of the .NET Framework? I'm wondering if these problems have been fixed.
 
Thanks,
 
Randy
GeneralMulti thread safememberoferebert12 Jun '08 - 2:44 
It is written in the MSDN that the SerialPort class is not thread safe so for my opinion because the DataReceieved event is called in a new thread you must protect the access to the serial port with a mutex to avoid read and write at the same time.
GeneralNeither open nor closedmemberMarceRos15 May '08 - 0:46 
Hi,
 
I'm learning to work with the serial port. It seems to be simple but I found out that sometimes (I assume it happens when I leave the program without closing the port) the port gets stucked and my next run won't be able to open it nor close it. Do you know what to do in that case?
 
Another question about your article. What does the WithEvents keyword do? I work with C# and I want to make sure I do the right thing.
 
Thank you very much,
 
Marcelo
GeneralRe: Neither open nor closedmemberSigurd Johansen16 May '08 - 9:21 
Hello Marcelo.
 
If you try to open the port from to programs you are not allowed to that.
 
The WithEvents means that it is able to handle a stream coming in on the port.
 
Sigurd Johansen
QuestionASP.Net?memberTechnoshaman2 Apr '08 - 0:57 
Thanks for this useful article. I'd like to know if I can do this on the web. I want to make a home automation system, and I want to be able to access my PC at home through the Internet using my PC at work. So there'll be a web page that'll be accessing my computer's serial port which works as a web server, and that computer will be connected a controller box I made via the serial port. So is it possible to access hardware through C# and ASP.Net? Would this work out? Thanks in advance Smile | :)
AnswerRe: ASP.Net?memberTechnoshaman6 Apr '08 - 5:24 
I guess I had to try and find out myself after all. It does work Smile | :)
GeneralRe: ASP.Net?memberSigurd Johansen6 Apr '08 - 10:04 
Nice. Smile | :)
GeneralI have a problem with your programmemberlinamavilla11 Feb '08 - 8:53 
hi!
 
I'm trying to communicate my pc with a pda hp ipaq hx2700 with windows mobile 5.0. I made the code you post in here making the pda the receiver and the pc the transceiver.
 
I have a problem because in the windows mobile 5.0 form, i can't put
CheckForIllegalCrossThreadCalls = False because it says it is not declared. Even if i declare the control class, it doesnt work.
 
I made the code without that line and when im gonna send, i have an error with the thread.
 
Can you help me please????
 
if you want, you could wite to me to linamavilla@yahoo.com
 
thanks.
 
Lina
GeneralRe: I have a problem with your programmemberSigurd Johansen12 Feb '08 - 5:09 
I have no experience with the mobile 5.0 form. Maybe you can use system.threading. Look at this link http://msdn2.microsoft.com/en-us/library/system.io.ports.serialport.aspx. Maybe it can help you. Smile | :)
GeneralNeed help ,How To Connect serial with Cach BoxmemberMujahid10 Feb '08 - 8:15 
Heloo my Teaher,,
Thans for your helping..
i need ur help << how to connect serail with Cash Box,,
i want this becus i have accounting program and now i want to open mony box when customer pay ,,
so wt is the code ,,give me example for it,,
thanx agine
this my email:
 
onesecret2020@hotmail.com
 
i am from Oman
Confused | :confused:
GeneralRe: Need help ,How To Connect serial with Cach BoxmemberSigurd Johansen10 Feb '08 - 10:51 
Hello
 
I have never tried this, but if your cash box is connected to a computer via a serial port I guess you have to sent a command to it using the port write statement. You have to find out witch caracter that will open the cash box. Here I assume that sending the caracter "a" will open the cash box
 
Port.Write(Chr(97) & vbCr) meaning send a and end with carrige return.
 
You can find a complete list of ASCII caracters on this address: http://www.asciitable.com Smile | :)
Generalneed help pls, reading from usb portmemberadnanmn23 Jan '08 - 19:54 
hi there,
we have a barcode reader, want to recieve its data through usb port,
how can we achieve this task in .net, which api should be used ?
waiting for reply ...
GeneralRequired Helpmemberkevinbhavasar10 Sep '07 - 0:45 
Hello sir,
i have to use PABX device with my C#.net application.
i found that using Serial port i can access the PABX(PBX) device but now for testing i want to some row data in text file.
i want to know in which format the device will send the data..
Thanks
Smile | :)
 
Kevin C. Bhavsar
MCA-SPU

GeneralRe: Required HelpmemberSigurd Johansen11 Sep '07 - 3:55 
I have only been working with Aastra PBX solution and they are using a Pocet adapter connected to the serial port and are using ATPC1 protocol to communicate.
 
Sigurd Johansen
Generalhelp me on transfer data between modemsmembernkcspecial19 Aug '07 - 1:14 
Hi,
to send data between modems i think as below:
 
from modem A send 1 message to modem B like that: "ATD123456" to request a connect.
Modem B Response "ATA" if it accepted.
 
after all, 2 modems can be direct sending data to another modem.
 
please help me.
thanks a lot.
Generalserial port usb adaptermemberrigidigi30 Jul '07 - 9:13 
will the .NET 2.0 serial port control work on a USB port with a serial adapter ?
GeneralRe: serial port usb adaptermemberSigurd Johansen31 Jul '07 - 9:36 
I have not tried this but I guess it will work if you are abel to find the port.
To find all ports on your PC you can try this code.
 
Dim ports As String() = SerialPort.GetPortNames()
 
' Find all avilable COM ports on the PC.
Dim port As String
For Each port In ports
ComboBox1.Items.Add(port)
Next port
 
You have to add a Combobox named Combobox1 to your project.
 
Hope this will help.
 
Sigurd Johansen
GeneralRe: serial port usb adaptermemberTorpedoke-be8 Mar '08 - 11:00 
Hello,
 
I have tried this but without any luck. I think the problem is that the system works with 2 different COMports (the comport of the USB converter and the comport of the modem). On my system the USB converter is com4 but the modem is com12. I can't send any AT COMMAND to com12.
 
Can anyone help me with playing a Wave-file on actief line?
 

regards,
 
Bart
GeneralRe: serial port usb adaptermemberrigidigi2 Jul '09 - 8:41 
I had no problem with using a usb to serial port adapter. Blush | :O
GeneralRe: serial port usb adapter [modified]membergpraceman30 Jun '08 - 18:27 
Yes, you can use a USB to Serial adapter. Just make sure you install the driver for the adapter, so it will create a COM port. Once the COM port is created, you can use it like a regular serial port. The COM port will exist on the computer as long as you have the adapter plugged in.
 
modified on Tuesday, July 1, 2008 12:43 AM

QuestionText filesmemberdb@Jax11 Jul '07 - 8:21 
can you show me examples of sending files thru the vb.net serial control? How to handle file names, sizes etc...
 
db
Questionc sharpmemberPushkar Joshi21 May '07 - 0:27 
how to write same code in c#?
 
please reply me
AnswerRe: c sharpmemberSigurd Johansen21 May '07 - 1:25 
Hi.
 
I must say that I don't know C# but there are many good converters on the internet.
I have tried this one http://converter.telerik.com/
and I got the following code in C#:
 

using System;
using System.IO.Ports;
public class Form1
{
SerialPort Port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
 
private void btnSendText_Click(object sender, System.EventArgs e)
{
Port.Open();
Port.Write(txtSendText.Text + "!%");
Port.Close();
}
}
 

 
using System;
using System.IO.Ports;
 
public class Form1
{
abstract SerialPort port = new System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
 
private void Form1_Load(object sender, System.EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
if (port.IsOpen == false) port.Open();
}
 
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
TextBox1.Text = (port.ReadTo("!%"));
if (port.ReadExisting.Length == 0)
{
ListBox1.Items.Add(TextBox1.Text);
TextBox1.Text = "";
}
}
}

 
Sigurd Johansen
GeneralRe: c sharpmemberPushkar Joshi21 May '07 - 18:07 
Thanks,
 
I wll try it and reply you.
 
Regards
Questionhow to dial a number with serialport?membermehrdadsh10 May '07 - 3:27 
tanks for your learning.
[i dont know english alotSigh | :sigh: ]
please tell me
how to dial a number with serialport?
Because this code not work:
serialport1.open();
serialport1.write("2105320AT D");
please write true codeRose | [Rose]
 
fsadfasdfas

AnswerRe: how to dial a number with serialport?memberSigurd Johansen14 May '07 - 20:24 
Try this
 
serialport1.write("ATD2105320" & vbCr);
 
Sigurd Johansen
GeneralRe: how to dial a number with serialport?memberVachanC29 Apr '08 - 20:50 
I am trying to comunicate with two ports. Actually with the use of third party control i had configured 2 ports ( com3 and com4 ). now i am writing/sending text to com3 it will shown on com4 text.. but here only first character is coming.. not whole text..
Sigh | :sigh:
i m not getting what to do.. we need to do this application with the using NULL Modem.
 
suggest if possible !!!!
Questionmessage arrived after port closedmemberTaoge8 Apr '07 - 17:58 
Hi, when i used the serial port in NET 2.0 to communitcae with a GPS receiver (the data arrived every second), it seems sometimes the data_received event fired after the serial port closed.
Any ideas?
 
Thanks
AnswerRe: message arrived after port closedmemberSigurd Johansen9 Apr '07 - 3:47 
Why are you closing the port?
 
Sigurd Johansen
QuestionIn WebmemberPanda197527 Feb '07 - 6:19 
In Web??? Work fine??
tk
GeneralThank youmembervmayzel24 Feb '07 - 9:42 

Generalevent objectmemberkuncung5 Feb '07 - 21:17 
Hi, I have problem with event in the communication on serial port, I mean we have a hardware, and the hardware send message . Does your source can do that?
GeneralRe: event objectmemberSigurd Johansen6 Feb '07 - 10:58 
I'm not sure if I know what you mean but you could try this.
 
Private Sub port_DataReceived(ByVal sender As Object, ByVal e As _
System.IO.Ports.SerialDataReceivedEventArgs) Handles port.DataReceived

TextBox1.Text &= port.readExisting
End Sub
 
Sigurd Johansen
Generalerror in using System.IO.PortsmemberMember #374662521 Jan '07 - 1:29 
Hi, im trying to send a string to IO port. By using .net 2003, but there is an error in using System.IO.Ports
the error is "the type or namespace "Ports" does not exist in the class or namespace "System.IO" (are you missing an assembly reference?)
thank you.
GeneralRe: error in using System.IO.PortsmemberSyed Muhammad Kamran23 Jan '07 - 0:49 
This is because the serial port support (System.IO.Ports namespace) is added in dotnet 2.0 (released in 2005)
GeneralCombine RD &amp; TD to form a loop to test this.memberSyed Muhammad Kamran16 Jan '07 - 23:42 
You can also combine pin2 and pin3 (RD & TD) of RS232 with a wire, to make a loop back. This way whatever you output to COM will become your input.

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

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