/*    mija 2008
      demo for RFM01 - RX 868MHz

      PIC 16F876A
      xtal = 4MHz
*/
#include "RX_RFM01.h"

//************************************************************************

#define SDI    PIN_B0
#define SCK    PIN_B1
#define SDO    PIN_B2      // input for PIC
#define nIRQ   PIN_B3
#define nSEL   PIN_B4
#define LED    PIN_B5

//************************************************************************
unsigned char RF_RXBUF[22];
int1 led_trg;

//************************************************************************

void RF_INIT(void)
{
   output_high(nSEL);
   output_high(SDI);
   output_low(SCK);
   input(SDO);
}

void RF_WRITE_CMD(unsigned int16 cmd)
{
   unsigned int8 i;

   output_low(SCK);
   output_low(nSEL);
   for (i=0;i<16;i++)
   {
      output_low(SCK);
      if (cmd & 0x8000) output_high(SDI);
      else output_low(SDI);
      output_high(SCK);
      cmd <<= 1;
   }
   output_low(SCK);
   output_high(nSEL);
}

int8 RF_RDFIFO(void)
{
   unsigned int8 i,Result;

   output_low(SCK);
   output_low(nSEL);
   output_low(SDI);
   for (i=0;i<16;i++)      // skip satus bits
   {
      output_high(SCK);
      output_high(SCK);
      output_low(SCK);
      output_low(SCK);
   }
   Result = 0;
   for (i=0;i<8;i++)
   {
      Result <<= 1;
      if (input(SDO)) Result |= 1;
      output_high(SCK);
      output_high(SCK);
      output_low(SCK);
      output_low(SCK);
   }
   output_high(nSEL);
   return Result;
}

void main()
{
   unsigned int8 i,j,ChkSum;

   setup_adc_ports(NO_ANALOGS);
   setup_adc(ADC_OFF);
   setup_spi(SPI_MASTER|SPI_L_TO_H|SPI_CLK_DIV_4);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);

   output_high(LED);
   delay_ms(1000);
   output_low(LED);

   RF_INIT();

   RF_WRITE_CMD(0x0000);
   RF_WRITE_CMD(0x918A);   // 868BAND,134kHz
   RF_WRITE_CMD(0xA640);   // 876Mhz
   RF_WRITE_CMD(0xC847);   // 4.8kbps
   RF_WRITE_CMD(0xC69B);   // AFC setting
   RF_WRITE_CMD(0xC42A);   // Clock recovery manualcontrol,Dig. filter, DQD=4
   RF_WRITE_CMD(0xC240);   // output 1.66Mhz
   RF_WRITE_CMD(0xC080);
   RF_WRITE_CMD(0xCE88);   // use FIFO 8bit
   RF_WRITE_CMD(0xCE8B);
   RF_WRITE_CMD(0xC081);   // open RX

   led_trg = 0;
   i = 0;
   while (1)
   {
      while (!input(nIRQ))
      {
         RF_RXBUF[i++] = RF_RDFIFO();
         putc(RF_RXBUF[i-1]);
         if (i == 18)
         {
            i = 0;
            RF_WRITE_CMD(0xCE88);
            RF_WRITE_CMD(0xCE8B);
            ChkSum = 0;
            for (j=0;j<16;j++) ChkSum += RF_RXBUF[j];
            if (ChkSum == RF_RXBUF[16])
            {
               led_trg = ~led_trg;
               output_bit(LED,led_trg);
            }
         }
      }
   }
}