// hello16f88.c
//
// jackie lee
// jackylee@media.mit.edu
// 2005/10/06
//
// This example demonstrates how to use 16F88 ADC.
//
//  
// For full details on the iRX board and this program, refer to 
// http://www.media.mit.edu/~r/projects/picsem/GettingStarted/
//
//

#include "C:\Program Files\PICC\Devices\16f88.h"

// Configure PIC to use: HS clock, no Watchdog Timer, 
// no code protection, enable Power Up Timer
//

#fuses HS,NOWDT,NOPROTECT,PUT
#fuses INTRC_IO,NOWDT,NOPROTECT,PUT, NOLVP, MCLR, NODEBUG, NOFCMEN, NOIESO

// Tell compiler clock is 8MHz.  This is required for delay_ms()
// and for all serial I/O (such as printf(...).  These functions
// use software delay loops, so the compiler needs to know the
// processor speed.
//
#use delay (clock=8000000)

// Declare that we'll manually establish the data direction of
// each I/O pin on port B.
//
#use fast_io(B)

// Standard definitions for the irx2_1 board
//
#define RS232_XMT       PIN_B1  // (output) RS232 serial transmit
#define RED_LED         PIN_B2  // (output) Red LED (low true)
#define IR_LED          PIN_B3  // (output) Infrared LED (low true)
#define IR_SENSOR       PIN_B4  // (input) IR sensor (Sharp IS1U30)
#define RS232_RCV       PIN_B5  // (input) RS232 serial receive

// Macros to simplify I/O operations
//
#define RED_LED_ON      output_low(RED_LED)
#define RED_LED_OFF     output_high(RED_LED)
#define IR_LED_ON       output_low(IR_LED)
#define IR_LED_OFF      output_high(IR_LED)
#define IR_RECEIVED	(!input(IR_SENSOR))

// Default tri-state port direction bits: all PORT B bits are
// output except for IR_SENSOR (bit 4) and RC232_RCV (bit 5).
//
#define IRX_B_TRIS      0b00110000

// Inform printf() and friends of the desired baud rate 
// and which pins to use for serial I/O.
//
#use rs232(baud=9600, xmit=RS232_XMT, rcv=RS232_RCV)

void main() {

  // Declare variables for voltage reading and ten-bit
  // a-to-d value
  float adc_value, volts_read;
  int counter;
  double volts_send;
  counter = 0;

  // Set up a-to-d ports and converter
  setup_adc_ports(sAN0 | sAN1 | VSS_VDD);
  setup_adc(ADC_CLOCK_DIV_64);
  set_adc_channel(0);

  // since we've declared #use fast_io(B) (above), we MUST 
  // include a call to set_tris_b() at startup.
  // 
  set_tris_b(IRX_B_TRIS);

  RED_LED_ON;                    // reality check at startup
  delay_ms(200);
  RED_LED_OFF;

  while (1) {
    RED_LED_ON;                  // turn on the led
	adc_value = read_adc();
    volts_read = adc_value*20.00000/1024;
	volts_send = (double) volts_read;
    printf("Voltage %i: %f --- %x \r\n", counter, volts_send, volts_read); // print to serial port
	counter = counter+1;
    RED_LED_OFF;                 // turn off the led
    delay_ms(500);               // do nothing for half a second
  }
}

