title: Reading from Arduino serial port using RS232 connection and C code
body: <p>I have an Arduino Uno running the following code:</p>
  
  <pre><code>byte data;
  
  void setup(){
     Serial.begin(9600);
  }
  
  void loop(){
  
    data = 0xAA;
    Serial.write(data);
    delay(1000);
  }
  </code></pre>
  
  <p>It's really simple, just writing the value of 0xAA to the Serial TX pin every second.</p>
  
  <p>I've connected the Serial TX pin to pin 3 of a DB9 breakout cable, and pin 5 of the breakout cable to ground on the Arduino. The serial cable is then plugged in to a USB-Serial converter that connects to my laptop's USB port. I know from past experience that the USB-Serial converter is reliable and won't distort data.</p>
  
  <p>On my laptop I'm running the code below, and I expect to see AA printed to the screen every second, however, I'm seeing the value 15 instead. Is there anything wrong with my code, or is this caused by differing voltage levels?</p>
  
  <pre><code> void dump_packet(void* packet, int len)
   {
  u_int8_t* bytes = (u_int8_t*)packet;
  int i = 0;  
  
  while (i &lt; len){
      if (i == len-1){
          printf("%02X-", bytes[i++]);
      }
      else{
          printf("%d", bytes[i++]);
          }
  }   
   }
  
   int ttySetRaw(int fd, struct termios *prevTermios)
   {
   struct termios t;
   if (tcgetattr(fd, &amp;t) == -1)
    return -1;
   if (prevTermios != NULL)
   *prevTermios = t;
   t.c_lflag &amp;= ~(ICANON | ISIG | IEXTEN | ECHO);
   t.c_iflag &amp;= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
   INPCK | ISTRIP | IXON | PARMRK);
   t.c_oflag &amp;= ~OPOST; /* Disable all output processing */
   t.c_cc[VMIN] = 1; /* Character-at-a-time input */
   t.c_cc[VTIME] = 0; /* with blocking */
   if (tcsetattr(fd, TCSAFLUSH, &amp;t) == -1)
     return -1;
   return 0;
   }
  
   int main()
   {
     struct termios  tty;
     struct termios  savetty;
     speed_t     spd;
     unsigned int    sfd;
     unsigned char   buf[12];
     int reqlen = 79;
     int     rc;
     int     rdlen;
     int success;
  
     sfd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
     rc = tcgetattr(sfd, &amp;tty);
     if (rc &lt; 0) {
      printf("failed to get attr: %d, %s", rc, strerror(errno));
      exit (-2);
     }
     savetty = tty;    /* preserve original settings for restoration */
  
     success = ttySetRaw(sfd, &amp;tty);
     spd = B9600;
     cfsetospeed(&amp;tty, (speed_t)spd);
     cfsetispeed(&amp;tty, (speed_t)spd);
  
     if (sfd &gt; 0 &amp;&amp; success == 0){
  printf("TTY set up ready to Read:\n\n");
     }
  
     memset(&amp;buf[0], 0, sizeof(buf));
  
     do {
      rdlen = read(sfd, buf, reqlen);
    if (rdlen != -1){
      printf("Read %d bytes\n", rdlen);
      dump_packet( buf, rdlen);
     }
  
     } while (1);
  
     tcsetattr(sfd, TCSANOW, &amp;savetty);
     close(sfd);
     exit (0);
  
     return 0;
     }
  </code></pre>