求助大佬!感谢!
1、只要串口接收到的数据流中存在0x1A,就会抛出“索引超出数组界限”。
2、关键代码如下:
private void Form1_Load(object sender, EventArgs e)
{
sp1.Parity = Parity.None;
sp1.BaudRate = int.Parse("9600");
sp1.ReceivedBytesThreshold = 5; //设置触发字节数
//---------------------------------------------------------------------
Control.CheckForIllegalCrossThreadCalls = false; //
sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived); //串口接收事件
sp1.DtrEnable = true;
sp1.RtsEnable = true;
sp1.ReadTimeout = 1000;
sp1.Close();
}
private void button_open_Click(object sender, EventArgs e)
{
try
{
sp1.Open();
}
catch
{
sp1.Close();
MessageBox.Show("没有此串口!");
}
}
void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (sp1.IsOpen)
{
byte[] byteRead = new byte[sp1.BytesToRead]; //获取串口接收缓冲区中字节数
try
{
Byte[] receivedData = new Byte[sp1.BytesToRead];
sp1.Read(receivedData, 0, receivedData.Length);
this.Invoke(new EventHandler(delegate
{
textBox1.Text = Convert.ToString(receivedData.Length);
}));
sp1.DiscardInBuffer(); //clear
//-------------------------------------------------
if (receivedData[0] == 0xAA && receivedData[1] == 0x55)
{
string Recostr = string.Empty;
if (DataType == 0)
Recostr = "Hex: " + arr2string(receivedData, 0, receivedData.Length);
else
Recostr = "Dec: " + arr2string(receivedData, 0, receivedData.Length);
RecodLine = DateTime.Now.ToString("G") + " " + Recostr;
this.Invoke(new EventHandler(delegate
{
listBoxAutoRefesh(RecodLine);
}));
receok = true;
}
}
catch (System.Exception ex)
{
sp1.DiscardInBuffer();
MessageBox.Show(ex.Message, "出错提示");
}
}
}
3、现象截图如下:
4、接收数据流验证过百来个字节,经实验,只要数据流中任何位置存在0x1A,都会抛出“索引超出数组界限”异常。