CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Programming How To Work With C# Serial Port Communication

How To Work With C# Serial Port Communication

Rana Ahsan February 7, 2013 46 Comments


 How To Work With C# Serial Port Communication    

In today’s programming tutorial, I am going to describe some basics about how we can perform serial port communication from our C#.NET applications. Serial communications can be done via either direct to physical serial port connected to the computer or via a USB to serial converter interface. If the device do require a serial port and your computer don’t have any, you can make use of such converters easily.
Belkin USB Serial Converter

This type of communication aren’t as much easy as other similar tasks such as working with logic drive on computer via c# and need use of specific kind of communication protocol.

One interesting thing that you might need to remember that, when the physical serial port are being used, it doesn’t have any PID or VID. But if you are using any specific type of devices which facilitate this kind of communication via USB interface, you can retrieve their PID/VID respectively and communicate accordingly. .NET has a very useful internal classes which can make this kind of communication to be very easy and efficient.

If you want your laptop to live a long life you’re going to need to get rid of the heat inside of it, Laptop AXS can help you choosing a good cooling pad for your laptop and avoid this issues.

Lets have a look into them.

Retrieve List Serial Ports:

OK, lets 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;
}

And it is enough for further processing. .NET can understand where to communicate via the port name in string like “COM1”, “COM2” etc.

Using WMI query:

The following code snippet will work similarly as the one given above, but it make use of core WMI and returns a list of Management objects:

private List<ManagementObject> getAllComPort()
{
     List<ManagementObject> objct = new List<ManagementObject>();
     using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " +
     WIN_SERIAL_OBJECT_NAME + ""))
     {
         foreach (ManagementObject serialPortObj in searcher.Get())
         {
             objct.Add(serialPortObj);
         }
     }
     return objct;
}

Open Or Close Serial Ports:

well, as have now been able to get the list of ports, now we can start communicating. First step to start serial port communication is to open the port, then send/receive necessary data and finally close the port(s). Lets see an example 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();

Read/Write Data via Serial Port Communication:

OK, now we can start doing the real communication. However, it is very important that, you have prior knowledge what kind of data the connected device is expecting. and 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 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) && (tmrComm.timedout == false))
      {
          Application.DoEvents();
      }
      if (SerialObj.BytesToRead > 0)
      {
          byte[] inbyte = new byte[1];
          SerialObj.Read(inbyte, 0, 1);
          if (inbyte.Length > 0)
          {
              byte value = (byte)inbyte.GetValue(0);
              //do other necessary processing you may want.
          }
      }
      tmrComm.tmrComm.Dispose();
      SerialObj.DiscardInBuffer();
      SerialObj.DiscardOutBuffer();
      SerialObj.Close();
}

First thing we are doing here, is discarding existing buffer, 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 add a slight delay, which helps to make up the time required between receiving and sending reply for the device. In this time, normally, windows do ques your work instruction and sends to devices. But, it may not happen because of CPU scheduling issue etc. So, better to check whether any response came or not. If not, force windows to perform this action now by ‘Application.DoEvents()’ command statement.

References:

For working more with deep communication and troubleshoot, you will need to study carefully the Microsoft’s official documentation on serial object class.
Hope this small tutorial on serial port communication with c# will be helpful to you in some extent. Let me know if you want some more similar tutorials or have any questions. Happy coding :).

Related

Filed Under: Programming Tagged With: .net, c#

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. Sandip Shinde says

    February 21, 2013 at 4:34 am

    Thank You Very Much For This tutorial

    I got The New Idea & Concepts To Connect Serial Port
    Its Realy HelpFul.

    Sandip Shinde
    NetSolution Technogies

    Reply
    • naseema says

      May 13, 2015 at 11:59 pm

      how to read com port with using .net?

      Reply
    • hussainkhanalfa says

      May 19, 2015 at 4:46 pm

      i need code to read data from atmel 4 pin microcontroller and write data on it again it is on the board

      Reply
  2. Ramesh KP says

    March 15, 2013 at 2:43 am

    i like this blog, lot of big things described in light manner..!!

    Reply
  3. Curios User says

    March 25, 2013 at 5:28 am

    Maybe you should write a little bit about the SerialObj and tmrComm, where did they came from ??

    Reply
    • Md Ali Ahsan Rana says

      March 28, 2013 at 8:40 am

      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

      Reply
  4. Phil says

    May 7, 2013 at 1:20 pm

    Were is the CommTimer type found??

    Reply
    • Md Ali Ahsan Rana says

      May 8, 2013 at 4:45 am

      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.

      Reply
      • Phil says

        May 8, 2013 at 4:58 am

        Thanks for the reply, my question is what assembly is “CommTimer” in?

        Reply
        • Md Ali Ahsan Rana says

          May 8, 2013 at 11:34 am

          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.

          Reply
          • Phil says

            May 9, 2013 at 11:34 am

            Thanks very much for the additional code, its working now 🙂

          • aniljacob_75@yahoo.com says

            November 2, 2017 at 5:28 am

            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

  5. Andargachew Gobena says

    May 22, 2013 at 11:44 pm

    thanks a lot for the tutorial.Can you make a tutorial or guid me to writing device drivers for serial port devices?

    Reply
    • Md Ali Ahsan Rana says

      May 23, 2013 at 12:45 pm

      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.

      Reply
  6. Stephan says

    September 9, 2013 at 7:38 am

    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

    Reply
    • Md Ali Ahsan Rana says

      September 30, 2013 at 1:38 pm

      That is simply a constant where you will have to mention your target object name. Hope this helps.

      Reply
  7. xavi says

    July 4, 2014 at 4:37 am

    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^]

    Reply
  8. Katherine says

    August 7, 2014 at 12:44 pm

    not helpful, there are a lot of simpler ways to do this

    Reply
    • Md Ali Ahsan Rana says

      August 7, 2014 at 1:01 pm

      There could be, for sure. Why don’t you just share some way/link, I will be happy to share with my readers.

      Reply
  9. Madan Gehlot says

    August 21, 2014 at 3:57 am

    Can we use serial port communication with AVR micro-controller?

    Reply
    • Md Ali Ahsan Rana says

      August 21, 2014 at 10:34 am

      Not sure about that, haven’t tried yet.

      Reply
  10. sneha says

    September 23, 2014 at 3:03 am

    I am getting error at “Applicatio.DoEvent”. how to resolve it?
    I am using WPF

    Reply
    • Md Ali Ahsan Rana says

      September 23, 2014 at 8:23 am

      You can try with this solution, this might help: http://stackoverflow.com/questions/19007288/alternative-to-application-doevents-in-wpf

      Reply
  11. Sachin says

    September 30, 2014 at 6:58 am

    Can you to get punch in and out data from PunchMachine using above code

    Reply
  12. ravi says

    October 29, 2014 at 2:11 am

    showing error::: ‘Timer’ is an ambiguous reference between ‘System.Windows.Forms.Timer’ and ‘System.Timers.Timer’…what to do plz help

    Reply
  13. bhalaniabhishek says

    December 14, 2014 at 3:55 am

    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

    Reply
  14. Nizam Khan says

    January 13, 2015 at 1:50 am

    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

    Reply
  15. Thiha Swe says

    January 14, 2015 at 10:29 pm

    Please help me . Does it need all ping or which pings need mainly to receive and send data from computer and other device.

    Reply
  16. zeeshan siddique says

    February 3, 2015 at 2:40 am

    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 .

    Reply
    • Md Ali Ahsan Rana says

      February 3, 2015 at 11:02 pm

      Its always wise to make connection on demand(when needed) always without unnecessarily keeping a connection open, unless some exceptional cases.

      Reply
      • zeeshan siddique says

        February 4, 2015 at 1:24 am

        then why sometimes it give error that serial port cannot be opened after several communications ?

        Reply
  17. siva naidoo says

    March 5, 2015 at 7:50 am

    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?

    Reply
  18. Sahid Marian says

    March 11, 2015 at 4:47 am

    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.

    Reply
  19. kamran hafeez malik says

    May 17, 2015 at 10:28 am

    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

    Reply
  20. jimm says

    June 24, 2015 at 11:07 pm

    Thank You Great Work

    Reply
  21. Matt Quinn says

    October 3, 2015 at 5:22 pm

    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,

    Reply
  22. Deep Siddharth Verma says

    December 3, 2015 at 5:31 am

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

    Reply
  23. paul says

    March 23, 2016 at 6:15 am

    what assembly is “CommTimer” in?

    Reply
  24. Gu Hui Quan says

    June 12, 2016 at 9:27 pm

    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.

    Reply
  25. tarun says

    September 9, 2016 at 5:01 am

    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

    Reply
  26. Mohammad says

    January 19, 2017 at 1:20 pm

    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

    Reply
  27. Gopakumar says

    July 10, 2017 at 4:23 am

    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

    Reply
  28. Rajesh Maheshwari says

    September 16, 2017 at 11:28 pm

    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

    Reply
  29. Swati Dewangan says

    December 18, 2017 at 6:23 am

    Can u tell me how to code a program to record the exact time when serial port data arrives in visual studio in C#

    Reply
  30. Nitin says

    April 15, 2019 at 3:10 am

    I am getting error at “Applicatio.DoEvent”. how to resolve it?

    Reply
  31. waail says

    August 6, 2019 at 7:24 am

    Hello Can this code work with laboratory device????

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in