title: Clearing the serial port's buffer
body: <p>This is what my function looks like to open the serial port (using Ubuntu 12.04):</p>
  
  <pre><code>int open_port(void)
  {
    int fd; /* File descriptor for the port */
  
    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
  
    if (fd == -1)
    {
     // Could not open the port.          
     perror("open_port: Unable to open /dev/ttyUSB0 - ");
    }
    else
      fcntl(fd, F_SETFL, 0);
  
    struct termios options;
  
    tcgetattr(fd, &amp;options); 
    //setting baud rates and stuff
    cfsetispeed(&amp;options, B19200);
    cfsetospeed(&amp;options, B19200);
    options.c_cflag |= (CLOCAL | CREAD);
    tcsetattr(fd, TCSANOW, &amp;options);
  
    tcsetattr(fd, TCSAFLUSH, &amp;options);
  
    options.c_cflag &amp;= ~PARENB;//next 4 lines setting 8N1
    options.c_cflag &amp;= ~CSTOPB;
    options.c_cflag &amp;= ~CSIZE;
    options.c_cflag |= CS8;
  
    //options.c_cflag &amp;= ~CNEW_RTSCTS;
  
    options.c_lflag &amp;= ~(ICANON | ECHO | ECHOE | ISIG); //raw input
  
    options.c_iflag &amp;= ~(IXON | IXOFF | IXANY); //disable software flow control
  
    return (fd);
  }
  </code></pre>
  
  <p>What the problem is, is that when I run this program and if my serial device was already plugged in, the buffer has content in it. I need a way to clear the buffer before I start reading from it. I thought using <code>tcsetattr(fd, TCSAFLUSH, &amp;options);</code> would fix this problem, by flushing the IO buffers before initializing the port, but no such luck. Any insight?</p>