Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

How can i use serial port to send 3 byte to the Arduino with C++, Linux

I want to use the serial port to send 3 bytes to Arduino. The 1st byte contains command, 2nd byte and 3 bytes contain the data. I programmed my code that way, but I always have problems. I don't know if the Arduino received my data or not. Because he does not do anything I want. I'm new to this topic. Please help me. I use Arduino Mega and Linux Ubuntu.

Here's what I want to send to the Arduino

int serialport_init(const char* serialport, int baud)
{
   struct termios toptions;
   int fd;

   fd = open(serialport, O_RDWR | O_NOCTTY | O_NONBLOCK);
   if (fd == -1)  
    {
    perror("init_serialport: Unable to open port ");
    return -1;
    }

     if (tcgetattr(fd, &toptions) < 0) 
    {
    perror("init_serialport: Couldn't get term attributes");
    return -1;
    }

    cfsetispeed(&toptions, baud); //baud is B115200
    cfsetospeed(&toptions, baud);

    // 8N1
    toptions.c_cflag &= ~PARENB;
    toptions.c_cflag &= ~CSTOPB;
    toptions.c_cflag &= ~CSIZE;
    toptions.c_cflag |= CS8;
    // flow control active
    toptions.c_cflag |= CRTSCTS;

    toptions.c_cflag |= CREAD | CLOCAL;  
    toptions.c_iflag &= ~(IXON | IXOFF | IXANY); 

    toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
    toptions.c_oflag &= ~OPOST; // make raw
    toptions.c_cc[VMIN]  = 1;
    toptions.c_cc[VTIME] = 5;
   /* Make raw */
    tcsetattr(fd, TCSANOW, &toptions);
    if( tcsetattr(fd, TCSAFLUSH, &toptions) < 0) {
    perror("init_serialport: Couldn't set term attributes");
    return -1;
    }

 return fd;


  }


 int serialport_write(int fd, uint8_t speed, uint8_t steer) 
 {  
    uint8_t drive=0x01;
    uint8_t packet[3] = {drive,speed,steer};
    int n = write(fd,&packet[0],3);
    if (n != 3) return -1;
    return 0;
  }

Comments