Spanish Italian
17434 Users    

Serial Port Communication in C#

  Download PDF version of the Article

The serial port is a serial communication interface through which information transfers in or out one bit at a time.
A quick search on Google reveals that there are a lot of free serial port monitor applications available for PC users. However, what these applications lack, is the possibility of controlling the serial port in a direct manner. They are generally good “sniffers” but they do not allow the user to actually write to the serial port or control any device attached to it. The applications with the write capability encapsulated are not for free, and the cheapest costs about 50 Euro – a great deal of money taking into account how easy it is to make a personalized application.

This article will show how it is possible to build such an application using the C# environment. It is not intended to be a C# tutorial, but to teach a user who has basic knowledge of C or C# to integrate serial port control in one of his applications.

For the example application, I have used the SharpDevelop development environment which includes a C# compiler. This is an open source IDE which takes up very little space on your hard drive and can be a good alternative to users who do not want to install the gigabytes of Visual Studio on their PCs for a simple serial port application.

Once you have downloaded and installed the SharpDevelop environment, create a Windows Application project (solution) called SerialPort:

 


Once you have created the application, display the windows form that was automatically created (by clicking on the “Design” button at the bottom of the screen) and unroll the menu available under “Components” available on the left-hand menu:

 

You will notice that one of the components available here is the one called “SerialPort”. Pick that component and drag&drop it over the surface of the form on the right. This will add the component to your project. The object that is created is called “serialPort1” and it will be used to access the serial port. To be able to use this component, however, you need to add at the beginning of your code the directive for using the System.IO.Ports namespace, as this is not added by default when you create the solution:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;

Once this is done, create a regular button on the surface of the form, call it “button1” and change its label to “Write”. Then double click on it in order to create the function that will be executed when the button is clicked.


In this function we will perform several tasks. The first one is to configure the baud rate, COM port, number of data bits, parity and stop bits of the communication:

//configuring the serial port
serialPort1.PortName="COM1";
serialPort1.BaudRate=9600;
serialPort1.DataBits=8;
serialPort1.Parity=Parity.None;
serialPort1.StopBits= StopBits.One;

Next, before writing to the port, it needs to be opened:

//opening the serial port
serialPort1.Open();

Please note that if the COM1 port is already used by an application, you will get an error message when this instruction is executed. Alternatively, if you open the COM1 port with your C# application and then fail to close it, any other application trying to use it will not be able to do that.

OK, it is now time to write to the serial port:

//write data to serial port
serialPort1.Write("ABC");

When this instruction is executed, three bytes are sent to the serial port: the ASCII code of “A”, the ASCII code of “B” and the ASCII code of “C”.

Once the write operation is performed, you must not forget to close the port:

//close the port
serialPort1.Close();

So, as a summary, all the code that makes up the body of the function should be:


void Button1Click(object sender, EventArgs e)
{
//configuring the serial port
serialPort1.PortName="COM1";
serialPort1.BaudRate=9600;
serialPort1.DataBits=8;
serialPort1.Parity=Parity.None;
serialPort1.StopBits= StopBits.One;

//opening the serial port
serialPort1.Open();

//write data to serial port
serialPort1.Write("ABC");

//close the port
serialPort1.Close();

}

Now you have a broad path open in front of you, as you will be able to write your own customized applications that can send any data to any device attached to the serial port. The above code is also compatible with USB to Serial converters, provided that their drivers work by emulating COM ports.

Read the Italian version: Comunicazione Seriale in C#

C# and Serial Port.

Slinky, but what about receiving a string.....perhaps next blog ?
By the way, I'll give SharpDevelop a try, it seems worth it.

RE: C# and Serial Port

Hi Frabs,
What does "slinky" mean? I looked is up and found out it was a spring toy, but I do not really understand what you wanted to say...

Anyway, regarding the reading of bytes from the serial port: I didn't really detail this, because there are literally loads of freely available applications out there which perform the function of serial port sniffing and displaying, in any format you would need.

However, in case someone does want to do this in C#, the serialport class available, which is used in the above example provides several methods. To read bytes, you could use any of the following:

serialPort1.Read(byte_buffer,0,10); //this will read 10 bytes from the serial port and insert them starting with index 0 in a byte array called "byte_buffer", which has to be declared above


received_byte=serialPort1.Readbyte(); //this will read one byte from the serial port, and store it in a variable called received_byte


received_char=serialPort1.Readchar(); //same as above but reads a char


serialPort1.Readline(); //reads characters from the input buffer until the NewLine character is encountered; returns a string

Please pay attention though that the usage of all these functions is somewhat...tricky. In case you call any of these functions and no byte is available in the input buffer of the serial port, your application will appear to hang, and it will do so until either you kill it or the number of expected bytes (or at least one byte, depending on which of the above you use) is finally transmitted by the peripheral connected to the serial port of the PC.

There are ways of making the application work somewhat like in an "interrupt" manner, using the C# concept of "events" which trigger a function when bytes are available in the input buffer of the serial port, but although I am familiar enough to use them, I lack the theoretical notions of C# required to thoroughly explain these.

Regarding your thoughts of giving C# a try... I congratulate you! As you may have noticed, I am no C# expert myself, but for the hardware engineer who sometimes wants to format some text/binary files, to extract some data, to make a simple GUI...or to write some bytes to the serial port, it is a great tool. And this sharpdevelop compiler (not only free, but also open source, which is great!) only asks you to install a small amount on your PC (not hundreds of megabytes, like other IDEs)

Regards,
Cristian

C# and Serial Port.

Hi Cristian, nice to meet you here on YOUR ELECTRONIC OPEN SOURCE.

Slinky sounds like sexy (It has been even used on one of H.P.Books).

Thanks for the detailed explanation about receiving data from the serial port, though I think an event based module suits better my usual kind of program. (That's what I do with VB).

Well actually I was considering C# AND SharpDevelop that, quoting your own words is "not only free, but also open source, which is great!".

At the moment I'm still satisfied with VB for Visual Programming and VC++ for writing some dlls. Don't get me wrong, I'm not a Windows supporter and I'm not a kick ass high level programmer, I prefer stacks, ADC, I2C, Timers and watchdogs, but sometimes I must develop test benches or datalogger for my embedded projects, and that's where my "high level" programming comes handy. Perhaps getting a little acquainted with C# could let me drop VB and VC++, using one only language developed on an Open Source project.

Cheers
Frabs

asp.net connection with serial port

Thank you very much for code to transmit the data but if i want to receive data from this form please tell me what to do

RE: asp.net connection with serial port

Hi,
Regarding your question, please read the comments to this article as other have asked this before. In one of the comments above I actually detail a method for receiving data via the serial port. I hope it is what you are looking for and that it will work fine for you.

Best regards,
Cristian

How to access usb/ serial ports on the internet

Hi,
Thank you for good hint for ports. But my question is , how may i access usb/ serial ports over the internet. Can you tell me please?

Thank you.

RE: How to access usb/ serial ports on the internet

Hi GM,
It can be done but it is not trivial. And it is not very clear how you want to do it. Using a browser? Using a C# application? Or what? You should be more specific and somebody in this community might help you...

Regards,
Cristian

c++

please if you can help helpe me

RE: c++

Hi Abdale,
I would gladly help you if I could, but for that, I need to know... what is it exactly that you need. Is it code to access the serial port from C++? I think the latest .net framework maps the "outportb" instruction, in order to make things compatible to the old programs written in Borland C++, but I am not 100% sure.

Regards,
Cristian

Send AT command on GSM modem/Phone

Hi,
Dear i want to know that how i send the AT commands on GSM modem or mobile. Can i write the the AT commands in string that is send to port or u have any other method to send AT commands. plz guid me...
And also tell me that what mobile is best replacement of the GSM modem.
I am wait 4 ur answer.
umer_ufm@yahoo.com

RE: Send AT command on GSM modem/Phone

Hi UFM,
I would rather post the answer here for everybody to benefit from it, rather than writing you an e-mail.

So in short, it is perfectly possible to use the above code and write the AT commands as strings. I am not 100% familiar with these commands, and it might be that you need to append a termination character to each command (like 0x0A or 0x0D, depending on the phone).

I cannot tell you which the best mobile replacement is for the GSM modem. Guess it all depends on how much such a phone would allow you to do with AT commands.

Regards,
Cristian

Correction

Please consider this page first: http://www.codeproject.com/KB/system/rs232ThreadSafe.aspx

Your program would fail if you tried to access the serial port from a button, that's why people use thread safe calls...

Emrah

-----------------------------------------------------

Enslaving machines to free the mankind...

RE: Correction

Hi Emrah,
You are somewhat right. But only partially. Please note that the method described on the web page that you provided the link for, is actually the event driven method for reading the bytes from the serial port. Although this method is mentioned by myself and Frabs in the above comments, I have not described it, nor provided any source code for it. If it is used, the programmer does indeed need to take a little care about threading and other aspects of high level programming.

However, the methods for reading from the serial port that I have detailed will easily work without any complications, and you can directly assign the strings returned by the methods to textbox objects.

Regards,
Cristian

Then you taught me another

Then you taught me another way to access the serial port, thank you :)

Regards,
Emrah

Enslaving machines to free the mankind...

I lil help please

I have written a code in C# that helps me accept dome data from a test hardware which sends numbers in bytes when i press a button in the hardware.. But the code in my computer times out before I read the data. Also if i set the timeout to infinity. No data is recieved..

Please guide me. A source code to read such data will be highly appreciated. I've treid around 8 console and two variants of form codes but none of em are actually solving my problem.

Please help!

RE: I lil help please

Hello Sushi,
Can you confirm the correct functioning of your hardware by using the windows embedded hyperterminal? Can you see the bytes coming in?

Regards,
Cristian

Hi Cristian, I am using

Hi Cristian,

I am using Visual studio 8, i want to read the data from the serial port, i am actually interfacing pc and microcontroller.the data from the controller is commin to the serial port, from that i need to read and display it on the front end, the GUI is ready but data is to be read. does anyone knw as to how to do this? pls help

RE: Hi Cristian, I am using

Hello, whoever you are.
In cases like this, I always recommend using a proven and definitely fault-free method of checking for incoming data: the hyperterminal. Please use hyperterminal to confirm data is coming in to your PC (not only the scope).

Reading data from the serial pot using Visual Studio 8 applicatios is highly dependent upon the serial port access method you use. In case it is the method described n this article, please have a look at the second comment on this article, where I detail a way to do it.

Hope this helps!
Cristian

Thank you for the info

Thank you for the info cristian, yes i also agree that hyperterminal is the best way of checking the incoming data, actually that has already been implemented and tested. The data is coming till the serial port, since there is an option in visual studio where the data can be read from the serial port i wanted to implement the same, i am not finding any sort of tutorial regarding this. If u can suggest me a way to do it, it would be of great help.

Thanks in advance.

Microsoft C# System.IO.Ports.SerialPort

The way you do is the same I did for years, but I encountered some devices, that simply do not read anything at all when C# Serial Port class is used while you can perfectly read incoming data when using Microsoft HyperTerminal. I just encountered another case right now as I did 3 years ago. It seems that this did not change much over the last years.
I do not want to start complain about Microsoft, but I think that it is reasonable to be catious when you use their code and do not expect to work properly or at all. Try to manipulate some bitmaps. Microsoft classes are slow!!!!!!
In this case it is really necessary to unlock the pointer functionality. It is like returning into a pure C/C++, the conveniance if C# is definitely lost.

RE: Microsoft C# System.IO.Ports.SerialPort

Hi Stupido,
Can you give me some example of such devices? What you say is really news to me, although I realize that one of the previous posters in this thread might be experiencing the same.
If you told me what device this is, I might be looking if we have it here and I would investigate what does not work.

Regards,
Cristian

I can not read data from serial port

Hi guys

can any one help me to read from a serial port, i can send data from the pc to the pin pad but when i try to send data to the pc from the pin pad they are not comunicating and i dont know what to do . If anybody knew how to read data from the pin pad help out.

Hellen

"pin pad" serial port

Hi Helen,
I presume the "pin pad" is a device with RS-232 communication capabilities, right?
If this is the case, my recommendation is to always test your hardware with a known and proven software tool, like for instance the hyperterminal. Turn on and cofigure the hyperterminal, and you should see on the screen the hex values send by the device connected to the serial port. Make sure the correct COM port is selected and the correct communication protocol parameters are all in order (baud rate, data bits, stop bits etc.)

Regards,
Cristian

"pin pad" serial port

Hi Cristian,

Thank you, it works and i can read the hex from the pin pad and i converted to unicode.

Helen

Serial Port Communication in Excel (VBA)

Another great article about Serial Port communication.

"The purpose of this article is to demonstrate how you can perform serial port communication in the VBA (Visual Basic Applications - script editor included in any typical Microsoft Excel distribution) but without using the MSComm control or any other third party add-on or ActiveX."

Serial Port Communication in Excel (VBA)

Accessing Serial port Remotely

Hi guys,

I try to access my serial port device remotely, pls help.

Ronald

is it possible?

sir, is it possible to pass a value to a hardware using the serial port tool?

ahhmm i will appreciate your help..

im doing my thesis and i have to send signal to display the score of contestant into

the LED using the usb port, thnks in advance..

RE: is it possible?

Hi vigz,
To answer short: yes, it is possible. I am a little confuzed though, on your approach. Do you want to use the USB port or thephysical serial port of the PC? If you want to use the serial port, you can surely use the C# example in the article. If you want to use the USB port, you can also use thei c# example, provided that you use a USB-to-serial port converter that comes with Vicrtual Com Port (VCP) drivers. FTDI makes a few of these ICs and they work pretty neat from C#.

Regards,
Cristian

Is there any way

Hey guys,

I wrote an application which send and receive data from a pinpad and i start testing the application, when i finised testing the on my computer, I upload it to the server machine to do another test but when I run the application from client computers it does not recognize the pin pad, but when I run the application from my computer it works properly. My question is that is there any way I can access the pin pad remotely?

Thanks

Victor

Hi, It is Victor again, pin

Hi, It is Victor again, pin pad is a device with RS-232 which use serial port

Thanks again

Victor

RE: Hi, It is Victor again, pin

Hi Victor,
Can you let us know where do you connect the pin pad device when you run your application from the client computer? Is the pin pad connected to the server or to the client computer? I am not really sure which serial port is accessed this way, although I would firstly guess it should be the serial port on the client PC.

Regards,
Cristian

Pin pad

Hello Christian,

Sorry for not responding sooner,I connect the pin pad to the client computer, What i would like to do is ran the application from server and i have about 20 pin pads which will be connected to client computers, and i also want to locate the client computes in different places of the building.

Thanks

Victor

RE: Pin pad

Hi Victor,
Unfortunately I do not really have any idea why it would not work. I would say that given the circumstances you decribe, even if you call the application from the server it should be the serial port of the client computer that gets accessed. However, I am no guru in C# and I might be wrong here. Hopefuly it will be somebody with more knowledge in this area that will enlighten us.

Best regards,
Cristian

RE: Pin pad

Hello Cristian,

Thank you for your help, do you think if i use socket programming does it help? maybe by assigning IP Address and PortNo.

Thanks

Victor

RE: Pin pad

Hi Victor,
Unfortunately I am acquainted only marginally with socket programming. I remember doing something with "data socket" in LabView a few years ago, but that's about it. From what I remember, I would not think this would be a solution to the present problem, but I guess programming it yourself is for free...

Regards,
Cristian

Pinpad data communication

Hi Victor,

I am a software engineer who is currently working on POS device integration and I am currently working on the pinpad part.

It has come to my attention that you succeeded in implementing a pin pad communication program with pc. Is your program only using serial port library from .Net? How do you encrypt and decrypt the data from and to the pinpad? Do you have to install specific driver for the system to recognize the pinpad you plugged in?

I tried writing a program that sends data(in my case a string) to the pinpad, the pinpad shows that it is receiving data, but the response it give back is not suitable at all. Can you give me some guidance as to how do we ask the pinpad to perform specific operation such as accepting pin from users?

Thank you for your attention and your help will be very much appreciated because I've been stucked with this issue for days without any improvement.

Regards,

Andika

RE: Pinpad data communication

Hi Andika,

To answer your questions point by point (sinc victor des not seem to be around):

1. All you need to do serial comunication in C# is the serial port library from .NET. You also have to install the .NET framework on your PC, but that is transparent

2. You do not need to install any additional divers for any type of serial communication

As a general advice, I suggest that in order to see if you own code is wrong, you should take an existing application that does serial port communication (like hyperterminal, for instance, although it is rather not very flexible; or tera term would be another choice) and see if the commands you send do get the expected answer.

Regards,
Cristian

Pinpad data communication

Hi Adika,
Sorry for not replaying for your question. I know it is late but if it helps, yes I use a serial port library from .net. And the pin pad itself has an encryption and decryption algorithms ( just the user enters normal number like 1234 and the pin pad itself encrypt it to store to the database). Yes you have to install a driver for the system to recognize the pin pad after you install the driver go to device manager and you will find the com no for that specific pin pad.

If you have any question don’t hesitate to ask and I able to access the pin pad remotey.

Regards,

Victor

AT command

hi
i have a question about sending at command. if i want to send the following command :ATD 00000
which dial a a mobile number, i should send the hexdecimal of letters A,T and D. in other word the data send to the gsm modul by the fuction write should be 0x41,0x54,0x44 ?
if any one can post an example of an at command send using the c# lang i will be very thanks.
Reagards

RE: AT command

Hi man,
If you follow exactly the steps described in the article, you might want to replace the

//write data to serial port
serialPort1.Write("ABC");



instruction with:

//write data to serial port
serialPort1.Write("ATD 00000");



I believe this should do it. Of course, you can also use your approach, but the easiness of the AT commands resides exactly in giving the user the possibility to use ASCII strings, so you would do it more complicated than necessary.

Good luck,
Cristian

c#

but it not work for long time

i want that by pressing write button it write and when i press stop button it should display messege that port is closed............

RE: c#

I am afraid you will have to give me more details about what you are trying to do. Are you the same poster of the "AT Command" message? If you want to close the port upon pressing a button, you should simply create a button just like the "Write" button is exemplified in the article and then add the simple code:

//close the port
serialPort1.Close();

Hope this helps...

Cristian

Is there a library in C# which works for USB

Hi All,

I wrote a program for pin pad using serial port libraries and it work properly but when i changeed the cable to USB it does not send or receive data to the pin pad. Is there any USB library in c# which work the same as serial port? If there pls let me know and a sample code is very advantagous for me.

Thanks

Ruth

RE: Is there a library in C# which works for USB

Hi Ruth,
Are you talking about a USB-to-RS232 converter cable? Because if you are, then, the code above should work. I have specifically tried it with FTDI chips (FT232RL, specifically).

If you are talking about a plain USB cable betwen the PC and a potential USB interface of the pin pad, then you need special code to communicate via USB.

Let m know wht your situation is.

Regards,
Cristian

Hi Cristian, At first i

Hi Cristian,

At first i wrote the code for USB-to-RS232 converter cable, like you said the above code work perfectly but now i connect the plain USB cable to the PC and it is not working.

Thanks,

Ruth

RE: Hi Cristian, At first i

Hi Ruth,
As I wrote above this is totally expected. USB is a totally different protocol from UART, this is why USB-to-Rs232 converters do exist actually. Starting to write code for USB communication is not trivial, however the most basic pre-requisite in this case is for the pin pad to allow connection to an USB port of the PC (which I doubt it does, in case it is specified for RS232 communication only).

Regards,
Cristian

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
10 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.

Who's new

  • christiank79
  • agabor
  • fabriziopd
  • irenix
  • pepershoe
  • raghun14
  • andreaspousette
  • rilhyk
  • thientruong
  • snaku

Who's online

There are currently 0 users and 33 guests online.