C# 串口通信
2021/8/25 12:06:07
本文主要是介绍C# 串口通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
串口通信模板,存档备用:
using System; using System.Collections.Generic; using System.IO.Ports; using System.Threading; namespace ComCommunication { class ComLogic { public static bool SuccessFlag = false; protected static SerialPort COM = new SerialPort(); protected Thread SendThread; protected bool keepSending = true; protected int sendComDataTick = 20; //protected Thread ReceiveThread;//也可用线程定时侦听实现接收数据逻辑 protected int receiveComDataTick = 5; protected byte[] receiveBuffer = new byte[160]; protected List<byte> receiveList = new List<byte>(); protected delegate void RecEventHandler(byte[] queueByte); protected event RecEventHandler DataReceivedEvent; protected byte dealRev; protected byte DealRev { get { return dealRev; } set { dealRev = value; DataReceivedEvent?.Invoke(receiveBuffer); //DataReceivedEvent?.BeginInvoke(receiveBuffer, null, null); } } public LinkTrackLogic() { DataReceivedEvent += new RecEventHandler(DealDataReceivedEvent);//绑定事件 } public virtual void Open(string Port) { if (COM != null && COM.IsOpen == false) { try { COM.BaudRate = 2000000; COM.PortName = Port; COM.ReadTimeout = 550; COM.ReceivedBytesThreshold = 8; COM.DataReceived += Com_DataReceived;//串口接收事件 COM.Open(); SendThread = new Thread(SendDataHandler); SendThread.Priority = ThreadPriority.Highest; SendThread.IsBackground = true; SendThread.Start(); SuccessFlag = true; } catch (Exception ex) { //log } } } protected virtual void SendDataHandler() { while (keepSending) { try { //处理发送数据逻辑 } catch (Exception ex) { //log } Thread.Sleep(sendComDataTick);//35ms一周期 } } protected virtual void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { Thread.Sleep(receiveComDataTick); int n = COM.BytesToRead; byte[] receiveTemp = new byte[n]; int count = COM.Read(receiveTemp, 0, n); //1.缓存数据 receiveList.AddRange(receiveTemp); //2.完整性判断 while (receiveList.Count > 0) { //判断帧头帧尾校验等,根据数据长度取出完整的一帧数据 int dataLen = receiveList.Count;//设置为协议定义长度 receiveBuffer = new byte[dataLen]; //得到完整的数据,复制到readBuffer中 receiveList.CopyTo(0, receiveBuffer, 0, dataLen); //从缓冲区中清除 receiveList.RemoveRange(0, dataLen); //触发外部处理接收消息事件 DealRev += 1; } } catch (Exception ex) { //log } } protected virtual void DealDataReceivedEvent(byte[] receive) { try { //处理数据 } catch (Exception ex) { //log } } } }
这篇关于C# 串口通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#