C#串口连接的读取和发送详解
一、串口连接的打开与关闭
串口,即com口,在.net中使用 serialport 类进行操作。串口开启与关闭,是涉及慢速硬件的io操作,频繁打开或关闭会影响整体处理速度,甚至导致打开或关闭串口失败。非特殊情况,串口一次性打开后,在退出程序时关闭串口即可。在打开串口前,可以设置一些常用的参数。常用的参数如下:
(1)串口的接受/发送超时时间:readtimeout/writetimeout。
(2) 串口的接受/发送缓存区大小:readbuffersize/writebuffersize。
具体代码如下:
// open com _serialport = new serialport(com, baud); if (_serialport.isopen) _serialport.close(); // set the read / write timeouts _serialport.readtimeout = 500; _serialport.writetimeout = 500; // set read / write buffer size,the default of value is 1mb _serialport.readbuffersize = 1024 * 1024; _serialport.writebuffersize = 1024 * 1024; _serialport.open(); // discard buffer _serialport.discardinbuffer(); _serialport.discardoutbuffer();
需要注意的是超出缓冲区的部分会被直接丢弃。因此,如果需要使用串口传送大文件,那接收方和发送方都需要将各自的缓冲区域设置的足够大,以便能够一次性存储下大文件的二进制数组。若条件限制,缓冲区域不能设置过大,那就需要在发送大文件的时候按照发送缓冲区大小分包去发送,接收方按顺序把该数组组合起来形成接受文件的二进制数组。
二、串口发送
serialport 类发送支持二进制发送与文本发送,需要注意的是文本发送时,需要知道转换的规则,一般常用的是ascii、utf7、utf-8、unicode、utf32。具体代码如下:
#region send /// <summary> /// 发送消息(byte数组) /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public void send(byte[] buffer, int offset, int count) { lock (_mux) { _serialport.write(buffer, offset, count); _sendcount += (count - offset); } } /// <summary> /// 发送消息(字符串) /// </summary> /// <param name="encoding">字符串编码方式,具体方式见<see cref="encoding"/></param> /// <param name="message"></param> public void send(encoding encoding , string message) { lock (_mux) { var buffer = encoding.getbytes(message); _serialport.write(buffer, 0, buffer.length); _sendcount += buffer.length; } } #endregion
三、串口接受
串口接受需要注意,消息接受与消息处理要代码分离。不能把流程处理的代码放入信息接受处,因为消息处理或多或少会有耗时,这会造成当发送方发送过快时,接受方的接受缓冲区会缓存多条消息。我们可以把接受到的消息放入队列中,然后在外部线程中,尝试去拿出该条消息进行消费。采用 “生产-消费”模式。具体代码如下:
#region receive private void pushmessage() { _serialport.datareceived += (sender, e) => { lock (_mux) { if (_serialport.isopen == false) return; int length = _serialport.bytestoread; byte[] buffer = new byte[length]; _serialport.read(buffer, 0, length); _receivecount += length; _messagequeue.enqueue(buffer); _messagewaithandle.set(); } }; } /// <summary> /// 获取串口接受到的内容 /// </summary> /// <param name="millisecondstotimeout">取消息的超时时间</param> /// <returns>返回byte数组</returns> public byte[] trymessage(int millisecondstotimeout = -1) { if (_messagequeue.trydequeue(out var message)) { return message; } if (_messagewaithandle.waitone(millisecondstotimeout)) { if (_messagequeue.trydequeue(out message)) { return message; } } return default; } #endregion
四、完整代码与测试结果
串口工具类的完整代码如下:
using system; using system.collections.concurrent; using system.collections.generic; using system.io.ports; using system.linq; using system.runtime.serialization; using system.text; using system.threading; using system.threading.tasks; namespace serialportdemo { public class sserialport { private serialport _serialport; private readonly concurrentqueue<byte[]> _messagequeue; private readonly eventwaithandle _messagewaithandle; private int _receivecount, _sendcount; private readonly object _mux; public int receivecount { get => _receivecount; } public int sendcount { get => _sendcount; } public sserialport(string com, int baud ) { // initialized _mux=new object(); _receivecount = 0; _sendcount = 0; _messagequeue = new concurrentqueue<byte[]>(); _messagewaithandle = new eventwaithandle(false, eventresetmode.autoreset); // open com opencom(com.toupper(),baud); // receive byte pushmessage(); } private void opencom(string com, int baud) { // open com _serialport = new serialport(com, baud); if (_serialport.isopen) _serialport.close(); // set the read / write timeouts _serialport.readtimeout = 500; _serialport.writetimeout = 500; // set read / write buffer size,the default of value is 1mb _serialport.readbuffersize = 1024 * 1024; _serialport.writebuffersize = 1024 * 1024; _serialport.open(); // discard buffer _serialport.discardinbuffer(); _serialport.discardoutbuffer(); } #region static /// <summary> /// 获取当前计算机的串行端口名的数组 /// </summary> /// <returns></returns> public static string[] getportnames() { return serialport.getportnames(); } #endregion #region receive private void pushmessage() { _serialport.datareceived += (sender, e) => { lock (_mux) { if (_serialport.isopen == false) return; int length = _serialport.bytestoread; byte[] buffer = new byte[length]; _serialport.read(buffer, 0, length); _receivecount += length; _messagequeue.enqueue(buffer); _messagewaithandle.set(); } }; } /// <summary> /// 获取串口接受到的内容 /// </summary> /// <param name="millisecondstotimeout">取消息的超时时间</param> /// <returns>返回byte数组</returns> public byte[] trymessage(int millisecondstotimeout = -1) { if (_messagequeue.trydequeue(out var message)) { return message; } if (_messagewaithandle.waitone(millisecondstotimeout)) { if (_messagequeue.trydequeue(out message)) { return message; } } return default; } #endregion #region send /// <summary> /// 发送消息(byte数组) /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public void send(byte[] buffer, int offset, int count) { lock (_mux) { _serialport.write(buffer, offset, count); _sendcount += (count - offset); } } /// <summary> /// 发送消息(字符串) /// </summary> /// <param name="encoding">字符串编码方式,具体方式见<see cref="encoding"/></param> /// <param name="message"></param> public void send(encoding encoding , string message) { lock (_mux) { var buffer = encoding.getbytes(message); _serialport.write(buffer, 0, buffer.length); _sendcount += buffer.length; } } #endregion /// <summary> /// 清空接受/发送总数统计 /// </summary> public void clearcount() { lock (_mux) { _sendcount = 0; _receivecount = 0; } } /// <summary> /// 关闭串口 /// </summary> public void close() { _serialport.close(); } } }
测试代码如下:
class program { static void main(string[] args) { console.writeline($"该计算机可使用的串口列表:{string.join(",", sserialport.getportnames())}"); console.write("请输入需要打开的串口:"); string port = console.readline(); sserialport com = new sserialport(port, 57600); console.writeline($"串口 {port} 打开成功..."); console.write("请输入需要打开的串口发送的消息:"); string text = console.readline(); while (true) { com.send(encoding.default, text); console.writeline($"总共发送 {com.sendcount}"); var message = com.trymessage(); if (message != null) { console.writeline($"{datetime.now.tostring("hh:mm:ss fff")} {encoding.default.getstring(message)}"); //// test:从添加延时可以测试到,接受消息和处理消息必须分不同线程处理。因为对于消息的处理或多或少都需要耗时,这样容易造成消息处理不及时。而添加到队列后,我们可以随时取出处理 //system.threading.thread.sleep(100*1); } console.writeline($"总共接受 {com.receivecount}"); } console.readkey(); } }
使用串口工具测试如下,对于串口的接受如丝般顺滑。当我们在消息中增加测试延时后,就会发现当串口工具继续快速发送一段时间后关闭发送,发现使用队列后,依然没有丢失一条来自发送方的消息。
总结
到此这篇关于c#串口连接的读取和发送的文章就介绍到这了,更多相关c#串口连接读取和发送内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!