在C#中,使用System.IO.Ports.SerialPort
類可以實現串口通信。以下是一個簡單的示例,展示了如何使用SerialPort
類進行串口通信:
System.IO.Ports
命名空間。using System.IO.Ports;
SerialPort
對象,并配置串口參數。例如,要使用COM1端口,波特率為9600,數據位為8,停止位為1,無奇偶校驗:SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort.Open();
SerialPort
對象添加事件處理程序,以便在接收到數據時執行相應操作。這里我們使用DataReceived
事件:serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
serialPort_DataReceived
方法,處理接收到的數據:private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[serialPort.BytesToRead];
serialPort.Read(buffer, 0, buffer.Length);
string receivedData = System.Text.Encoding.ASCII.GetString(buffer);
Console.WriteLine("接收到的數據: " + receivedData);
}
serialPort.Close();
將以上代碼整合到一個完整的示例中:
using System;
using System.IO.Ports;
namespace SerialPortExample
{
class Program
{
static void Main(string[] args)
{
SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort.Open();
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
Console.WriteLine("按任意鍵關閉串口...");
Console.ReadKey();
serialPort.Close();
}
private static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[serialPort.BytesToRead];
serialPort.Read(buffer, 0, buffer.Length);
string receivedData = System.Text.Encoding.ASCII.GetString(buffer);
Console.WriteLine("接收到的數據: " + receivedData);
}
}
}
運行此示例,程序將打開COM1端口,并在接收到數據時在控制臺輸出接收到的數據。按任意鍵關閉串口。