winform串口控件serialPort1的使用

serialPort1 控件使用的关键点主要有三:

1、配置串口号
2、配置数据接收事件
3、打开串口

关键代码如下:

        private void Form1_Load(object sender, EventArgs e)
        {
            serialPort1.PortName = "COM1";           
            serialPort1.DataReceived += SerialPort1_DataReceived;
            serialPort1.Open();
        }

        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                int len = serialPort1.BytesToRead;
                Byte[] buf = new byte[len];
                int length = serialPort1.Read(buf, 0, len);
                string result = System.Text.Encoding.ASCII.GetString(buf);
                UpdateTextBox(result);
            }
            catch (Exception ex)
            {
                UpdateTextBox(ex.Message);
            }

        }

  

本用例用到测试工具:

Serial Port  

pwd: 3gkk

 

posted @ 2018-10-09 14:33  早起Abc  阅读(3457)  评论(0编辑  收藏  举报