上位机和底层的通信方式是同步的,上位机第一次发送可以完成。
串口接收到返回的信息进行判断,然后直接在接收函数中再次发送。
设置断点可以完成整个过程,但是直接运行,就卡死。
目前发现是接收到返回的信息后再次发送的时候,卡死。
请问如何解决?
//串口接收事件
private void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) {
while (comm.BytesToRead > 0) {
rx_Buf[rx_Cnt++] = (byte)comm.ReadByte();
}
if (rx_Cnt == 8) { //8个字节 接收完成
rx_Cnt = 0;
} else {
return;
}
Console.WriteLine("-----接收发回帧-----");
if (rx_Buf[0] == 0xFF && rx_Buf[1] == 0xFE && rx_Buf[6] == 0xFE && rx_Buf[7] == 0xFF) {
switch (rx_Buf[4]) {
case 0x01:
if (rx_Buf[5] == 0xAA) {
flag_State = FLAG_STATUS.STATE_WRITE;
send_file = true;
Console.WriteLine("-----验证成功 开始发送文件-----");
} else {
MessageBox.Show("0x01 失败");
}
break;
case 0x02:
if (rx_Buf[5] == 0xAA)
send_file = true;
else
MessageBox.Show("0x02 失败");
break;
default:
MessageBox.Show("失败");
break;
}
//验证通过,发送文件
if (send_file) {
if (transLen < fileLenth) {
int len = fs.Read(sendBuf, 5, 1024);
Console.WriteLine("len:" + len.ToString());
if (len > 0) {
uint crcValue = Fn_GetCRC32(sendBuf, 5, 1024);
byte[] crcBytes = new byte[4];
for (int i = 4; i > 0; i--) {
crcBytes[4 - i] = (byte)(crcValue & 0xFF);
crcValue >>= 8;
}
for (int i = 0; i < 4; i++) {
sendBuf[1029 + i] = crcBytes[i];
}
transLen += len;
comm.DiscardOutBuffer();
Console.WriteLine("-----清空发送缓冲区-----");
comm.Write(sendBuf, 0, sendBuf.Length);
Console.WriteLine("transLen:" + transLen.ToString());
Console.WriteLine("------------------------------------");
}
} else {
MessageBox.Show("烧写完成");
try {
fs.Close();
comm.Close();
} catch (Exception) {
}
}
send_file = false;
}
}
}