#include "main.h"


#define LED PIN_E1  
#define CE  PIN_E2

int16 count;

int8 rcv_buf[0x10];   // I2C receive buffer   
int8 snd_buf[0x10];   // I2C send buffer     

int8 buffer[0x10];   // I2C buffer     
int8 address;

const char cmd[40]={0xB5, 0x62, 0x06, 0x31, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x80, 0x84, 0x1E, 0x00, 0xE0, 0xC8, 0x10, 0x00, 0x40, 0x42, 0x0F, 0x00, 0xA0, 0x86, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7, 0x00, 0x00, 0x00, 0x12, 0x03};

#INT_SSP
void ssp_interupt ()
{
   BYTE incoming, state;

   state = i2c_isr_state();
   
   if(state < 0x80)                     //Master is sending data
   {
      incoming = i2c_read();
      if(state == 1)                     //First received byte is address
      {
         address = incoming;
         if (incoming == 2)
         {
            buffer[0]=make8(count,0);
            buffer[1]=make8(count,1);
         }
      }
      if(state == 2)                     //Second received byte is data
         buffer[address] = incoming;
         
      
   }
   if(state == 0x80)                     //Master is requesting data
   {
      i2c_write(buffer[address]);
   }
}


#int_TIMER2 // every 10 ms
void  TIMER2_isr(void) 
{
   output_low(CE);
   count=get_timer1();
   set_timer1(0);
   output_high(CE);
}

 
void main()
{
   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_OFF);
//   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
//   setup_wdt(WDT_144MS);
   setup_timer_1(T1_EXTERNAL|T1_DIV_BY_1);
   setup_timer_2(T2_DIV_BY_16,196,16);
   setup_ccp1(CCP_OFF);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   
   delay_ms(1000);
   int n;
   for (n=0;n<40;n++)
   {
      putc(cmd[n]);
   }

   printf("cvak...\r\n");
//   snd_buf[2]=0x55;
//   snd_buf[3]=0xAA;
   
   set_timer1(0);
   enable_interrupts(INT_SSP); 
//   enable_interrupts(INT_TIMER2);
   enable_interrupts(GLOBAL);    

   while(true)
   {
      
output_high(LED);
output_low(LED);
      set_timer1(0);
      output_high(CE);
      delay_ms(999);
      delay_us(966);
      output_low(CE);
   count=get_timer1();
   
      printf("count: %Lu %X %X %X %X\r\n",count, buffer[0],buffer[1],buffer[2],buffer[3]);
   }
}