我有两个应用程序通过串口通信。目标有一个导航的状态机。它将接收并丢弃数据,直到它获得消息字节(0xE3)的开始,然后处理数据直到消息字节(0x3E)结束。我对某些数据有疑问。我认为这是一个处理问题,而不是沟通问题。我也知道这很简单,但很难找到问题。
主机正在向目标发送数据。 bfr数据为:FlowLayoutPanel
{0xAA, 0xFF, 0x05, 'H', 'e', 'l', 'l', 'o'};
目标是使用select()和read()来接收数据。
byte = MSG_START_BYTE; // 0xE3
if (write(fd, &byte, 1) < 0)
return -1;
if (write(fd, bfr, bfr_len) < 0)
return -1;
if (write(fd, &crc, sizeof(crc)) < 0)
return -1;
byte = MSG_END_BYTE; // 0x3E
if (write(fd, &byte, 1) < 0)
return -1;
目标控制台输出为:
char rx_bfr[128];
uint8_t max_bytes_to_read = 1;
memset(rx_bfr, 0, strlen(rx_bfr));
...
printf("\tactivity...");
bytes_read = read(fd, rx_bfr, max_bytes_to_read);
if (bytes_read < 0)
return -1;
else if (bytes_read == 0)
return -1;
printf(" %d bytes to process...\n", bytes_read);
for (i = 0; i < bytes_read; i++)
{
printf("byte[%d] = 0x%x\n", i, rx_bfr[i]);
switch (state)
{
case SOM:
if (rx_bfr[i] == 0xE3)
...
所以在我的状态机中,if条件是寻找Waiting for message...
activity... 1 bytes to process...
byte[0] = 0xffffffe3
activity... 1 bytes to process...
byte[0] = 0xffffffaa
activity... 1 bytes to process...
byte[0] = 0xffffffff
activity... 1 bytes to process...
byte[0] = 0x5
activity... 1 bytes to process...
byte[0] = 0x48
activity... 1 bytes to process...
byte[0] = 0x65
activity... 1 bytes to process...
byte[0] = 0x6c
activity... 1 bytes to process...
byte[0] = 0x6c
activity... 1 bytes to process...
byte[0] = 0x6f
activity... 1 bytes to process...
byte[0] = 0xffffffd4
activity... 1 bytes to process...
byte[0] = 0xffffff81
activity... 1 bytes to process...
byte[0] = 0x1a
activity... 1 bytes to process...
byte[0] = 0x3c
activity... 1 bytes to process...
byte[0] = 0x3b
activity... 1 bytes to process...
byte[0] = 0x3e
作为SOM,但第一个&#34;字节&#34;从printf看到的缓冲区是0xE3
。
答案 0 :(得分:5)
char rx_bfr[128];
在您的平台上char
已签名。值为0xE3的带符号的char为负,但值为0xE3的整数为正,因此它们不会相等。请改用unsigned char
。