【C# 串口助手接收数组数据并进行处理】

串口助手接受到的数据为 “[123,456,789]” 进行处理后添加到数组中。

    private List<byte> buffer = new List<byte>(4096);
    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        int n = serialPort1.BytesToRead;
        byte[] buf = new byte[n];
        serialPort1.Read(buf, 0, n);

        buffer.AddRange(buf);
        int index = 0;
        while(buffer.Count >= 4)
        {
            if(buffer[0] == 0x5B) //判断收到的首字符 [
            {
                if(buffer[index] != 0x5D) //直到收到尾字符为 ] 停下
                {
                    index++;
                    if(index >= buffer.Count)
                    {
                        break;
                    }
                }
                else
                {
                    byte[] ReceiveBytes = new byte[index + 1];
                    buffer.CopyTo(0,ReceiveBytes,0,index+1); 
                    RunReceiveDataCallback(ReceiveBytes);
                    buffer.RemoveRange(0, index); //数据处理
                }
            }
            else
            {
                buffer.RemoveAt(0);//首字符不是我们想要的,删除
            }
        }

    }

    private void RunReceiveDataCallback(byte[] ReceiveBytes)
    {
        string str = Encoding.Default.GetString(ReceiveBytes);
        int[] arr;
        string str2 = str.Substring(1, str.Length - 2);
        string[] str3 = str2.Split(',');
        arr = Array.ConvertAll(str3, int.Parse);
        addValue(arr);
    }
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值