title: Loss of data from Bluetooth to UART
body: <p>I am using <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/39778e.pdf" rel="nofollow">PIC18F87J11</a> and <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/rn-42-ds-v2.32r.pdf" rel="nofollow">RN42 Bluetooth module</a> with 38400  baud rate. I made an android app that connects to the Bluetooth module and sends some data from my phone to the Micrcontroller. Everything is good but I noticed sometimes I lose some data. The PIC18 is expecting about 100 characters, if the app sends those 100 characters there are no issues, but sometimes it sends about 98 characters. Then the PIC18 keeps waiting for 2 more characters, but the next time the app sends something its 100 characters long. </p>
  
  <p>This is causing the app to out of sync with the Microcontroller, since the first byte represents a command. I have about 20 ms delay between each characters I send but that didn't solve the problem. This doesn't happen all the time but when it happens it mess ups everything. I tried increasing the time delay which seems to be helpful but I don't want it to be too slow. </p>
  
  <p>What is causing some of the data to be lost and how do I fix it? </p>
  
  <p><strong>UART code and Interrupt</strong> </p>
  
  <pre><code>#define CLOCK_FREQ 8000000 
  #define BAUD_RATE 38400
  #define SPBRG_VAL   ( ((CLOCK_FREQ/BAUD_RATE)/16) - 1)
  
  void ConsoleInit(void)
  {
   TRISCbits.TRISC7 = 1;
   TRISCbits.TRISC6 = 0;
   TXSTA = 0x24;
   RCSTA = 0x90; // 0b10010000;
   SPBRG = SPBRG_VAL;
  }
  
  BYTE ConsoleGet(void)
  {
     if(RCSTAbits.OERR)
          {
          RCSTAbits.CREN = 0;   // Disable UART receiver
          RCSTAbits.CREN = 1;   // Enable UART receiver
          }
  
          return RCREG;
  }
  
  
  void timerInit (void)
  {
  // Time Period Achieved : 0.001s
  T0CONbits.T08BIT = 0;
  T0CONbits.T0CS = 0;
  T0CONbits.PSA = 1;
  TMR0H = 0xF8;
  TMR0L = 0x30;
  T0CONbits.TMR0ON = 1;
  }
  </code></pre>
  
  <p><strong>Interrupt Routine</strong> </p>
  
  <pre><code>if (TMR_IF) {
  TMR0H = 0xF8;
  TMR0L = 0x30;
    if (PIR1bits.RCIF )
             {
                  ProcessMenu(); // In this function I call ConsoleGet() and have switch statment 
             }
  
          if (INTCONbits.TMR0IE) {
              /* there was a timer overflow */
              PIR1bits.RCIF = 0;
  
          }
  
      }
  </code></pre>
  
  <p>Thanks!</p>