Home
Login / Signup
 di 

Serial Port Communication in C#

Serial Port Communication in C#

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

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

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

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

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

RE: Input for transmission

Hi ST,
You will have noticed in the beginning of the article that there is a section dedicated to the configuration of the serial port. I want to draw your attention to a particular line of code in that section:

serialPort1.PortName="COM1";

This line is where you specify which COM port you want to use (in this case it is COM1). If your computer has more than one serial port, you can search for the available names in the Device Manager and see there which COM name these ports use.

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...

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

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

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

"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

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)

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

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

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

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

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

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

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

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

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

RE: See if hardware's connected

Hi Wilco,
I am not a professional programmer, but in case the driver fails in using the write and read timeout properties of the class, I would suggest to implement a timer approach (C# can access windows timers with 1ms resolution). I am afraid, however, that this approach would lengthen download time when the device is connected, so you might want to get a more "software oriented" advice.

Regards,
Cristian

RE: Draw shapes

Hi Agnes,
I would suggest that you take the following approach. Read the image in some kind of a structure in C#. I have only used bitmaps before, and I would hope you do the same as the format is quite easy to read and interpret. Once ou do that, you can easily send the hole image, byte by byte, with the method described in the article. I do not know if this is the most efficient method, but it surely would work.

Regards,
Cristian

RE: Re: Draw Shapes

Hi Agnezz,
Sorry for the late reply.
My suggestion, is as follows. You may draw the shapes in Paint, under Windows XP. Paint can save in BMP format and you may save your shapes as a known file (for instance "shapes.bmp").
After that you may read that BMP file using a C# program, extract the useful bytes from it, and then flush these bytes via serial port, as indicated in the article. For ease of use, I would suggest to use monochrome bitmap only, because it has the simplest format and you can easily interpret the file in C#, if you are familiar with this programming language.

Regards,
Cristian

RE: Half duplex communication using c#

I am not really sure what you mean... the communication is half duplex by default, although the PC and the C# are capable of reading/writing bytes simultaneously.

If you are referring to serial protocols with hardware or software shaking then I would only suggest that you google for it in order to find out how exactly to assert/deassert the signals. Fortunately the class described in the article allows for asserting/deasserting the CTS/RTS signals.

Regards,
Cristian

Who's online

There are currently 0 users and 15 guests online.

Recent comments