title: Redundancy when reading USB serial port (C;Mac OSX;Arduino)
body: <p>I'm writing a simple C program that can read data from a USB port that is connected to my Arduino device. The Arduino outputs data at a baud rate of 9600 in chunks of 4 bytes.</p>
  
  <p>I want the input from the Arduino to my computer to look something like this:</p>
  
  <p>136.134.132.130.129.127.126.124.121.119.117.115.113.111.</p>
  
  <p>However, I'm getting something like this:</p>
  
  <p>271.274.281..2.4062.4022.40225.4021</p>
  
  <p>Question: How do I get the input in my C program to neatly synchronize with out loosing data/ rereading data? Are there some kind of flags that could tell my program when the port has new data?</p>
  
  <p>Code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;   /* Standard input/output definitions */
  #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 */
  #include &lt;sys/types.h&gt;
  
  
  int open_port(void)
  {
    int fd; /* File descriptor for the port */
  
    fd = open("/dev/tty.usbmodemfd121", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1)
    {
      perror("open_port: Unable to open /dev/tty");
    }
    else
      fcntl(fd, F_SETFL, 0);
  
    struct termios options;
    tcgetattr(fd,&amp;options);
    cfsetospeed(&amp;options,B9600);
    options.c_cflag |=(CLOCAL | CREAD);
    tcsetattr(fd, TCSANOW, &amp;options);
  
    return (fd);
  }
  
  
  int main (){
  
      int i;
      for(i=0; i&lt;50; i++){
  
      fcntl(open_port(), F_SETFL, FNDELAY);
      char buf[5];
      size_t nbytes;
      ssize_t bytes_read;
  
      nbytes = sizeof(buf);
      bytes_read = read(open_port(), buf, nbytes);
      printf("%s ", buf);
      buf[0]=0;
      }
  
      return 0;
  
  }
  </code></pre>