Spanish Italian
14317 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

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

Who's new

  • alrica
  • andresnovak
  • digdigdug
  • Taggart
  • gb2012
  • jlw60019
  • abcd123456
  • deepakbagde
  • rod.rahul
  • dodi

Who's online

There are currently 0 users and 13 guests online.