C# SerialPort 串行端口类 学习笔记

SerialPort 中的属性 

1 :PortName  通讯端口名称

2:BaudRate 波特率

3:DataBits 数据位

4:StopBits 停止位

5:ReadTimeout 超时时间

6:IsOpen() SerialPort对象是否打开

SerialPort 中使用到的(方法)函数

Open() 打开串行端口链接 Close() 关闭端口链接

发送数据: 

1 / Write 该函数有三个重载

Write(string text) 向串行端口发送字符串

Write(byte[] buffer,int offset,int count)  使用缓冲区的数据,将字节写入到串行端口

Write(char[] chr,,int offset,int count)  将指定数量的字符写入到串行端口

接收数据:

1 / Read 函数

Read(byte[] buffer,int offset,int count)  读出缓冲区字节,写入到字节数组中

2 / 写入串行端口数据还有(WriteLine(string text),将指定字符串写入缓冲区)

3  / 读取串行端口数据还有(ReadByte(),读取一个字节)(ReadChar(),读取一个字符)

(ReadTo(string Value),读到指定字符串)(ReadLine(),一直读到输入缓冲区中的SerialPort.NewLine值)

SerialPort 中的事件

1:DataReceived  理解为接收串行端口数据的监听事件,当端口接收到数据触发该事件

在该事件中 用Read() 读取传入数据

代码示例:

 public class PortControlHelp
    {
        /// <summary>
        /// 串口对象
        /// </summary>
        private SerialPort sp;
        /// <summary>
        ///收发串口数据委托
        /// </summary>
        /// <param name="data"></param>
        public delegate void ComReceiveDataHandler(string data);
        public ComReceiveDataHandler comReceiveDataHandler = null;
        /// <summary>
        /// 串口名称数组
        /// </summary>
        public string[] PortNameArr;
        /// <summary>
        /// 接口状态
        /// </summary>
        public bool PortState { set; get; } = false;
        /// <summary>
        /// 编码类型
        /// </summary>
        public Encoding encodingType { set; get; } = Encoding.ASCII;
        /// <summary>
        /// 
        /// </summary>
        public PortControlHelp()
        {
            //获取当前计算机的串行端口组
            PortNameArr = SerialPort.GetPortNames();
            sp = new SerialPort();
            //串口接收监听事件
            sp.DataReceived -= new SerialDataReceivedEventHandler(Sp_DataReceived);
            sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
        }
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //接收传入数据中的字节
            byte[] by = new byte[sp.BytesToRead];
            //读出byte
            sp.Read(by, 0, by.Length);
            string str = encodingType.GetString(by);
            if (comReceiveDataHandler == null)
            {
                comReceiveDataHandler(str);
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="strData"></param>
        public void SendData(string strData)
        {
            try
            {
                sp.Encoding = encodingType;
                sp.WriteLine(strData);

               
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="ProtName">端口名称</param>
        /// <param name="BtRate">波特率</param>
        /// <param name="dataRit">数据位</param>
        /// <param name="StopBit">停止位</param>
        /// <param name="timeout">超时</param>
        public void OpenPort(string protName, int baudRate = 115200, int dataRit = 8, int stopBit = 1, int timeout = 5000)
        {
            try
            {
                sp.PortName = protName;
                sp.BaudRate = baudRate;
                sp.DataBits = dataRit;
                sp.StopBits = (StopBits)stopBit;
                sp.ReadTimeout = timeout;
                sp.Open();
                PortState = true;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 关闭
        /// </summary>
        public void ClosePort()
        {
            try
            {
                sp.Close();
                PortState = false;
            }
            catch (Exception)
            {
                throw;
            }
        }

    }

学习来源:详细信息可查看链接- C#实现简单的串口通信-.net