从串口解码二进制数据

Decoding binary data from serial port

我正在尝试通过我的 Raspberry Pi 上的串口与 Simplebgc 板进行通信。我正在向似乎可以正常工作的电路板写入命令,但我需要帮助解码二进制响应。当指南似乎增加到 18 时,为什么我得到 23 次轮空?我对 C 和二进制都是新手。

void sendCommand() {
    int fd;

    if ((fd = serialOpen ("/dev/ttyS0", 115200)) < 0) {
        //fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno));
        cout<<"Unable to open serial device"<<endl;
        return;
    }

    unsigned char motor_on[6] = {0x3E, 0x4D, 0x01, 0x4E,0x01, 0x01}; //MOTOR ON
    unsigned char motor_off[6] = {0x3E, 0x6D, 0x01, 0x6E,0x01, 0x01};  //MOTOR OFF
    unsigned char board_info[6] = {0x3E, 0x56, 0x01, 0x57, 0x01, 0x01};  //BOARD_INFO

    serialFlush(fd);

    // Send command to grab board info
    write(fd, board_info, 6);
    sleep(2);

    // Read board response and print it
    char c;
    int counter = 0;
    while (read(fd, &c, 1) == 1) {
        //putchar(c);  // print out char    
        printf("%d ",c);
        counter++;
    }
    cout<<"\ncounter="<<counter<<endl;
    sleep(5);


}

int main() {
    sendCommand();
    return 0;
}

输出:

pi@raspberrypi:~/myPrograms/SerialGPIOExamples/c++/SBGC_board $ ./serialSBGCTest 62 86 18 104 30 70 10 0 27 0 0 0 0 0 0 0 0 0 0 0 0 0 137 counter=23

响应是一条包含 header:

的消息

Message format
Each command consists of the header and the body, both with checksum. Commands with the wrong header or body checksum, or with the body size that differs from expected, should be ignored. Parser should scan incoming datastream for the next start character and try to restore synchronization from it.

Header:
    Start Character    1u
    Command ID         1u
    Payload Size       1u
    Header Checksum    1u
Body
    18 bytes as defined by you.
    Body Checksum      1u

这为您提供了 23 个字节。 4 个字节 header。 Body。 1 字节 body 校验和。