Lightsout
Lightsout

Reputation: 3757

Decoding binary data from serial port

I am trying communicate with a Simplebgc board via serial on my Raspberry Pi. I am writing commands to the board which seems to be working but I need help decoding the binary response. Why am I getting 23 byes when the guide seems to add to 18? I am new to both C and binary.

enter image description here

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;
}

output:

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

Upvotes: 1

Views: 1309

Answers (1)

Loki Astari
Loki Astari

Reputation: 264471

The response is a message which has a 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

This gives you 23 bytes. 4 Bytes header. Body. 1 byte body checksum.

Upvotes: 2

Related Questions