C#串口开发主要使用的是System.IO.Ports.SerialPort类,其中详细成员介绍可参考MSDN文档。
由于本机没有串口,需要使用VSPD虚拟串口工具创建2个虚拟串口,如下图中的COM1、COM2
使用winform创建如下界面,COM1发送数据,COM2接收数据,发送端和接收端的波特率、数据位、校验位、停止位必须一致
public partial class Form1 : Form { private SerialPort spCOM1; private SerialPort spCOM2; public Form1() { InitializeComponent(); var portNames = SerialPort.GetPortNames(); //获取本机可使用的COM端口 cmbCOM1.DataSource = portNames; cmbCOM2.DataSource = portNames; cmbBaudRate.DataSource = new int[] { 9600, 115200 };//波特率,默认9600 cmbDataBits.DataSource = new int[] { 6, 7, 8 }; //数据位 cmbParity.DataSource = new string[] { "None" }; //校验位 cmbStopBits.DataSource = new int[] { 1, 2, 3 }; //停止位 cmbCOM1.SelectedIndex = 0; cmbCOM2.SelectedIndex = 1; cmbBaudRate.SelectedIndex = 0; cmbDataBits.SelectedIndex = 2; cmbParity.SelectedIndex = 0; cmbStopBits.SelectedIndex = 0; spCOM1 = new SerialPort(); spCOM2 = new SerialPort(); spCOM2.ReadTimeout = 1000; spCOM2.DataReceived += SerialPort_DataReceived; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (spCOM1.IsOpen || spCOM2.IsOpen) { spCOM1.Close(); spCOM2.Close(); } } private void btnConnect_Click(object sender, EventArgs e) { if (spCOM1.IsOpen || spCOM2.IsOpen) { spCOM1.Close(); spCOM2.Close(); btnConnect.Text = "连接"; } else { spCOM1.PortName = Convert.ToString(cmbCOM1.SelectedValue); spCOM1.BaudRate = Convert.ToInt32(cmbBaudRate.SelectedValue); spCOM1.DataBits = Convert.ToInt32(cmbDataBits.SelectedValue); spCOM1.StopBits = (StopBits)Convert.ToInt32(cmbStopBits.SelectedValue); spCOM1.Parity = (Parity)Enum.Parse(typeof(Parity), Convert.ToString(cmbParity.SelectedValue)); spCOM1.Open(); spCOM2.PortName = Convert.ToString(cmbCOM2.SelectedValue); spCOM2.BaudRate = Convert.ToInt32(cmbBaudRate.SelectedValue); spCOM2.DataBits = Convert.ToInt32(cmbDataBits.SelectedValue); spCOM2.StopBits = (StopBits)Convert.ToInt32(cmbStopBits.SelectedValue); spCOM2.Parity = (Parity)Enum.Parse(typeof(Parity), Convert.ToString(cmbParity.SelectedValue)); spCOM2.Open(); btnConnect.Text = "断开"; } } private void btnSend_Click(object sender, EventArgs e) { byte[] buffer = Encoding.UTF8.GetBytes(txtSend.Text); spCOM1.Write(buffer, 0, buffer.Length); txtSend.Text = ""; } private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (spCOM2.BytesToRead > 0) { byte[] buffer = new byte[spCOM2.BytesToRead]; spCOM2.Read(buffer, 0, buffer.Length); string value = Encoding.UTF8.GetString(buffer); this.Invoke(() => { txtReceive.Text += value + "\r\n"; }); } } }