/*******************************************************
FILE:     adc.c

DESCRIPTION: To demo use of analog-to-digital converter (ADC). 
See CCS help files for details on built-in ADC functions. 

REVISION HISTORY:  
*******************************************************/
//--Includes

#include <16f88.h>
#device ADC=10             // for 10-bit ADC results

//--Setup commands

#fuses INTRC_IO,NOWDT,NOPROTECT,PUT,NOWRT,NOLVP  // internal oscillator
#id 0x1234                     // 4 digit id
#use standard_io(A)
#use standard_io(B)
//#use fast_io(A)
//#use fast_io(B)
#use delay(clock=8000000)      // declare clock speed


//--Pin definitions
#define LED      PIN_B0   // LED


//--Defines
#define AD_CHAN_DELAY  20       // adc channel change delay (uS)


/*******************************************************
  Main starts here
*******************************************************/

void main(void)
{
  int8 i;
  int16 data;

//-------Setup commands

//  set_tris_a(0xFF);   // a is all inputs (for adc)
//  set_tris_b(0xC0);   // b7,b6 in, rest out
  setup_oscillator(OSC_8MHZ);
  
/*----ADC setup commands, see CCS function help file and 
      see file 16f88.h for details. Use AN0 with range of
      0V to 5V. Conversion will return 10-bit number in range
      of 0 to 1023, 0=0.0V, 1023=5.0V. ADC clock setup depends
      on which PICchip is used, consult PICchip data sheet
      for the specifics, also see file 16f88)adc.txt. For the 
      settings used here, max sampling rate is about 20 KHz.*/
  setup_adc_ports(sAN0 | VSS_VDD);  // AN0 and voltage range see file 16f88.h for options
  setup_adc(ADC_CLOCK_DIV_16); // TAD = 2.0 uS if chip clock 8 MHz
  set_adc_channel(0);         // select channel 0
  delay_us(AD_CHAN_DELAY);    // wait to settle
  
//-------Flash led a few times

  for (i=0;i<3;i++) {
    output_high(LED);
    delay_ms(100);
    output_low(LED);
    delay_ms(300);
  }
  
/*-------Endless loop collecting data, be inventive with
         what you do with the data, here it turns the LED
         on if the ADC voltage is greater than 2.5V. */

  while (TRUE) {
    delay_ms(10);       // about 100 Hz sampling rate
    data = read_adc();  //do the conversion
    if (data > 512)
      output_high(LED);
    else
      output_low(LED);
  }
}


