Search code examples
c++libserial

C++ libserial skipping 0x09


I am attempting to read data over serial from a Pixhawk flight controller which communicates via the Mavlink protocol. It sends 17 bytes, the first three being 0xFE, 0x09 followed by a counter that increments every message. I have confirmed this with GtkTerm.

However when I run the following code, 0x09 (the second byte) is always skipped so only 16 bytes of each 17 byte message is received.

Any ideas? Thanks, James.

LibSerial::SerialStream pixhawkSerial;

pixhawkSerial.Open("/dev/ttyACM0");

pixhawkSerial.SetBaudRate( LibSerial::SerialStreamBuf::BAUD_57600 ) ;

pixhawkSerial.SetCharSize( LibSerial::SerialStreamBuf::CHAR_SIZE_8 );

pixhawkSerial.SetNumOfStopBits(1);

pixhawkSerial.SetParity( LibSerial::SerialStreamBuf::PARITY_NONE ) ;

pixhawkSerial.SetFlowControl( LibSerial::SerialStreamBuf::FLOW_CONTROL_NONE );

char next_byte [100];
int i = 0;
while (i<100){
    if( pixhawkSerial.rdbuf()->in_avail() > 0 ){
        pixhawkSerial >> next_byte[i];
        i++;
    }
    else cout << "No data" << endl;
}

Solution

  • Wasn't able to get libserial to work, however I gave temios a go and it worked without issues.

    Attached is the working code.

    int fd;
    struct termios oldAtt, newAtt;
    fd = open("/dev/ttyACM0", O_RDWR  | O_NOCTTY | O_NDELAY);
    
    tcgetattr(fd, &oldAtt);
    memset(&newAtt, 0, sizeof(newAtt));
    newAtt.c_cflag = CRTSCTS | CS8 | CLOCAL | CREAD;
    newAtt.c_iflag = IGNPAR;
    newAtt.c_ispeed = B57600;
    newAtt.c_oflag = 0;
    newAtt.c_ospeed = B57600;
    newAtt.c_lflag = 0;
    
    newAtt.c_cc[VTIME] = 0;
    newAtt.c_cc[VMIN] = 1;
    
    tcflush(fd, TCIOFLUSH);
    tcsetattr(fd, TCSANOW, &newAtt);
    
    char rBuffer;
    char next_byte [100];
    int i=0;
    int dataReceived;
    
    while (i<100) {
        dataReceived = read(fd,&rBuffer,1);
        if (dataReceived>0){
            next_byte[i] = rBuffer;
            i++;
        }
    }
    
    tcsetattr(fd,TCSANOW,&oldAtt);
    close(fd);