hanshierlou
hanshierlou
2017-04-21 01:49

C#串口接收有时候会捕捉到“函数不正确”错误

10
  • c#
  • 串口通讯
    /// <summary>
    /// 發送一條16進制指令到繼電器
    /// </summary>
    private void SendDataToJiDianQi(string strSend)
    {
        try
        {
            string[] strArray = strSend.Split(' '); //01 02 00 00 00 09 B8 0C
            byte[] byteBuffer = new byte[strArray.Length];
            int count = 0;
            for (int i = 0; i < strArray.Length; i++)        //对获取的字符做相加运算
            {
                byte[] bytesOfStr = Encoding.Default.GetBytes(strArray[i]);
                int decNum = Convert.ToInt32(strArray[i], 16);
                byteBuffer[count] = Convert.ToByte(decNum);
                count++;
            }
            if (_spJiDianQi.IsOpen)
            {
                _spJiDianQi.DiscardInBuffer();
                _spJiDianQi.DiscardOutBuffer();//当你的程序在窗口发送一帧数据(所谓一帧是指由多个字节组成的有逻辑意义的数据)过程中检测到串口发送错误,如果让串口继续发生就没有意义了,这个时候可以用SerialPort.DiscardOutBuffer方法来清除已经进入发送缓冲区的错误数据;
                _spJiDianQi.Write(byteBuffer, 0, byteBuffer.Length);
            }
            else
            {
                WriteLog("繼電器串口打開失敗!");
            }
        }
        catch (Exception ex)
        {              
            WriteLog("發送指令給繼電器異常:" + ex.Message);
            if (_spJiDianQi.IsOpen)
            {
                _spJiDianQi.DiscardOutBuffer();
            }
        }
    }

    /// <summary>
    /// 接收繼電器串口數據的方法
    /// </summary>
    private string ReceiveDataFromJiDianQi()
    {
        string value = "";
        try
        {
            if (_spJiDianQi.IsOpen)
            {

                Thread.Sleep(50); //為了接收數據的完整性
                int byteNum = _spJiDianQi.BytesToRead;
                if (byteNum > 0)
                {
                    byte[] receivedData = new byte[byteNum];        //创建接收字节数组
                    if (receivedData.Length > 0)
                    {
                        _spJiDianQi.Read(receivedData, 0, receivedData.Length);         //读取数据
                        for (int i = 0; i < receivedData.Length; i++)
                        {
                            value += receivedData[i].ToString("X2");  //16进制显示
                        }

                        //_spJiDianQi.DiscardInBuffer();//当你的程序在接收一帧数据时发生错误,如果再让串口继续接收也没有意义了,这个时候可以用SerialPort.DiscardInBuffer方法来清除已经进入接收缓冲区的错误数据了
                    }
                    else
                    {
                        WriteLog("讀取繼電器串口數據時,沒有數據返回。");
                    }
                }
            }
            else
            {
                WriteLog("繼電器串口打開失敗!");
            }
        }
        catch (Exception ex)
        {
            WriteLog("讀取繼電器串口數據方法異常:" + ex.Message);
            //if (_spJiDianQi.IsOpen)
            //{
            //    _spJiDianQi.DiscardInBuffer();
            //}
        }
        return value;
    }
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答