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

     最近在写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;
        }

}

 

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kk电子粉丝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值