基于C#实现串口通信Demo
1.基本概念
2.前端winForm布局如下(仅仅为了实现功能,布局略丑)
3.代码实现如下
namespace SerialPortTest
{
public partial class Form1 : Form
{
SerialPort sp1 = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//分别对应前端的波特率、数字位、校验位、停止位
cbBaudRate.SelectedIndex = 0;
cbDataBits.SelectedIndex = 0;
cbCheck.SelectedIndex = 0;
cbStop.SelectedIndex = 0;
string[] strCom = SerialPort.GetPortNames();
if (strCom == null)
{
MessageBox.Show("本机没有串口!", "Error");
return;
}
//GetPortNames()方法:获取当前计算机的串行端口名的数组
foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
{
cbCom.Items.Add(com);
}
cbCom.SelectedIndex = 0;
sp1.BaudRate = 9600;
Control.CheckForIllegalCrossThreadCalls = false;
sp1.DataReceived += Sp1_DataReceived;