title: Reading and writing to serial port in C on Linux
body: <p>I'm trying to <strong>send/receive data over an USB Port using FTDI</strong>, so I need to handle serial communication using C/C++. I'm working on <strong>Linux</strong> (Ubuntu).</p>
  
  <p>Basically, I am connected to a device which is listening for incoming commands. I need to send those commands and read device's response. Both commands and response are <strong>ASCII characters</strong>.</p>
  
  <p>Everything works fine using GtkTerm but, when I switch to C programming, I encounter problems.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;      // standard input / output functions
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;     // string function definitions
  #include &lt;unistd.h&gt;     // UNIX standard function definitions
  #include &lt;fcntl.h&gt;      // File control definitions
  #include &lt;errno.h&gt;      // Error number definitions
  #include &lt;termios.h&gt;    // POSIX terminal control definitions
  
  /* Open File Descriptor */
  int USB = open( "/dev/ttyUSB0", O_RDWR| O_NONBLOCK | O_NDELAY );
  
  /* Error Handling */
  if ( USB &lt; 0 )
  {
  cout &lt;&lt; "Error " &lt;&lt; errno &lt;&lt; " opening " &lt;&lt; "/dev/ttyUSB0" &lt;&lt; ": " &lt;&lt; strerror (errno) &lt;&lt; endl;
  }
  
  /* *** Configure Port *** */
  struct termios tty;
  memset (&amp;tty, 0, sizeof tty);
  
  /* Error Handling */
  if ( tcgetattr ( USB, &amp;tty ) != 0 )
  {
  cout &lt;&lt; "Error " &lt;&lt; errno &lt;&lt; " from tcgetattr: " &lt;&lt; strerror(errno) &lt;&lt; endl;
  }
  
  /* Set Baud Rate */
  cfsetospeed (&amp;tty, B9600);
  cfsetispeed (&amp;tty, B9600);
  
  /* Setting other Port Stuff */
  tty.c_cflag     &amp;=  ~PARENB;        // Make 8n1
  tty.c_cflag     &amp;=  ~CSTOPB;
  tty.c_cflag     &amp;=  ~CSIZE;
  tty.c_cflag     |=  CS8;
  tty.c_cflag     &amp;=  ~CRTSCTS;       // no flow control
  tty.c_lflag     =   0;          // no signaling chars, no echo, no canonical processing
  tty.c_oflag     =   0;                  // no remapping, no delays
  tty.c_cc[VMIN]      =   0;                  // read doesn't block
  tty.c_cc[VTIME]     =   5;                  // 0.5 seconds read timeout
  
  tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ &amp; ignore ctrl lines
  tty.c_iflag     &amp;=  ~(IXON | IXOFF | IXANY);// turn off s/w flow ctrl
  tty.c_lflag     &amp;=  ~(ICANON | ECHO | ECHOE | ISIG); // make raw
  tty.c_oflag     &amp;=  ~OPOST;              // make raw
  
  /* Flush Port, then applies attributes */
  tcflush( USB, TCIFLUSH );
  
  if ( tcsetattr ( USB, TCSANOW, &amp;tty ) != 0)
  {
  cout &lt;&lt; "Error " &lt;&lt; errno &lt;&lt; " from tcsetattr" &lt;&lt; endl;
  }
  
  /* *** WRITE *** */
  
  unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
  int n_written = write( USB, cmd, sizeof(cmd) -1 );
  
  /* Allocate memory for read buffer */
  char buf [256];
  memset (&amp;buf, '\0', sizeof buf);
  
  /* *** READ *** */
  int n = read( USB, &amp;buf , sizeof buf );
  
  /* Error Handling */
  if (n &lt; 0)
  {
       cout &lt;&lt; "Error reading: " &lt;&lt; strerror(errno) &lt;&lt; endl;
  }
  
  /* Print what I read... */
  cout &lt;&lt; "Read: " &lt;&lt; buf &lt;&lt; endl;
  
  close(USB);
  </code></pre>
  
  <p>What happens is that <code>read()</code> returns 0 (no bytes read at all) or block until timeout (<code>VTIME</code>). I'm assuming this happens because <code>write()</code> does not send anything. In that case, device wouldn't receive command and I cannot receive response. In fact, turning off the device while my program is blocked on reading actually succeded in getting a response (device sends something while shutting down).</p>
  
  <p>Strange thing is that adding this </p>
  
  <pre><code>cout &lt;&lt; "I've written: " &lt;&lt; n_written &lt;&lt; "bytes" &lt;&lt; endl; 
  </code></pre>
  
  <p>right after <code>write()</code> call, I receive:</p>
  
  <pre><code>I've written 6 bytes
  </code></pre>
  
  <p>which is exactly what I expect. Only my program doesn't work as it should, like <strong>my device cannot receive what I'm actually writing</strong> on port.</p>
  
  <p>I've tried different things and solution, also regarding data types (I've tried using std::string, such as <code>cmd = "INIT \r"</code> or <code>const char</code>) but nothing really worked.</p>
  
  <p>Can someone tell me where I'm wrong?</p>
  
  <p>Thank you in advance.</p>
  
  <p><strong>EDIT:</strong>
  Previously version of this code used </p>
  
  <p><code>unsigned char cmd[] = "INIT \n"</code></p>
  
  <p>and also <code>cmd[] = "INIT \r\n"</code>. I changed it because command sintax for my device is reported as </p>
  
  <p><code>&lt;command&gt;&lt;SPACE&gt;&lt;CR&gt;</code>. </p>
  
  <p>I've also tried avoiding the <code>O_NONBLOCK</code> flag on reading, but then I only block until forever. I've tried using <code>select()</code> but nothing happens. Just for a try, I've created a waiting loop until data is avaliable, but my code never exit the loop. Btw, waiting or <code>usleep()</code> is something I need to avoid. Reported one is only an excerpt of my code. <strong>Complete code needs to work in a real-time environment</strong> (specifically OROCOS) so I don't really want sleep-like function.</p>