调用库:
using System.IO.Ports;
创建serialport对象并设置,当然也可以直接拖serialport控件然后设置属性:
public SerialPort test = new SerialPort();
test.PortName = "COM1"; //串口名称
test.BaudRate = 38400; //波特率
test.Parity = Parity.None; //校验位
test.DataBits = 8; //数据位
test.StopBits = StopBits.One; //停止位
test.RtsEnable = true; //确定是否使 Request To Send (RTS) 线有效,一般设置为true
test.ReadTimeout = 100; //读数据时限
设置完之后就可以用了,首先打开/关闭操作
//打开
if (!test.IsOpen)
test.Open();
//关闭
test.Close();
然后是接受数据部分,由Serialport对象自带的data_received完成,收下来分类然后存到相应的list中
假设接受的数据为
数据头 | 长度(高位) | 长度(低位) | 数据段 | 结束符 |
0 |