C#串口通讯类

本文介绍了一个用于串口通信的辅助类库,支持多种配置参数,包括波特率、校验位等,并提供了数据读写功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AltotechBeta.RobotApp.Helper
{
    /// <summary>
    /// 串口帮助类
    /// </summary>
    class SerialHelper
    {
        #region ...字段...
        /// <summary>
        /// SerialPort实例
        /// </summary>
        private static SerialPort serialPort;   //串口
        /// <summary>
        /// Disposed标志
        /// </summary>
        private bool isAlreadyDisposed;
        /// <summary>
        /// 接收的数据
        /// </summary>
        private byte[] _arrayReceive;
        #endregion

        #region ...属性...
        /// <summary>
        /// 接收的数据
        /// </summary>
        public byte[] ArrayReceive
        {
            get
            {
                return _arrayReceive;
            }
        }
        #endregion

        #region ...构造函数...
        /// <summary>
        /// 初始化
        /// </summary>
        public SerialHelper()
        {
            try
            {
                serialPort = new SerialPort();
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
            }
            catch (Exception ee)
            {
                //
            }
        }
        public SerialHelper(string portName) : this()
        {
            serialPort.PortName = portName;
        }
        public SerialHelper(string portName, int baudRate) : this()
        {
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;//波特率
        }
        public SerialHelper(string portName, int baudRate, Parity parity) : this()
        {
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;//波特率
            serialPort.Parity = parity;//校验位
        }
        public SerialHelper(string portName, int baudRate, Parity parity, int dataBits) : this()
        {
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;//波特率
            serialPort.Parity = parity;//校验位
            serialPort.DataBits = dataBits;
        }
        public SerialHelper(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) : this()
        {
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;//波特率
            serialPort.Parity = parity;//校验位
            serialPort.DataBits = dataBits;
            serialPort.StopBits = stopBits;
        }

        #endregion

        #region ...私有方法...
        /// <summary>
        /// 接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                if (serialPort.IsOpen == true)
                {
                    if (serialPort.BytesToRead > 0)
                    {
                        _arrayReceive = new byte[serialPort.BytesToRead];
                        serialPort.Read(_arrayReceive, 0, serialPort.BytesToRead);
                    }
                }
            }
            catch (Exception ee)
            {
                AppHelper.SaveException(ee);
            }

        }

        /// <summary>
        /// Virtual Dispose method
        /// </summary>
        /// <param name="isDisposing">Disposing</param>
        private void Dispose(bool isDisposing)
        {
            try
            {
                if (isAlreadyDisposed)
                {
                    return;
                }
                if (isDisposing)
                {
                    if (serialPort.IsOpen)
                    {
                        serialPort.Close();
                        serialPort.Dispose();
                    }
                }
                isAlreadyDisposed = true;
            }
            catch (Exception ee)
            {
                AppHelper.SaveException(ee);
            }

        }
        #endregion

        #region ...公有方法...
        /// <summary>
        /// 打开串口
        /// </summary>
        public void OpenPort()
        {
            if (null != serialPort)
            {
                try
                {
                    if (!serialPort.IsOpen)
                        serialPort.Open();
                }
                catch (Exception ee)
                {
                    AppHelper.SaveException(ee);
                }
            }
        }

        /// <summary>
        /// close
        /// </summary>
        public void ClosePort()
        {
            try
            {
                if (serialPort.IsOpen)
                    serialPort.Close();
                serialPort.Dispose();
            }
            catch (Exception ee)
            {
                AppHelper.SaveException(ee);
            }
        }

        ///// <summary>
        ///// 发送
        ///// </summary>
        ///// <param name="data">数据</param>
        ///// <param name="count">数据条数</param>
        public void Write(params byte[] data)
        {
            try
            {
                serialPort.Write(data, 0, data.Length);
            }
            catch (Exception ee)
            {
                AppHelper.SaveException(ee);
            }

        }

        /// <summary>
        /// 发送字符串
        /// </summary>
        /// <param name="strBuf">要发送的字符串</param>
        public void Write(string strBuf)
        {
            try
            {
                serialPort.Write(strBuf);
            }
            catch (Exception ee)
            {
                AppHelper.SaveException(ee);
            }
        }



        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(true);
        }
        #endregion
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿蒙Amon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值