欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#串口通讯,复制粘贴就可用,仅仅介绍怎样最快的搭建一个串口通讯,异常拦截等等需要自己加上

程序员文章站 2022-04-18 18:50:44
using System; using System.Collections.Generic; using System.IO.Ports; using System.Text; //串口通讯类 public class SerialPortManager { //声明一个静态的串口资源 priva ......
using system;
using system.collections.generic;
using system.io.ports;
using system.text;

//串口通讯类
public class serialportmanager
{

    //声明一个静态的串口资源
    private serialport comdevice = new serialport();
    public serialportmanager()
    {
        var portlist = serialport.getportnames();//获取当前搜索到的串口集合
        comdevice.datareceived += new serialdatareceivedeventhandler(com_datareceived); //绑定事件,接收到串口数据时触发
    }

    /// <summary>
    /// 打开和关闭串口,
    /// 前端放个按钮调用这个方法
    /// 串口名称用serialport.getportnames()拉取所有串口,上面构造有写
    /// 下面相关的参数具体有些哪些百度下就知道了,这块只是举例,当然也可以直接用
    /// </summary>
    /// <param name="serialportname">串口名称</param>
    /// <returns></returns>
    public void openorcloseserialport(string serialportname)
    {
        //判断当前状态是打开还是关闭,开启的话就关闭,反之就开启
        if (comdevice.isopen == false)
        {
            //设置串口名称
            comdevice.portname = serialportname;
            //设置波特率  
            comdevice.baudrate = 115200;
            //设置数据位 
            comdevice.databits = 8;
            //校验位设置 
            comdevice.stopbits = stopbits.one;
            //停止位设置
            comdevice.parity = parity.none;
            //开启串口
            comdevice.open(); 
        }
        else
        {
            comdevice.close();//关闭串口
        }
    }

    /// <summary>
    /// 串口数据读取方法,在构造时已经监听 
    /// </summary>
    private void com_datareceived(object sender, serialdatareceivedeventargs e)
    {
        byte[] redatas = new byte[comdevice.bytestoread];
        comdevice.read(redatas, 0, redatas.length);
        //接收到的字节流
        var data = redatas; 
        //根据自己需求转换 
        var str = new utf8encoding().getstring(redatas);
    }

    /// <summary>
    /// 发送数据方法
    /// </summary>
    /// <param name="data">需要发送的字节流</param>
    public void com_senddata(byte[] data)
    {
        if (comdevice.isopen)
        {
            comdevice.write(data, 0, data.length);//发送数据
        }
    }
}