title: Raspberry Pi UART program in C using termios receives garbage (Rx and Tx are connected directly)
body: <p>I have a simple program written in C which uses termios to send a basic string to the Raspberry Pi UART and attempts to read and output the response. The Rx and Tx pins on the Raspberry Pi are connected with a jumper so whatever is sent should be immediately received.</p>
  
  <p>Despite the program outputting that it successfully sent and received 5 characters for the chosen string ('Hello'), trying to print the contents of the buffer just produces one or two garbage characters.</p>
  
  <p>The program:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;termios.h&gt;
  
  int main(int argc, char* argv[]) {
  
      struct termios serial;
      char* str = "Hello";
      char buffer[10];
  
      if (argc == 1) {
          printf("Usage: %s [device]\n\n", argv[0]);
          return -1;
      }
  
      printf("Opening %s\n", argv[1]);
  
      int fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);
  
      if (fd == -1) {
          perror(argv[1]);
          return -1;
      }
  
      if (tcgetattr(fd, &amp;serial) &lt; 0) {
          perror("Getting configuration");
          return -1;
      }
  
      // Set up Serial Configuration
      serial.c_iflag = 0;
      serial.c_oflag = 0;
      serial.c_lflag = 0;
      serial.c_cflag = 0;
  
      serial.c_cc[VMIN] = 0;
      serial.c_cc[VTIME] = 0;
  
      serial.c_cflag = B115200 | CS8 | CREAD;
  
      tcsetattr(fd, TCSANOW, &amp;serial); // Apply configuration
  
      // Attempt to send and receive
      printf("Sending: %s\n", str);
  
      int wcount = write(fd, &amp;str, strlen(str));
      if (wcount &lt; 0) {
          perror("Write");
          return -1;
      }
      else {
          printf("Sent %d characters\n", wcount);
      }
  
      int rcount = read(fd, &amp;buffer, sizeof(buffer));
      if (rcount &lt; 0) {
          perror("Read");
          return -1;
      }
      else {
          printf("Received %d characters\n", rcount);
      }
  
      buffer[rcount] = '\0';
  
      printf("Received: %s\n", buffer);
  
      close(fd);
  }
  </code></pre>
  
  <p>Outputs:</p>
  
  <pre><code>Opening /dev/ttyAMA0
  Sending: Hello
  Sent 5 characters
  Received 5 characters
  Received: [garbage]
  </code></pre>
  
  <p>I can't see any major problem with the code myself, but I might be wrong. I can successfully send and receive characters using PuTTY connected with the same settings, so it can't really be a hardware problem. Although I haven't tried it in PuTTY, trying to connect with anything less than 115200 baud with this program will result in nothing being received.</p>
  
  <p>Where am I going wrong?</p>