串口助手接受到的数据为 “[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);
}