【C#】 实现串口通信

using System;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace DAL
{
    public class AsySerialDal
    {
        private static readonly object syncRoot = new object();
        const int COMDAL_RECVBUF_SIZE = 512;
        bool _isReceivingdal = false;
        private string m_portdal = "COMX";
        bool bComOpenDal = false;//标志

        SerialPort SerialPort = new SerialPort();
        byte[] ComRecvBuf = new byte[COMDAL_RECVBUF_SIZE + 1];

        public delegate void ReturnRecStr(byte[] RecveiveInfo, int datalen,string portName);                 
        public event ReturnRecStr ReturnRecStrEvent;

        //打开串口的方法
        public bool OpenPort(string PortName, int baurate)
        {
            m_portdal = PortName;
            bool ret = false;
            try
            {
                if (bComOpenDal == false)
                {
                    SerialPort.PortName = PortName;//端口号
                    SerialPort.BaudRate = baurate;//波特率
                    SerialPort.Parity = Parity.Odd;//偶校验位
                    SerialPort.DataBits = 8;//数据位为8
                    SerialPort.StopBits = StopBits.One;//1个停止位
                    SerialPort.ReadTimeout = 500;
                    SerialPort.RtsEnable = true;
                    SerialPort.Handshake = Handshake.None;//控制协议
                    SerialPort.ReceivedBytesThreshold = 1;
                    SerialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
                    SerialPort.Open();
                    bComOpenDal = true;
                }
            }
            catch (Exception ex)
            {
              
            }
            if (SerialPort.IsOpen)
            {
                ret = true;
            }
            return ret;
        }

        //关闭串口的方法
        public void ClosePort()
        {
            if (bComOpenDal == true)
            {
                SerialPort.DataReceived -= SerialPort_DataReceived;
                SerialPort.Close();
                if (!SerialPort.IsOpen)
                {
                }
                bComOpenDal = false;
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            lock (syncRoot)
            {
                _isReceivingdal = true;
                if (ComRecvBuf != null && bComOpenDal == true)
                {
                    SerialPort sp = (SerialPort)sender;

                    while (sp.IsOpen && sp.BytesToRead > 0)
                    {
                        int len = sp.BytesToRead > COMDAL_RECVBUF_SIZE ? COMDAL_RECVBUF_SIZE : sp.BytesToRead;
                        sp.Read(ComRecvBuf, 0, len);
                        if (ReturnRecStrEvent != null)
                        {
                            ReturnRecStrEvent(ComRecvBuf, len, m_portdal);//推送到上一层。
                        }
                    }
                }
                _isReceivingdal = false;
            }
        }

        //向串口发送数据
        public void SendCommandByte(byte[] WriteBuffer)
        {
            try
            {
                if (bComOpenDal == true && SerialPort.IsOpen == true)
                {
                    SerialPort.Write(WriteBuffer, 0, WriteBuffer.Length);
                }
            }
            catch (Exception ex)
            {

            }
        }

    }
}
posted @ 2024-10-15 10:54  qiutian-hao  阅读(36)  评论(0编辑  收藏  举报