用 winform 写一个串口通讯
以下是一个简单的串口通讯程序,使用 C# 和 WinForms 编写:
-
创建一个新的 WinForms 应用程序项目。
-
在 Form 上添加以下控件:
- 一个 ComboBox,用于选择串口号
- 一个 ComboBox,用于选择波特率
- 一个 Button,用于打开或关闭串口
- 一个 TextBox,用于显示接收到的数据
- 一个 TextBox,用于输入要发送的数据
- 一个 Button,用于发送数据
-
在 Form 的 Load 事件中初始化串口号和波特率的 ComboBox,代码如下:
private void Form1_Load(object sender, EventArgs e) { string[] portNames = SerialPort.GetPortNames(); Array.Sort(portNames); comboBox1.Items.AddRange(portNames); comboBox1.SelectedIndex = 0; comboBox2.Items.Add("9600"); comboBox2.Items.Add("19200"); comboBox2.Items.Add("38400"); comboBox2.Items.Add("57600"); comboBox2.Items.Add("115200"); comboBox2.SelectedIndex = 0; } -
在 Button 的 Click 事件中打开或关闭串口,代码如下:
private void button1_Click(object sender, EventArgs e) { if (serialPort1.IsOpen) { serialPort1.Close(); button1.Text = "打开串口"; } else { serialPort1.PortName = comboBox1.SelectedItem.ToString(); serialPort1.BaudRate = int.Parse(comboBox2.SelectedItem.ToString()); serialPort1.Open(); button1.Text = "关闭串口"; } } -
在串口接收事件中显示接收到的数据,代码如下:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { string data = serialPort1.ReadExisting(); Invoke(new Action(() => { textBox1.AppendText(data); })); } -
在发送按钮的 Click 事件中发送数据,代码如下:
private void button2_Click(object sender, EventArgs e) { string data = textBox2.Text; if (serialPort1.IsOpen) { serialPort1.Write(data); } } -
最后,在 Form 的构造函数中注册串口接收事件,代码如下:
public Form1() { InitializeComponent(); serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); }
至此,一个简单的串口通讯程序就完成了。注意,这只是一个简单的示例,实际应用中还需要考虑更多的因素,如错误处理、数据校验等。
原文地址: https://www.cveoy.top/t/topic/bRpN 著作权归作者所有。请勿转载和采集!