title: Serial port communication in linux returns wrong answers
body: <p>I am trying to create a linux ubuntu program that will read data from tty serial port (COM port in windows). I'm not using USB adapter but actual COM port. This is my code for communication so far:</p>
  
  <pre><code>int OpenPort(void)
  {
     int fd; // file description for sp
  
     fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
  
     if(fd == -1) // port not opened 
     {
        printf("Error:\n%s.\n", strerror(errno));
     }
     else
     {
        fcntl(fd, F_SETFL, 0);
        printf("Success.\n");
     }
  
     return(fd);
  } // Open sp
  
  void Communicate(void)
  {
     struct termios settings;    
  
     tcgetattr( fd, &amp;settings );
  
     cfsetispeed(&amp;settings, B9600);    // Set bouds
     cfsetospeed(&amp;settings, B9600);
  
     settings.c_cflag &amp;= ~PARENB;    // set no parity, stop bits, data bits
     settings.c_cflag &amp;= ~CSTOPB;
     settings.c_cflag &amp;= ~CSIZE;
     settings.c_cflag |= CS8;
  
     tcflush( fd, TCIFLUSH );
  
     if (tcsetattr(fd, TCSAFLUSH, &amp;settings)!= 0)
     {
        printf("Error message");
     }   
  
     //Create byte array
     unsigned char send_bytes[] = { 0x1, 0x6, 0x2, 0xAA, 0x2, 0x3, 0xB8, 0x4 };
  
     write(fd, send_bytes, sizeof(send_bytes));  // Send data
     printf("Data sent. \n");
  
     char buffer[64]; // buffer to receive data
  
     printf("I'm reading data...\n");
     int n = read(fd, buffer, sizeof(buffer));
  
     if (n &lt; 0)
       printf("Failed to read\n");
  
     int i; 
     printf("Showing data...\n");
  
     for(i=0; i&lt;sizeof(buffer); i++)
     {
        printf("Hex: %x\n", buffer[i]);
     } 
  
     printf("Closing...\n");
  
     close(fd);
  
     printf("All done!\n");
  }
  </code></pre>
  
  <p>I have several problems here:</p>
  
  <ol>
  <li>After I run program once it executes correctly but when I try to run it again it stops at "I'm reading data..." and won't start even after I restart computer. After some time it allows me to execute program again.</li>
  <li>After program returns data it should send me hex data like A7, 9F etc. but this gives me integer values.</li>
  <li>Should I and how do I clear buffer array to free memory</li>
  </ol>
  
  <p>Can anyone help with these problems?</p>