C# 上位机与硬件设备间的串口通讯

打开串口函数

  public bool OpenSerialPort_Weight(String COM, int BaudRate)
        {
            SerialPort serialPort_Weight = new SerialPort(COM, BaudRate);
            try
            {
                serialPort_Weight.ReadTimeout = 32;//读取时间
                serialPort_Weight.Open();//打开串口
                serialPort_Weight.DataReceived += new SerialDataReceivedEventHandler(Weight_DataReceived);//当有接收到数据时触发                                                     
                serialPort_Weight.ReceivedBytesThreshold = 1;
                return true;
            }
            catch
            {
                return false;
            }
        }

串口接收数据函数

   private void Weight_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = serialPort_Weight.BytesToRead;    //获取接收缓冲区的字节数`这里写代码片`
            byte[] buf = new byte[n];   //声明一个临时数组存储当前来的串口数据               
            serialPort_Weight.Read(buf, 0, n);  //从串口输入缓冲区读取一些字节,并将那些字节写入到字节数组buf中指定的偏移量处,要读取的字节数目
            //字节数组buf[]中就是接收的原始数据
              for (int j = 0; j < buf.Length; j++)
              {
                z1_16 += buf[j].ToString("X2") + " ";//将字节数组中的元素分别转化成16进制的2位字符数,中间加上空格   以ASCII码的形式发送数据
                if (1 < j && j < 8)//截取其中的6位数据位
                {
                     z2_asc += ((char)buf[j]).ToString();
                                try
                                {
                                    z3_int = int.Parse(z2_asc);//将字符串类型转化成整型
                                }
                                catch
                                {

                                }
            }

串口接收数据不完整问题

在串口接收函数中加入一小段延时

  Thread.Sleep(18);//缓冲区有数据就会触发此方法,但是会出现数据不全的情况,延时可让传过来的数据完全

猜你喜欢

转载自blog.csdn.net/chenchaozzu/article/details/81590551
今日推荐