Serial Communication is a common data transmission method between hardware devices and computers, and is widely used in industrial control, embedded systems, sensor data acquisition and other fields. This article will introduce in detail how to use C# to realize data transmission and reception based on serial communication, and analyze its implementation process in combination with code examples.
1. Overview
The core of serial communication is the class, which encapsulates the underlying details of serial port operation and provides a simple and easy-to-use interface. The following is the basic process of serial communication:
1. Initialize the serial port: Set the serial port parameters (such as baud rate, data bit, stop bit, etc.).
2. Open the serial port: Open the serial port through the method.
3. Send data: Send data to the serial port through the method.
4. Receive data: receive data asynchronously through events.
5. Process data: parse and process the received data.
2. Key technical points
2.1 SerialPort class
SerialPort is the core class used in C# for serial communication, and provides methods for sending and receiving data.
2.2 Asynchronously receiving data
Receive data asynchronously through events to avoid blocking the main thread.
2.3 Data analysis
The received data is usually a byte array (byte[]) and needs to be parsed according to the protocol format.
2.4 Event mechanism
The received data is passed to other modules for processing through the event mechanism.
3. Code implementation
The following is a code example that implements data transmission and reception based on serial communication.
3.1 SerialPortHelper class
The SerialPortHelper class is responsible for initializing the serial port, sending data, receiving data and processing data.
public class SerialPortHelper { private SerialPort serialPort; // Serial port object private List<byte> _buffer = new List<byte>(); // Data buffer /// <summary> /// Custom serial message reception event /// </summary> public event ReceiveDataEventHandler ReceiveDataEvent; public SerialPortHelper() { serialPort = new SerialPort(); } /// <summary> /// Get all serial port names of the current computer /// </summary> public static string[] GetPortArray() { return (); // Get all available serial ports } /// <summary> /// Set serial port parameters /// </summary> public void SetSerialPort(string portName, int baudrate, Parity parity, int databits, StopBits stopBits) { = portName; // Port name = baudrate; // Baud rate = parity; // Parity = databits; // Data bits = stopBits; // Stop position += ReceiveDataMethod; // Subscribe to data reception events } /// <summary> /// Open the serial port /// </summary> public void Open() { try { (); // Open the serial port } catch (Exception ex) { ("Error opening serial port: " + ); } } /// <summary> /// Close the serial port /// </summary> public void Close() { (); // Close the serial port } /// <summary> /// Send data (byte array) /// </summary> public void SendDataMethod(byte[] data) { if (!) { Open(); // If the serial port is not opened, then open it first } (data, 0, ); // Send data } /// <summary> /// Send data (string) /// </summary> public void SendDataMethod(string data) { if (!) { Open(); // If the serial port is not opened, then open it first } (data); // Send string } /// <summary> /// How to handle data reception event /// </summary> private void ReceiveDataMethod(object sender, SerialDataReceivedEventArgs e) { try { byte[] dataChunk = new byte[]; // Read data in the buffer (dataChunk, 0, ); _buffer.AddRange(dataChunk); // Add data to the buffer while (_buffer.Count >= 3) // Make sure there is enough data in the buffer { byte thirdByte = _buffer[1]; // Get the third byte (function code) if (thirdByte == 0x03) // Function code 0x03 { if (_buffer.Count >= 19) // Check if there is a complete data packet { byte[] completePacket = _buffer.GetRange(0, 19).ToArray(); // Extract the complete data packet TriggerReceiveDataEvent(completePacket); // Trigger the receive event _buffer.RemoveRange(0, 19); // Remove processed data } else { break; // Insufficient data, wait for more data } } else if (thirdByte == 0x10 || thirdByte == 0x06) // Function code 0x10 or 0x06 { byte[] dataToProcess = _buffer.ToArray(); // Handle the entire buffer TriggerReceiveDataEvent(dataToProcess); // Trigger the receive event _buffer.Clear(); // Clear the buffer } else { _buffer.RemoveRange(0, 3); // Remove unrecognized data } } } catch (Exception ex) { ("Error processing serial port data: " + ); } } /// <summary> /// Trigger the received data event /// </summary> private void TriggerReceiveDataEvent(byte[] data) { if (ReceiveDataEvent != null) { ReceiveDataEventArg arg = new ReceiveDataEventArg(data); // Create event parameters (this, arg); // Trigger event } } }
3.2 ReceiveDataEventArg class
The ReceiveDataEventArg class is used to encapsulate received data and pass it as event parameters.
public class ReceiveDataEventArg : EventArgs { public byte[] Data { get; set; } // Received data public ReceiveDataEventArg(byte[] data) { Data = data; // Initialize the data } }
3.3 MainWindow
The main form is responsible for initializing the SerialPortHelper and processing the received data.
public partial class MainWindow : Window { private SerialPortHelper serialPortHelper; public MainWindow() { InitializeComponent(); SettingComPorts(); // Initialize the serial port } private void SettingComPorts() { string portName = "COM8"; // Serial port name int baudRate = 115200; // Baud rate Parity parity = ; // Parity int dataBits = 8; // Data bits StopBits stopBits = ; // Stop position serialPortHelper = new SerialPortHelper(); (portName, baudRate, parity, dataBits, stopBits); // Set serial port parameters (); // Open the serial port += ReceiveDataEvent; // Subscribe to receive data events } /// <summary> /// How to handle data events /// </summary> private void ReceiveDataEvent(object sender, ReceiveDataEventArg e) { byte[] receivedData = ; // Get the received data if (receivedData[1] == 0x03) // Function code 0x03 { int receiveDataLength = receivedData[2]; // Get the valid data length byte[] receiveDataBuffer = new byte[receiveDataLength]; (receivedData, 3, receiveDataBuffer, 0, receiveDataLength); // Extract valid data ushort[] units = (receiveDataBuffer); // Analyze data if (units != null) { List<ChannelData> channelDatas = (units); // Get device information UpdateDeviceInfo(channelDatas); // Update the UI } } } }
4. Detailed explanation of the data delivery process
4.1 Initialize the serial port
In the SettingComPorts method, set the serial port parameters and open the serial port.
Subscribe to the ReceiveDataEvent event to receive data.
4.2 Send data
Send data to the serial port through the SendDataMethod method.
4.3 Receive data
After the serial port receives data, the ReceiveDataMethod method is triggered.
Add the received data to the buffer and parse the data according to the function code.
4.4 Processing data
In the ReceiveDataEvent method, the received data is parsed and the UI is updated.
5. Analysis of key technologies
5.1 Asynchronously receive data
Receive data asynchronously through events to avoid blocking the main thread.
5.2 Data analysis
The received byte array is parsed according to the function code (such as 0x03, 0x06) and the valid data is extracted.
5.3 Event mechanism
The received data is passed to the main form or other module for processing through events.
6. Summary
This article introduces in detail how to use C# to realize data transmission and reception based on serial communication. Through the SerialPort class, we can easily implement serial port communication and combine event mechanism to realize data transmission and processing. Serial communication is suitable for data transmission between hardware devices and computers, and is an important technology in industrial control and embedded system development.
Hope this article helps you! If you have any questions, please leave a message in the comment area to discuss.
This is the article about how to use C# serial communication to achieve data transmission and reception. For more related contents for sending and receiving C# data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!