c#串口通讯中serialPort_DataReceive读取数据并显示的使用方法:
在使用下述代码中、串口设备一直发数据,PC读取的时候i总是会超出数组索引。求助解决办法。privatevoidserialPort1_DataReceived(objec...
在使用下述代码中、串口设备一直发数据,PC读取的时候i总是会超出数组索引。求助解决办法。
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
MsgRectextBox.AppendText("Recieved:" + "\r\n\r\n");
//int Length = serialPort1.BytesToRead;
byte[] MsgRec = new byte[1024*1024];
int Length = -1;
int i = 0;
serialPort1.Read(MsgRec, 0, 1024);
//builder.Clear();
MsgRecCount++;
while (MsgRec[2 + i] != 0xFF)
{
i++;
}
Length = Length + i + 4;
i = 0;
byte[] MsgRec1 = new byte[Length];
for (int j = 0; j < Length; j++)
{
MsgRec1[j] = MsgRec[j];
}
MsgRec1 = dataAnalyzer.ChangFE012FFFE002FE(MsgRec.Take(Length).ToArray());
string result = dataAnalyzer.ToHexString(MsgRec1);
MsgRectextBox.AppendText(MsgRecCount.ToString() + "-" + DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss:fff]") + "\r\n");
MsgRectextBox.AppendText(result + "\r\n");
} 展开
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
MsgRectextBox.AppendText("Recieved:" + "\r\n\r\n");
//int Length = serialPort1.BytesToRead;
byte[] MsgRec = new byte[1024*1024];
int Length = -1;
int i = 0;
serialPort1.Read(MsgRec, 0, 1024);
//builder.Clear();
MsgRecCount++;
while (MsgRec[2 + i] != 0xFF)
{
i++;
}
Length = Length + i + 4;
i = 0;
byte[] MsgRec1 = new byte[Length];
for (int j = 0; j < Length; j++)
{
MsgRec1[j] = MsgRec[j];
}
MsgRec1 = dataAnalyzer.ChangFE012FFFE002FE(MsgRec.Take(Length).ToArray());
string result = dataAnalyzer.ToHexString(MsgRec1);
MsgRectextBox.AppendText(MsgRecCount.ToString() + "-" + DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss:fff]") + "\r\n");
MsgRectextBox.AppendText(result + "\r\n");
} 展开
1个回答
展开全部
//你的循环条件有问题,当然会超了
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
MsgRectextBox.AppendText("Recieved:" + "\r\n\r\n");
//int Length = serialPort1.BytesToRead;
byte[] MsgRec = new byte[1024 * 1024];
int Length = -1;
int i = 0;
serialPort1.Read(MsgRec, 0, 1024);
//builder.Clear();
MsgRecCount++;
while (MsgRec[2 + i] != 0xFF)
{
i++;
if (i + 2 >= 1024)//大于等于数组长度时退出循环
break;//加上这个应该就不会超了
}
Length = Length + i + 4;
i = 0;
byte[] MsgRec1 = new byte[Length];
for (int j = 0; j < Length; j++)
{
MsgRec1[j] = MsgRec[j];
}
MsgRec1 = dataAnalyzer.ChangFE012FFFE002FE(MsgRec.Take(Length).ToArray());
string result = dataAnalyzer.ToHexString(MsgRec1);
MsgRectextBox.AppendText(MsgRecCount.ToString() + "-" + DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss:fff]") + "\r\n");
MsgRectextBox.AppendText(result + "\r\n");
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询