#include ".\main.h"


//#define MAXDUTY   (int16)160   // 50 kHz
//#define MAXDUTY   (int16)400   // 20 kHz
//#define MAXDUTY   (int16)800   // 10 kHz
#define MAXDUTY   (int16)1023   // 7.8 kHz
#define HALFDUTY  (int16)MAXDUTY/2
#define DIVISOR   255 // 7.8 kHz  
//#define DIVISOR   199 // 10 kHz  
//#define DIVISOR   99 // 20 kHz  
//#define DIVISOR   39  // 50 kHz

void main()
{  
   int16 reg=MAXDUTY;
   int16 current;
   int16 counter=0;
   int16 avg=0;
   
   setup_adc_ports(sAN0|VSS_VREF);
   setup_adc(ADC_CLOCK_DIV_32);
   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_EXT_L_TO_H|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DIV_BY_1,DIVISOR,1); 
   setup_ccp1(CCP_PWM);
   setup_ccp2(CCP_PWM);
   set_pwm1_duty(MAXDUTY);
   set_pwm2_duty(MAXDUTY);
   setup_comparator(NC_NC_NC_NC);// This device COMP currently not supported by the PICWizard
   setup_oscillator(OSC_8MHZ);
   
   set_adc_channel(0);
   
   delay_ms(1);
   
   
   while(TRUE)
   {
      output_low(PIN_D0);
      delay_us(40);
      output_high(PIN_D0);   
      delay_ms(3);
   }
   

   set_pwm2_duty(HALFDUTY);
   delay_ms(10);
   set_pwm2_duty((int16)850);
//   set_pwm2_duty((int16)650);

   while(TRUE);
   
   while(TRUE)
   {
      current=read_adc();
      if (current<200)
      {
         if (reg>HALFDUTY) reg--;
      }
      else
      {
         if (reg<MAXDUTY) reg++;
      }
      set_pwm2_duty(reg);
      /*
      avg=avg/10*9+reg/10;
      //delay_ms(5);
      if (counter==60000) 
      {
         set_pwm2_duty(avg);
         while(TRUE){};
      }
      counter++;
      */
   }
}