The SerialPort class in C# allows you to communicate with a serial port in .NET. This article will demonstrate how to write and receive data from a device connected to a serial port in C# and .NET. We will be writing the received data to a TextBox on a form, so this will also deal with threading.
In the past, to communicate with a Serial Port using .NET 1.1, you had to either use the Windows API or third-party control. With .NET 2.0 and above, Microsoft has added this support with the inclusion of the SerialPort class as part of the System.IO.Ports namespace. Implementation of the SerialPort class is very straightforward. To create an instance of the SerialPort class, you pass the SerialPort options to the class's constructor.
To receive data, we will need to create an EventHandler for the "SerialDataReceivedEventHandler":
You can also set other options, such as the ReadTimeout and WriteTimeout.
Once you are ready to use the Serial Port, you will need to open it:
Now, we are ready to receive the data. However, to write this data to the TextBox on a form, we need to create a delegate. .NET does not allow cross-thread action, so we need to use a delegate. The delegate writes to the UI thread from a non-UI thread.
We will now create the "sp_DataReceived" method that will be executed when data is received through the serial port,
Now we create our "si_DataReceived" method,
We can now receive data from a serial port device and display it on a form. Some devices will send data without being prompted. However, some devices need to send certain commands, and it will reply with the data the command calls for. For these devices, you will write data to the serial port and use the previous code to get the data that will be sent back. In my example, I will be communicating with a scale. For this particular scale, sending the command "SI\r\n" will force it to return the weight of whatever is on the scale. This command is specific for this scale. You will need to read the documentation of your serial device to find commands that it will receive. To write to the serial port, I have created a "Start" button on the form. I have added code to its Click_Event:
And that is all you need to do. I have attached the Visual Studio 2005 solution.
How to receive data from com port
Here is the complete application on how to receive data from a COM port in C#.
Summary
This article taught you how to communicate with a COM port in C#. You also learned how to receive data from a COM port using C#.