《C#串口编程系列文章》
(1)预备知识
(2)介绍SerialPort类的API
(3)使用SerialPort进行C#串口编程的常见bug点
(4)深入探究关闭串口时Winform界面卡死原因
(5)项目实战-串口编程代码示例
(6)RS232,RS485,串口,三个名词的联系与区别
(7)详解串口通信协议
获取PC上所有的串口名
public static string[] GetPortNames();
构造函数(设置串口参数)
public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits);
判断串口打开/关闭
public bool IsOpen { get; }
打开串口
public void Open();
关闭串口
public void Close();
发送数据
public void Write(byte[] buffer, int offset, int count);
public void Write(string text);
public void Write(char[] buffer, int offset, int count);
public void WriteLine(string text);
读取数据
public int Read(byte[] buffer, int offset, int count);
public string ReadExisting();
public int Read(char[] buffer, int offset, int count);
public int ReadByte();
public int ReadChar();
public string ReadLine();
编码方式
public Encoding Encoding { get; set; }
此属性,决定ReadExisting,ReadChar,Write(string text),Write(char[] buffer, int offset, int count)采用的编码方式。
行结束符
public string NewLine { get; set; }
此属性决定ReadLine和WriteLine方法使用的换行符。
超时设置
public int ReadTimeout { get; set; }
public int WriteTimeout { get; set; }
当我们调用读或写方法,如果在指定的超时时间内没有从接收缓存读到数据或者将数据发送到发送缓存,那么读写方法就会抛出超时异常。
串口收到数据触发的事件
public event SerialDataReceivedEventHandler DataReceived;
接收到多少字节触发一次DataReceived事件
public int ReceivedBytesThreshold { get; set; }
清空接收和发送缓存
public void DiscardInBuffer();
public void DiscardOutBuffer();
其他极其不重要的属性(哈哈😄)
public bool DtrEnable { get; set; }
public bool RtsEnable { get; set; }
public bool CtsHolding { get; }
public bool DsrHolding { get; }
public Handshake Handshake { get; set; }
这5个属性在串口编程中几乎永远用不到,但我们解释下这5个属性,可以选择不看。
上世纪串口实现使用了RxD,TxD两根数据收发线,一根地线,若干根控制线。随着IT技术的日新月异,现在几乎不再使用控制线。而上述的5个属性正是对控制线的抽象,所以这些属性也用不到了,这些属性的默认值一般都是false,None,即禁用,不使用的含义,所以在串口编程中不理这些属性就OK了。
当然,你可能会问什么时候使用这些属性?
串口驱动程序支持控制线的话,我们连接两个串口时必须也要把控制线接好。如果串口驱动程序不支持控制线的话,那么我们只需要接好RxD,TxD,Ground三根线即可,控制线可以不接。
我们根据被控制的串口设备所使用的驱动程序是否支持控制线,来设置DtrEnable,RtsEnable,Handshake的值。但一般都未使用控制线。
什么是流控
Handshake指流控,也称为握手。通信双方发送数据要考虑对方的处理数据能力,接收方处理不过来发送方就要先暂停发送一段时间,这就是流控。流控可以通过控制线实现,称为硬流控;流控通过软件实现,称为软流控。现代串口通信一般也不使用流控机制。

接线方式(a)最常用,它没有流控,Handshake属性为None。
接线方式(b)使用了软件流控,Handshake属性为XOnXOff。
接线方式(c)使用了硬件流控,Handshake属性为RequestToSend。




