// #device adc=10 needs to be added to 16F88.h to get 10 bit a/d.

#include <16F88.h>
#fuses HS,NOWDT,NOLVP,PUT,NOPROTECT,BROWNOUT,NOWRT,CCPB3
#use delay(clock=16000000)
#use rs232(baud=9600,xmit=PIN_B5,rcv=PIN_B2,ERRORS)

#byte PIR1 = 0x0C
#bit CCP1IF = PIR1.2

#define SAMPLE_PERIOD 1000L // Sampling interval in mS
int16 count = SAMPLE_PERIOD;
int1 sample_fl = 0;

// Timer 2 overflows every one millisecond
#int_timer2
timer2_isr()
{
   if(count)
      count--;
      
   else
   {
      sample_fl = 1;
      count = SAMPLE_PERIOD;
   }   
}

void main()
{
   int16 old_t1_count;
   int16 new_t1_count;
   int32 level;
   int32 temperature;
      
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   setup_adc_ports(sAN0);
   setup_adc(ADC_CLOCK_DIV_32);

   setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);
   setup_ccp1(CCP_CAPTURE_RE|CCP_CAPTURE_DIV_16);

   // Timer 2 cycle time will be (1/clock)*4*t2div*(period+1)
	// In this program clock=16,000,000 and period=249
   // (1/16000000)*4*16*250=1000 us or 1kHz)
   setup_timer_2(T2_DIV_BY_16,249,1);

   enable_interrupts(INT_TIMER2);
   enable_interrupts(global);
   set_adc_channel(0);

   while(1)
   {
      if(sample_fl)
      {
         sample_fl = 0;
         
         // Level measurement
         CCP1IF = 0;
         while (!CCP1IF);
         old_t1_count = CCP_1;
         CCP1IF = 0;
         while (!CCP1IF);
         new_t1_count = CCP_1;
         level = new_t1_count - old_t1_count;   // Unscaled
         
         // Temperature measurement. LM35 outputs 10mV/deg. C from 0 deg. C.
         // With 10 bit adc and 5V range, slope is (5000mV/10mV)/1023
         // Do rounding by adding half denominator.    
         temperature = (int32) read_adc();
         temperature *= 500L;
         temperature = (temperature + 511L)/1023L;
         
         printf("%5lu,%2lu\n\r",level,temperature);
      }
   }
}
