
In today’s programming tutorial, I will describe some basics about how we can perform serial port communication from our C#.NET applications. Serial communications can be done either directly to a physical serial port connected to the computer or via a USB-to-serial converter interface. If the device requires a serial port and your computer doesn’t have one, you can easily use such converters.
This type of communication isn’t as easy as other similar tasks, such as working with a logic drive on a computer via c#, and requires the use of a specific communication protocol.
One exciting thing that you might need to remember is that when the physical serial port is being used, it doesn’t have any PID or VID. But if you are using a specific type of device that facilitates this kind of communication via USB interface, you can retrieve their PID/VID respectively and communicate accordingly. .NET has a very useful internal class that can make this kind of communication very easy and efficient.
Let’s have a look at them.
Retrieve List Serial Ports:
OK, let’s first see whether we can detect the serial ports from within our application. As a prerequisite, you need to make sure that, while the application is running, the Windows user must need to have access to the ports. The following C# code examples will return a list of Serial port names connected to the computer:
public List<String> GetAllPorts()
{
List<String> allPorts = new List<String>();
foreach (String portName in System.IO.Ports.SerialPort.GetPortNames())
{
allPorts.Add(portName);
}
return allPorts;
}
Code language: PHP (php)
Using WMI query:
It is enough for further processing. .NET can understand where to communicate via the port name in strings like “COM1,” “COM2,” etc.
The following code snippet will work similarly to the one given above, but it makes use of core WMI and returns a list of Management objects:
private List<ManagementObject> getAllComPort()
{
List<ManagementObject> ports = new List<ManagementObject>();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " +
WIN_SERIAL_OBJECT_NAME + ""))
{
foreach (ManagementObject serialPortObj in searcher.Get())
{
ports.Add(serialPortObj);
}
}
return ports;
}
Code language: PHP (php)
Open Or Close Serial Ports:
Well, as have now been able to get the list of ports, now we can start communicating. The first step to start serial port communication is to open the port, then send/receive necessary data, and finally close the port(s). Let’s see an example of how we can open and close ports:
System.IO.Ports.SerialPort myPort = new System.IO.Ports.SerialPort("COM1");
if (myPort.IsOpen == false) //if not open, open the port
myPort.Open();
//do your work here
myPort.Close();
Code language: JavaScript (javascript)
Read/Write Data via Serial Port Communication:
OK, now we can start communicating in real life. However, it is very important that you have prior knowledge of what kind of data the connected device is expecting. You will need to process their response as well to understand what they are saying. For this, you will need the corresponding firmware API command lists. Here, I will give a simple prototype of how the send/receive data workflow will be:
using System;
using System.Timers;
public class CommTimer
{
public Timer tmrComm = new Timer();
public bool timedout = false;
public CommTimer()
{
timedout = false;
tmrComm.AutoReset = false;
tmrComm.Enabled = false;
tmrComm.Interval = 1000; //default to 1 second
tmrComm.Elapsed += new ElapsedEventHandler(OnTimedCommEvent);
}
public void OnTimedCommEvent(object source, ElapsedEventArgs e)
{
timedout = true;
tmrComm.Stop();
}
public void Start(double timeoutperiod)
{
tmrComm.Interval = timeoutperiod; //time to time out in milliseconds
tmrComm.Stop();
timedout = false;
tmrComm.Start();
}
}
public void SendReceiveData()
{
byte[] cmdByteArray = new byte[1];
SerialObj.DiscardInBuffer();
SerialObj.DiscardOutBuffer();
//send
cmdByteArray[0] = 0x7a;
SerialObj.Write(cmdByteArray, 0, 1);
CommTimer tmrComm = new CommTimer();
tmrComm.Start(4000);
while ((SerialObj.BytesToRead == 0) &amp;amp;&amp;amp; (tmrComm.timedout == false))
{
Application.DoEvents();
}
if (SerialObj.BytesToRead &amp;gt; 0)
{
byte[] inbyte = new byte[1];
SerialObj.Read(inbyte, 0, 1);
if (inbyte.Length &amp;gt; 0)
{
byte value = (byte)inbyte.GetValue(0);
//do other necessary processing you may want.
}
}
tmrComm.tmrComm.Dispose();
SerialObj.DiscardInBuffer();
SerialObj.DiscardOutBuffer();
SerialObj.Close();
}
Code language: PHP (php)
The first thing we are doing here is discarding existing buffers, if any. Then, we will write an array of bytes to the port. This array can contain several hex values to represent a single command. Here, I have used one. After writing, and before you start reading the response, it’s always good to wait for a while, thus adding a slight delay, which helps to make up the time required between receiving and sending a reply for the device. At this time, Windows normally ques your work instructions and sends them to devices. But it may not happen because of CPU scheduling issues, etc. So, it is better to check whether or not any response came. If not, force Windows to perform this action now using the ‘Application.DoEvents()’ command statement.
References:
To work more deeply with communication and troubleshooting, you will need to study Microsoft’s official documentation on the serial object class carefully.
Hope this small tutorial on serial port communication with c# will be helpful to you to some extent. Let me know if you want some more similar tutorials or have any questions. Happy coding :).
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
Thank You Very Much For This tutorial
I got The New Idea & Concepts To Connect Serial Port
Its Realy HelpFul.
Sandip Shinde
NetSolution Technogies
how to read com port with using .net?
i need code to read data from atmel 4 pin microcontroller and write data on it again it is on the board
i like this blog, lot of big things described in light manner..!!
Maybe you should write a little bit about the SerialObj and tmrComm, where did they came from ??
Hi, thanks for noticing. tmrComm should have been shown to be initialized earlier. It is of type “CommTimer” as given in the code. Also “SerialObj” is of type SerialPort
Were is the CommTimer type found??
Hi Phil, I am not sure what is your actually question is. However, there was a small issue in the c# code example as initialization of “tmrComm” variable of type “CommTimer” wasn’t done in proper way. I have modified it. But, if you have something else question, please explain.
Thanks for the reply, my question is what assembly is “CommTimer” in?
Oh yes. I very much appreciate your catch. I thought I did shared it too, but didn’t, just realised after your question. Thanks a lot. I just added that class definition as well. Hope this helps. Please let me know if you still having any issue/have more feedbacks.
Thanks very much for the additional code, its working now 🙂
Hi Rana,
Do you have a complete code rather than bits and pieces? I am trying to understand how you are calling SendReceiveData. Can you please revert with the entire code please. Unfortunately i am new in C#. Any help will be greatly appreciated.
Thanks
thanks a lot for the tutorial.Can you make a tutorial or guid me to writing device drivers for serial port devices?
You mean you want to write driver software for serial port accessible devices? If so, you must need to have the command set that the device accepts and what it replies in response. If you got that, you can even use this article to send and receive data.
WIN_SERIAL_OBJECT_NAME Where is this command form can’t find it sorry I’m a Nube. Is it a Placeholder or a Proper .Net Command
That is simply a constant where you will have to mention your target object name. Hope this helps.
here is an alternative explanation, with code and you can download to make tests
ps:if you have only USB ports you can “virtualize” a serial port using the USB port:
– connect with an adapter to de USB port
– install te drivers and select a new created virtualized serial port (in my case COM3)
– uninstall the printer in the control panel printer window (quit device)
– is very important to quit the printer because if not, the port is taken by the printer and when you’re trying to open the port will be an error (“The given port name does not start with COM/com or does not resolve to a valid serial port”)
try it. it works great.
http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx%5B^]
not helpful, there are a lot of simpler ways to do this
There could be, for sure. Why don’t you just share some way/link, I will be happy to share with my readers.
Can we use serial port communication with AVR micro-controller?
Not sure about that, haven’t tried yet.
I am getting error at “Applicatio.DoEvent”. how to resolve it?
I am using WPF
You can try with this solution, this might help: http://stackoverflow.com/questions/19007288/alternative-to-application-doevents-in-wpf
Can you to get punch in and out data from PunchMachine using above code
showing error::: ‘Timer’ is an ambiguous reference between ‘System.Windows.Forms.Timer’ and ‘System.Timers.Timer’…what to do plz help
How can I send binary file to the GPS device via serial port communication, want to update firmware of device using C#..
can you please reply me I need your help..
Regards,
Abhi
Hello Md Ali Ahsan Rana
my problem is that i trying to get input from Weight machine ( Connection= USB, Company=DYMO Endicia Postage Technology,Item No=ES-7500UBLK) in web application in asp.net.Please give me any code if you have for this.
Thanks in advance
Please help me . Does it need all ping or which pings need mainly to receive and send data from computer and other device.
hi . i m working with rfeid serial module , i want to use with it .net apllication i want to know that which approach is better ?
1 : to open serial port when software is running at startup
2: or open serial port when needed after communication close it
please reply .
Its always wise to make connection on demand(when needed) always without unnecessarily keeping a connection open, unless some exceptional cases.
then why sometimes it give error that serial port cannot be opened after several communications ?
Hi i have a problem with communicating with a serial scale. If i use ReadLine() i get no values, but if i use ReadExisting() i get a constant string for e.g. 40 would show as 40404040404040
How do i get around this?
I have problem, it seems like i have nothing to read, it is always stuck here
while ((SerialObj.BytesToRead == 0) && (tmrComm.timedout == false))
I am using METEX ME 32 prahistoric device, which measures temperature, voltage.. i have been using using USB converter, it’sturned on, and shows value on it’s screen, but program doesnt seen it.
aoa . i have a project in which i draw in drawing and same thing is drawn in glcd. through serial communication ,
byte[] buffer_2_send = new byte[1];
byte data_2_send = 0;
data_2_send = Byte.Parse(textBox2.Text);//this way you will get the value 12 in your variable
//we will use a buffer because the serial_port.Write takes either a string or a buffer of data
buffer_2_send[0] = data_2_send;
MessageBox.Show(“” + buffer_2_send + ” ” + buffer_2_send.Length);
serialPort1.Write(buffer_2_send, 0, buffer_2_send.Length);
i basicaly send 12 or like this values on microcontroller
but at recieving side i cant recieve respective value so plz guide me
Thank You Great Work
If you have an application that writes to a serial port device through a USB adapter, and the application is hard-coded to use COM port 5, is there anything you can do so that moving a laptop that uses this application from one docking station to another will NOT cause Windows Plug and Play to assign a different COM port based on the VID of the second USB-to-serial device being different from the VID of the first USB-to- serial adapter?
The docking stations both use the same peripherals, all plugged into the same USB ports.
The users of these laptops don’t have administrative rights to change the COM port in Device Manager.
Some USB-to-serial adapters advertise ‘COM port retention’, but that only seems to make the laptop use the same COM port for the exact same USB-to-serial adapter (the very same one, not just one that ‘seems’ the same but has a different VID) each time the laptop is connected to that device.
Thanks,
hey.. i need to communicate with devices that are connected by usb in wpf application… can you please guide me in this.. i am newbie in this..
what assembly is “CommTimer” in?
System.IO.Ports.SerialPort myPort = new System.IO.Ports.SerialPort(“COM4”);
if (myPort.IsOpen == false) //if not open, open the port
myPort.Open()
error message:
A device attached to the system is not functioning.
thanks i ask you a question i have a software well working in serial port can i use this software over usb port without any change in software
Hi.excuse me for my bad English!I want to write a program in c# that print papers with Olivetti pr4sl slip printer.but I can’t communicate with this printer and don’t know how to send text directly to this printer in my program.can you help me for this?this printer connected to my pc with COM port and doesn’t have any driver.thanks
Good afternoon all,
I need to develop a LIMS(Lab integrated management system) using Asp.net and it should be bidirectional communication that means need to send the data of patient with tests,sample id,date etc to machine and need to get the results back to the computers from machines.Please help me how i can do
By SerialObj.DiscardInBuffer(); you are flushing data in the Serial Port buffer only. Data still remains in the base stream object, which will pop up on reading the port.
So, in addition, do SP.BaseStream.Flush() to really get rid af all existing data
Can u tell me how to code a program to record the exact time when serial port data arrives in visual studio in C#
I am getting error at “Applicatio.DoEvent”. how to resolve it?
Hello Can this code work with laboratory device????
where are these codes used? I am new to this. Are these codes used in MS-Dos ?
In what environment are these codes run in? I tried visual studio but get all kinds of errors. Are there included files that do not show in the codes documented here? Is this C#?