Net Core教程

C# 串口通信

本文主要是介绍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# 串口通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!