Well, after I had LEDs blinking away on my board in various fashions I wished to progress to reading analog inputs from sensors (in this case, a photoresistor).
I couldn't find some example code for the Hi-Tech C compiler off the internet so I wrote one using the PIC datasheet and the reference manual and some sample code in an word document I found online. It builds successfully, however, I still am not convinced that it is correct. Here it is:
Would this code work? I still have some qualms regard setting individual bits in registers (see ADCON0 up there).
If something appears terribly wrong with the code above please point it out and help me fix it.
Thanks!
I couldn't find some example code for the Hi-Tech C compiler off the internet so I wrote one using the PIC datasheet and the reference manual and some sample code in an word document I found online. It builds successfully, however, I still am not convinced that it is correct. Here it is:
Rich (BB code):
//main.c
//To read a photoresistor input and flash an LED if it is dark
#include<htc.h>
#define _XTAL_FREQ 20000000
__CONFIG(FOSC_HS & CP_OFF & CPD_OFF & LVP_ON & PWRTE_OFF & DEBUG_ON & WDTE_OFF & BOREN_OFF & WRT_OFF);
void main(void)
{
while(1)
{
unsigned int photo=0;
//16 bit integer(0-65536)
TRISB=0x0;
//PORTB configured as output
TRISA=0b11111111;
//set TRISA registers to input
ADCON1=0b00000000; //all pins are analog; result is left justified
ADCON0=0b10000001;
//switch on ADC module; sets clock to 32TOSC; input at RA0; GO bit is low
__delay_us(20); //wait for 20us; acquisition time
ADCON0=0b10000101; //start the conversion
while(ADCON0==0b10000101); //wait for conversion to complete
photo=ADRESH;
if(photo<32768) //if it is dark
PORTB=0b10000000; //light the LED
}
}
If something appears terribly wrong with the code above please point it out and help me fix it.
Thanks!