• TOC
    {:toc}

串口基本属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Serialport1.PortName = USBlist.SelectedValue.ToString();
// 设置串口的波特率为9600
Serialport1.BaudRate = int.Parse(Bps_Box.Text);
// 设置串口的数据位为8位
Serialport1.DataBits = int.Parse(DataBits_Box.Text);
// 设置串口的停止位为1位
Serialport1.StopBits = StopBits.One;
// 设置串口的校验位为None
Serialport1.Parity = Parity.None;
Serialport1.RtsEnable = true;
Serialport1.DtrEnable = true;
Serialport1.Handshake = Handshake.None;
Serialport1.NewLine = "\n";
Serialport1.ReadTimeout = 500;
Serialport1.WriteTimeout = 500;

串口相关用法

1
2
3
4
5
6
7
8
//创建串口,引号内的为你所使用的串口号
public SerialPort Serialport1 = new SerialPort("COM1");
//打开串口
Serialport1.Open();
//获取目前可用串口
string[] ports_ = SerialPort.GetPortNames();
//以字符串形式发送消息
Serialport1.Write(temp);

串口接收

其中,在C#中串口接收使用的是串口接收事件处理,当串口接收到数据,会触发相关的事件。若此时想要对窗口内其他元件进行修改,需要通过委托,将事件委托给主线程去执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
public void Invoke(string indata)
{
Messages.AppendText("接收:" + indata + '\n');
}
//串口接收事件处理
private void Serialport1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
Dispatcher.Invoke(new Action(() => Invoke(indata)));//委托给主线程实现
}

在笔者学习使用过程,出现过无法接收到数据,或者说,有接受到数据,但是无法触发串口接收事件。

目前存在可能原因:

  1. 发回的数据中需要包含‘\r’或者‘\n’。

  2. 串口接收中,需要去程序添加对应的串口接收事件。

    1
    Serialport1.DataReceived += new SerialDataReceivedEventHandler(Serialport1_DataReceived);