////////////////////////////////////////////////////////////////////////////////
//                        Laipac RF-24G / TXRX24G
//                   2.4GHz Wireless Servo Transmitter
//
// Filename     : 18LF2550 RF-24G Serial Servo Transmitter.c
// Programmer   : Steven Cholewiak, www.semifluid.com
// Version      : Version 1.0 - 02/27/2006
// Remarks      : Datasheets for RF-24G / TXRX24G are available from:
//                http://www.sparkfun.com/datasheets/RF/RF-24G_datasheet.pdf
//                http://www.sparkfun.com/datasheets/RF/RF-24G.pdf
//                http://www.sparkfun.com/datasheets/RF/nRF2401rev1_1.pdf
//                http://store.qkits.com/moreinfo.cfm/txrx24g.pdf
//
//                More information on the circuit can be found at:
//                http://semifluid.com/PIC18LF2550_wireless_servo.html
////////////////////////////////////////////////////////////////////////////////

#include <18F2550.h>
#device ADC=10
#use delay(clock=10000000)

#build(reset=0x1, interrupt=0x8)          // Necessary for Bootloader
#ORG 0x0F00,0x0FFF {}                     // Necessary for Bootloader

#use rs232(stream=PC, baud=57600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)

#include <RF-24G.c>

int1 dataReady = false;

#INT_RDA
void serial_isr()                         // Serial Interrupt
{
   int8 uReceive;

   uReceive = fgetc(PC);

   switch (uReceive) {
      case 0x12: {
            if (fgetc(PC) == 0x34 & fgetc(PC) == 0x56 & fgetc(PC) == 0x78 & fgetc(PC) == 0x90) #asm reset #endasm
         }
         break;
      case 101: {
            buf[0] = fgetc(PC);              // Servo 1
            buf[1] = fgetc(PC);              // Servo 2
            dataReady = true;
         }
         break;
   }
}

void main() {
   SETUP_ADC_PORTS(NO_ANALOGS);
   SETUP_ADC(ADC_OFF);
   SETUP_TIMER_0(RTCC_INTERNAL|RTCC_DIV_1);
   SETUP_TIMER_1(T1_DISABLED);
   SETUP_TIMER_2(T2_DISABLED, 127, 1);
   SETUP_TIMER_3(T3_DISABLED);
   SETUP_CCP1(CCP_OFF);
   SETUP_CCP2(CCP_OFF);
   enable_interrupts(INT_RDA);
   enable_interrupts(GLOBAL);

   delay_ms(100);

   printf("\n\rInitializing Port B...\n\r");
   RF_24G_initPorts();
   printf("Configuring RF-24G...\n\r");
   RF_24G_Config();
   RF_24G_SetRx();    // Switch to receive
   buf[0] = 127;
   buf[1] = 127;
   printf("OK!\n\r\n\r");

   while(1) {
      if(INPUT(RF_24G_DR1)){
         getBuffer();   // Get packet
         printf("%c%c%c",101,buf[0],buf[1]);
      }

      if(dataReady){
         // Transmit RF
         RF_24G_SetTx();   // switch to transmit
         delay_ms(1);
         putBuffer();      // send packet (buf)
         delay_ms(1);      // won't go back to recieve without this
         RF_24G_SetRx();   // switch back to receive
         delay_ms(1);
         dataReady = false;
      }
   }
}
