一个简单方法解决串口接收一包完整数据问题

     最近在写C#的串口时,明明是一包数据SerialPort事件非要产生一次或者多次事件来接收,导到一包数据分成两包数据 ,后来改成线程处理。废话不多说直接上程序。

如果有问题可以直接回复,谢谢,延时时间不一定是10ms,如果要求更高可以减少延时时间。

public partial class mainWin : Form
{
    const int dataMaxLen = 1024;

    Thread _readThread;
    bool _keepReading;

    public SerialPort serialPort1 = new SerialPort();

    //延时10ms左右时间,再看串口接收BUFF的数据个数是否改变,如果有改变则继续延时,如果不变则读取数据
    private int uartRxFlag = 0;


    public mainWin()
    {
        InitializeComponent();
    }

    private void openUart()
    {
        serialPort1.PortName = "COM1";
        serialPort1.BaudRate = 9600;
        try
        {
             serialPort1.Open();
        }
        catch
        {
            MessageBox.Show("串口被占用!");

             return;
         }
        _keepReading = true;
        _readThread = new Thread(uartReceiveHandle);
        _readThread.Start();
    }
     private bool uartSendData(string pData)
        {
            //串口数据发送
            if (!serialPort1.IsOpen)
            {
                MessageBox.Show("未打开串口");

                return false;
            }
            if (pData == null || pData.Length == 0)
                return false;

            //将字符串转化成数组
            byte[] pBuff = strToHexByte(pData);

            //发送数据
            try 
            {
                serialPort1.Write(pBuff, 0, pBuff.Length);
            }
            catch
            {
                MessageBox.Show("数据发送失败!");
            }

            return false;
        }

        private void uartReceiveHandle()
        {
            while (_keepReading)
            {
                string uartRxStr = string.Empty;
                byte[] readBuffer = OnDataReceived();
                if (readBuffer != null)
                {
                    uartRxStr = byteToStr(readBuffer);
                }
                else
                {
                    TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 5);
                    Thread.Sleep(waitTime);
                }
            }
        }

        private byte[] OnDataReceived()
        {
            if (!serialPort1.IsOpen)
            {
                return null;
            }
            int n = serialPort1.BytesToRead;
            if (n == 0)
            {
                return null;
            }
            // ==============关键的一步==============
            if (uartRxFlag != n)
            {
                uartRxFlag = n;

                return null;
            }
            //====================================
            uartRxFlag = 0;
            byte[] readBuffer = new byte[n];
            try
            {
                serialPort1.Read(readBuffer, 0, n);
            }
            catch
            {
                MessageBox.Show("接收失败!");
            }

            return readBuffer;
        }

        private byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";

            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

            return returnBytes;
        }

        private string byteToStr(byte[] pByte)
        {
            string hexString = string.Empty;

            if (pByte != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i=0; i<pByte.Length; i++)
                {
                    strB.Append(pByte[i].ToString("X2"));
                }
                string str = strB.ToString();
                hexString = string.Join(" ", Regex.Matches(str, @"..").Cast<Match>().ToList());
            }

            return hexString;
        }

}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页