SerialPortStream 稳定易用的第三方串口通信库
侧边栏壁纸
  • 累计撰写 62 篇文章
  • 累计收到 20 条评论

SerialPortStream 稳定易用的第三方串口通信库

一缕清风
2021-01-16 / 0 评论 / 135 阅读 / 正在检测是否收录...

简介

SerialPortStream是C#串口通讯类库之一,一个增强的自定义串口类,实现协议无关的数据帧完整接收功能,支持跨平台使用;相比于.net原生的serialport更加简单易用;开源且免费

GitHub

开源地址:https://github.com/jcurl/serialportstream

使用教程

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

namespace UsbDemo
{
    class ComConnect
    {
        protected SerialPortStream serialPort = null;
        public ComConnect()
        {
        }

        public void ConnectionCOM()
        {
            //配置串口参数
            serialPort = new SerialPortStream("COM3", 115200, 8, Parity.None, StopBits.One);
            serialPort.Handshake = Handshake.None;
            serialPort.RtsEnable = true;
            serialPort.DataReceived += OnReviceData;
            serialPort.ErrorReceived += OnErrorReceived;
            serialPort.PinChanged += OnPinChanged;

            if (!serialPort.IsOpen)
            {
                //打开串口
                serialPort.Open();

                var data = Encoding.UTF8.GetBytes("test");
                //同步发送
                serialPort.Write(data, 0, data.Length);
                //异步发送
                serialPort.WriteAsync(data, 0, data.Length);

                //关闭串口
                serialPort.Close();
            }

        }

        /// <summary>
        /// 数据接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnReviceData(object sender, SerialDataReceivedEventArgs e)
        {

        }

        /// <summary>
        /// 针脚改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPinChanged(object sender, SerialPinChangedEventArgs e)
        {
        }

        /// <summary>
        /// 异常信息事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
        }
    }
}
1

评论 (0)

取消