我正在编写一个程序来从连接到 PC 的旧 GPS 单元(Garmin Etrex Venture)捕获串行数据。在向设备发送“发送时间”数据包后,我使用来自 COM3 端口 (hCom) 的读取文件。
int read_packet() //READS PACKET FROM DEVICE hPort
{
unsigned char inbuff[64];
unsigned char inchar [1];
DWORD nb;
int j=0;
ReadFile(hPort, inbuff, 32, &nb, NULL); int k; for (j;j<25;j++) {printf("<read_packet> inbuff[%i] = %i \n",j,int(inbuff[j]));
//for (j=0;j<25;j++) {ReadFile(hPort, inchar, 1, &nb, NULL); printf("<read_packet> inchar[%i]: %i \n",j,int(inchar[0]));
}
return 0;
}
有效数据包以 0x10 开始,以 0x10 0x03 结束。我希望看到一个 ACK 数据包(0x06),然后是第二个包含实际时间的数据包。
当一次读取所有数据时inbuff
,读取在最后的 0x03 at 之后继续读取inbuff[21]
似乎是无意义的值:
<read_packet> inbuff[0] = 16
<read_packet> inbuff[1] = 6
<read_packet> inbuff[2] = 2
<read_packet> inbuff[3] = 10
<read_packet> inbuff[4] = 0
<read_packet> inbuff[5] = 238
<read_packet> inbuff[6] = 16
<read_packet> inbuff[7] = 3
<read_packet> inbuff[8] = 16
<read_packet> inbuff[9] = 14
<read_packet> inbuff[10] = 8
<read_packet> inbuff[11] = 9
<read_packet> inbuff[12] = 14
<read_packet> inbuff[13] = 225
<read_packet> inbuff[14] = 7
<read_packet> inbuff[15] = 22
<read_packet> inbuff[16] = 0
<read_packet> inbuff[17] = 12
<read_packet> inbuff[18] = 25
<read_packet> inbuff[19] = 176
<read_packet> inbuff[20] = 16
<read_packet> inbuff[21] = 3
<read_packet> inbuff[22] = 42
<read_packet> inbuff[23] = 0
<read_packet> inbuff[24] = 32
当我取消注释第二行并一次读取一个字符时,我收到了预期的 2 个数据包(尽管一直读取最终的 0x03):
<read_packet> inchar[0]: 16
<read_packet> inchar[1]: 6
<read_packet> inchar[2]: 2
<read_packet> inchar[3]: 10
<read_packet> inchar[4]: 0
<read_packet> inchar[5]: 238
<read_packet> inchar[6]: 16
<read_packet> inchar[7]: 3
<read_packet> inchar[8]: 16
<read_packet> inchar[9]: 14
<read_packet> inchar[10]: 8
<read_packet> inchar[11]: 9
<read_packet> inchar[12]: 14
<read_packet> inchar[13]: 225
<read_packet> inchar[14]: 7
<read_packet> inchar[15]: 22
<read_packet> inchar[16]: 0
<read_packet> inchar[17]: 12
<read_packet> inchar[18]: 0
<read_packet> inchar[19]: 201
<read_packet> inchar[20]: 16
<read_packet> inchar[21]: 3
<read_packet> inchar[22]: 3
<read_packet> inchar[23]: 3
<read_packet> inchar[24]: 3
谁能告诉为什么会发生第一种情况inbuff
?我想这是因为Readfile
不知道何时停止阅读。但是我不明白之后inbuff[21]
的附加值来自哪里。
谢谢。