How to Implement Serial Communication in C#
By FoxLearn 11/26/2024 8:43:25 AM 20.79K
What are serial ports?
A serial port is a communication interface that transfers data one bit at a time, sequentially.
Serial ports are widely used for communication with devices like modems, printers, barcode scanners, and medical equipment. They are also important in industrial automation, control systems, and networking devices like routers and switches.
How to use Serial Communication in C#
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "COM" and then click OK
Drag and drop Button, Label, ComboBox control from the Visual Studio toolbox onto your form designer, then design your form as shown below.
Add a reference to System.IO.Ports
assembly, then use SerialPort
class to interact with the serial port.
You need to include the System.IO.Ports
namespace to access serial communication functionalities.
using System; using System.IO.Ports;
Add a Form_Load event handler allows you to get all serial ports
private void Form1_Load(object sender, EventArgs e) { //Get all ports string[] ports = SerialPort.GetPortNames(); cboPort.Items.AddRange(ports); cboPort.SelectedIndex = 0; btnClose.Enabled = false; }
Use the appropriate COM port for your system, and you can list all available ports with SerialPort.GetPortNames()
.
Add code to button click event handler allows you to open, send and receive messages
You can also open serial port like this
private void btnOpen_Click(object sender, EventArgs e) { btnOpen.Enabled = false; btnClose.Enabled = true; try { // Configure the SerialPort object serialPort1.PortName = cboPort.Text; // Specify the port name (COM1, COM2, etc.) // Open the serial port serialPort1.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
Serial port baud rates refer to the speed at which data is transferred, measured in bits per second (bps).
serialPort1.BaudRate = 9600; // Set baud rate
Standard baud rates range from 110 to 256000 bits per second, with common values including 9600, 19200, and 115200 bps. The default baud rate is 9600.
You can also send data through serial port like this
private void btnSend_Click(object sender, EventArgs e) { try { if (serialPort1.IsOpen) { // Send data to the serial port serialPort1.WriteLine(txtMessage.Text + Environment.NewLine); txtMessage.Clear(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
You can also receive data through serial port like this
// c# serial port read private void btnReceive_Click(object sender, EventArgs e) { try { if (serialPort1.IsOpen) { // Read data from the serial port (blocking read) txtReceive.Text = serialPort1.ReadExisting(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
You can close port when clicking the Close button.
private void btnClose_Click(object sender, EventArgs e) { btnOpen.Enabled = true; btnClose.Enabled = false; try { // Close the port when done serialPort1.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
Don't forget to close the serial port when the form closes
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Close the port when done if (serialPort1.IsOpen) serialPort1.Close(); }
In this example, replace "COM5"
with your actual port name and adjust the baud rate as needed. Also, handle the received data and errors in the appropriate event handlers.
If you want to read data asynchronously, you can subscribe to the DataReceived
event.
serialPort.DataReceived += SerialPort_DataReceived; serialPort.ErrorReceived += SerialPort_ErrorReceived;
// data from serial c# private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Handle received data string data = serialPort.ReadExisting(); // txtReceive.Invoke((MethodInvoker)(() => txtReceive.AppendText(data))); }
And handle errors like this
private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { // Handle errors here MessageBox.Show("Serial port error: " + e.EventType); }
This is a simple example c# serial port that shows you how to use serial communication in c#. Always configure the serial port settings (like baud rate, parity, etc.) to match the settings of the device you're communicating with.
VIDEO TUTORIAL