在使用下述代码中、串口设备一直发数据,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");
}
c#串口通讯中serialPort_DataReceive读取数据并显示的使用方法:
答案:1 悬赏:20 手机版
解决时间 2021-02-05 05:32
- 提问者网友:鼻尖触碰
- 2021-02-04 11:10
最佳答案
- 五星知识达人网友:冷風如刀
- 2021-02-04 12:46
//你的循环条件有问题,当然会超了
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");
}
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");
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯