C# — WinForm 串口通信

C# 的串口通信,是采用serialPort控件,下面是对serialPort控件(也是串口通信必备信息)的配置如下代码:

View Code
1 serialPort1.PortName = commcomboBox1.Text;
2 serialPort1.BaudRate = int.Parse(baudcomboBox2.Text);
3 serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), efficacycomboBox3.Text);
4 serialPort1.DataBits = int.Parse(databitcomboBox4.Text);
5 serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbitcomboBox5.Text);

PortName:是所用串口的名称,一般当首次连入串口通信设备时,都会提示采用了哪个COM。

BaudRate:波特率,一般采用值有300,600,1200,2400,4800,9600,14400,28800,36000,115000等。

Parity:效验位,一般采用值有None,Even,Odd。

DataBits:数据位,一般采用值有5,6,7,8。

StopBits:停止位,一般采用值有1,2,3。

打开串口的代码如下:

View Code
 1 /*前面为串口基础信息的配置,这里为打开串口*/
 2 if (!serialPort1.IsOpen)
 3 {
 4      try
 5      {
 6           serialPort1.Open();
 7       }
 8       catch (Exception)
 9       {
10             MessageBox.Show("Port Access is failure,Reset The Serial Basic Information", "Prompting");
11        }  
12 }

发送串口内容的代码如下:

View Code
1 /*发送字符串str的格式就需要根据具体的串口设备协议来定*/
2 string str = "";
3 serialPort1.Write(str);
4 byte[] sendByte = Encoding.BigEndianUnicode.GetBytes(str.ToCharArray());
5 serialPort1.Write(sendByte, 0, sendByte.Length);
原文地址:https://www.cnblogs.com/guolebin7/p/2852576.html