SoFunction
Updated on 2025-04-06

C# Serial Communication SerialPort Use

Class isC#Class for serial communication. It provides a set of properties and methods for configuring serial ports, reading and writing data, and handling events in serial communication.

Initialize SerialPort object

First, you need to create aSerialPortobject and set its port name (PortName), baud rate (BaudRate) and other attributes.

using ;  
  
SerialPort serialPort = new SerialPort();  
 = "COM1"; // Serial port name = 9600; // Baud rate = 8; // Data bits = ; // Check bit = ; // Stop position = ; // Control protocol

Turn on and close serial ports

Configure itSerialPortAfter the object, you need to open the serial port to start communication.

();  
// ... Perform serial communication operation ...(); // Close the serial port after completion

Read and write data

useSerialPortThe object'sReadLineReadExistingReadByteRead data usingWriteLineWriteWrite data in other ways.

// Write data("Hello, serial port!");  
  
// Read datastring data = (); // Read a line of data until a newline is encountered// orstring existingData = (); // Read all available data

Event handling

SerialPortThe class provides several events that allow you to execute code in specific situations, such as when data is received.

 += new SerialDataReceivedEventHandler(DataReceivedHandler);  
  
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)  
{  
    SerialPort sp = (SerialPort)sender;  
    string indata = ();  
    ("Data Received:");  
    (indata);  
}

In this example, when data is received,DataReceivedHandlerThe method will be called and the received data will be read and printed.

Things to note

Make sure you have the correct serial port name, as well as the correct configuration parameters (baud rate, data bit, check bit, stop bit, etc.).
In a multithreaded environment, be careful about thread safety issues when handling serial port events.
Don't forget to close the serial port after completing serial communication.
Exception handling
In useSerialPortWhen you are , you should be ready to handle possible exceptions, such as when trying to open a non-existent port or an I/O error occurs.

try  
{  
    ();  
    // ... Serial communication operation ...}  
catch (Exception ex)  
{  
    ("Error: " + );  
}  
finally  
{  
    if ()  
    {  
        ();  
    }  
}

thistry-catch-finallyThe block ensures that the serial port is properly closed even if an exception occurs.

This is the end of this article about the use of serialPort in C# serial communication. For more related C# serialPort content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!