/*    mija 2008
      demo for RFM01 - TX 868MHz

      PIC 16F84
      xtal = 4MHz
*/

#include "TX_RFM02.h"

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

#define SDI    PIN_B0
#define SCK    PIN_B1
#define FSK    PIN_B2
#define nIRQ   PIN_B3      // input for PIC
#define nSEL   PIN_B4

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

//unsigned int8 test[16]={0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x03b,0x3c,0x3d,0x3e,0x3f};
unsigned int8 test[16]="\n\r\r\rtest\n\r\r\r   ";

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

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

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);
}

void RF_WRITE_DATA(unsigned int8 data)
{
   unsigned int8 i;

   for (i=0;i<8;i++)
   {
      while (input(nIRQ));
      while (!input(nIRQ));
      if (data & 0x80) output_high(FSK);
      else output_low(FSK);
      data <<= 1;
   }
}

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

   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);

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

   RF_WRITE_CMD(0xCC00);
   RF_WRITE_CMD(0x9361);   // 868BAND,+/-90kHz
   RF_WRITE_CMD(0xA640);   // 868Mhz
   RF_WRITE_CMD(0xD040);   // rate/2
   RF_WRITE_CMD(0xC823);   // 4.8kbps
   RF_WRITE_CMD(0xC220);   // enable bit sync
   RF_WRITE_CMD(0xC001);   // close all

   j= ' ';
   while (1)
   {
      RF_WRITE_CMD(0xC039); // start tx
      ChkSum = 0;
      RF_WRITE_DATA(0xAA);
      RF_WRITE_DATA(0xAA);
      RF_WRITE_DATA(0xAA);
      RF_WRITE_DATA(0x2D);
      RF_WRITE_DATA(0xD4);
      if (j++ > '~') j = '!';
      test[15]=j;
      for (i=0;i<16;i++)
      {
         RF_WRITE_DATA(test[i]);
         ChkSum += test[i];
      }
      RF_WRITE_DATA(ChkSum);
      RF_WRITE_DATA(0xAA);
      RF_WRITE_CMD(0xC001);
      delay_ms(1000);
   }
}