title: Read & write AT command to serial port in C
body: <p>I am trying to switch modem to command mode, write AT command and parse the response, but I am not too good with C and I do not understand what is wrong. The code I am calling is:</p>
  
  <pre><code>void switch_to_command_mode(int uart)
  {
      current_command_type = BTCommandTypeSwitchToATMode;
      char switchCmd[] = "\x2F\x2F\x2F";
      char emptySymbol[] = " ";
      char checkAT[] = "AT\r";
      ssize_t len = 0;
      write(uart, emptySymbol, strlen(emptySymbol));
      sleep(1);
      write(uart, switchCmd, strlen(switchCmd));
      sleep(1);
      write(uart, checkAT, strlen(checkAT));
  
      char buffer[255];  /* Input buffer */
      char *bufptr;      /* Current char in buffer */
      int  nbytes;
  
      bufptr = buffer;
  
      while (ioctl(uart, FIONREAD, (unsigned long)&amp;len) == 0 &amp;&amp; len &lt; 2) {
          warnx("waiting");
          usleep(1000);
      }
  
      while ((nbytes = read(uart, bufptr, buffer + sizeof(buffer) - bufptr - 1)) &gt; 0)
      {
          bufptr += nbytes;
          warnx("buffer %s", buffer);
          if (bufptr[-1] == '\n' || bufptr[-1] == '\r')
              break;
      }
  
      warnx("Final buffer: %s", buffer);
      if (strncmp(buffer, "OK", 2) == 0) {
          warnx("Great success!");
      }
  }
  </code></pre>
  
  <p>What I get as console output is:</p>
  
  <pre><code>waiting
  waiting
  buffer AT
  O      p �0
  buffer AT
  OK
   �0
  Final buffer: AT
  OK
   �0
  </code></pre>
  
  <p>According to documentation for the BT Module, the response should be in form of <code>&lt;CR&gt;&lt;LF&gt;OK&lt;CR&gt;&lt;LF&gt;</code>.</p>
  
  <p>Any guidance on why this is possibly happening and what can I do with that would be highly appreciated.</p>
  
  <p>P.S. I also already went through <a href="http://www.cmrr.umn.edu/~strupp/serial.html" rel="nofollow" title="Serial programming for POSIX OS">Serial programming for POSIX OS</a>.</p>