我的串口操作COM(serialPort)

创建一个全局变量

SerialPort comport = new SerialPort();

    public bool OpenSerialPort(string ComName)
        {
            if (!ComPort.IsOpen)
            {
                //关闭时点击,则设置好端口,波特率后打开
                try
                {
                    ComPort.PortName = ComName; //串口名 COM1
                    ComPort.BaudRate = 9600; //波特率  9600
                    ComPort.DataBits = 8; // 数据位 8
                    ComPort.ReadBufferSize = 4096;
                    ComPort.StopBits = StopBits.One;
                    ComPort.Parity = Parity.None;
                    ComPort.Open();
                    this.LBSatic.Text = $"当前端口{COMName}连接正常。";
                }
                catch (Exception ex)
                {
                    //捕获到异常信息,创建一个新的comm对象,之前的不能用了。
                    ComPort = new SerialPort();
                    this.LBSatic.Text = $"当前端口{COMName}连接出错,请切换端口。";
                    //现实异常信息给客户。
                    //MessageBox.Show(ex.Message);
                    return false;
                }
            }
            return true;
        }


this.ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.ComPort_DataReceived);


///关闭
 if (this.ComPort.IsOpen)
            {
                this.ComPort.Close();



            }

 /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        
       private void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);
            byte[] b = new byte[ComPort.BytesToRead];
            ComPort.Read(b, 0, b.Length);
            // string ret = Encoding.GetEncoding("GBK").GetString(b);
            string ReadMsg = Encoding.UTF8.GetString(b);
            SendKeys.SendWait(ReadMsg + "\r\n");
            Thread.Sleep(1000);
        }
    }

发送数据:

 /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool sendinfo(string SendMsg)
        {
            if (ComPort.IsOpen)
            {
                try
                {
                    byte[] ThisBT = Encoding.Default.GetBytes(SendMsg + "\r\n");
                    ComPort.Write(ThisBT, 0, ThisBT.Length);
                    this.LBSatic.Text = $"发送成功。";
                    return true;
                }
                catch (Exception ex)
                {
                    this.LBSatic.Text = $"发送失败。" + ex.Message;
                    return false;
                }
            }
            else
            {
                this.LBSatic.Text = $"请先连接串口。";
                return false;
            }
        }  

我的遍历所有的com口,确定可用再返回。

private void _init_devcom_tran()
        {
            string[] Ports = SerialPort.GetPortNames();
            if (Ports.Length > 0)
            {
                foreach (string One in Ports)
                {
                    if (_transport_com_dev != null && _transport_com_dev.IsOpen)
                    {
                        _transport_com_dev.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.SPort_DataReceived);
                        _transport_com_dev.Close();
                        //SPort.Dispose();
                    }
                    _transport_com_dev = new SerialPort();
                    _transport_com_dev.PortName = One; //串口名 COM1
                    _transport_com_dev.BaudRate = 9600; //波特率  9600
                    _transport_com_dev.DataBits = 8; // 数据位 8
                    _transport_com_dev.ReadBufferSize = 4096;
                    _transport_com_dev.StopBits = StopBits.One;
                    _transport_com_dev.RtsEnable = true;//设置RTS位高电平
                    _transport_com_dev.WriteTimeout = 800;//设定写超时
                    _transport_com_dev.ReadTimeout = 800;//设定读超时
                    _transport_com_dev.Parity = Parity.None;
                    _transport_com_dev.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SPort_DataReceived);
                    _transport_com_dev.Open();
                  
                    try
                    {
                        if (_transport_com_dev.IsOpen)
                        {
                            byte[] sendGet = Encoding.UTF8.GetBytes("DATA\n");
                            _transport_com_dev.Write(sendGet, 0, sendGet.Length);
                            Thread.Sleep(100);
                            byte[] b = new byte[_transport_com_dev.BytesToRead];
                            string ret = Encoding.GetEncoding("GB2312").GetString(b);//如果获取为空字符则为没有使用
                            if (!string.IsNullOrWhiteSpace(ret))
                            {
                                ComName = One;
                                this.label15.Text = Langs.RM.GetString("Connected") + ComName;
                                this.name = _transport_com_dev.PortName;
                                break;
                            }
                            else
                            {
                                continue;
                            }

                        }
                        else
                        {
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {

                    } 
                }
                if (string.IsNullOrWhiteSpace(ComName))
                {
                    this.label15.Text = Langs.RM.GetString("Connected failed");
                }
            }
            else
            {
                this.label15.Text = Langs.RM.GetString("Connected failed");
            }
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值