You are on page 1of 7

#include <P24FJ64GA002.

h> void initADC( ); int read_averageADC(); int readADC( int tsensor); int intensity=0,reff=0,reff2=0,read=0,read2=0;; _CONFIG1(JTAGEN_OFF & BKBUG_OFF & FWDTEN_OFF) //setup configuration bits _CONFIG2(FCKSM_CSDCMD & OSCIOFNC_ON & POSCMOD_NONE & FNOSC_FRC) #define SENSOR 1 #define DELAY 10000 int main() { AD1PCFG = 0x1FFE; //Set all pins to analogue input TRISB = 0; //Port B set to output for D4,D5,D6 and D7 // AD1PCFG=0x0fff; // Set all portB pins to digital PORTB=0x00;// set all output pins to zero

TRISA = 0x0001; //Port A set to output for RS and E and input for AN0 _TRISB9=1;//set RB9 as input T1CON=0x8030; PR1=0x2710; //Timer1 on. //Timer counter of 10 ( 10 is for mplab testing) in

decimal(PR1=period-1). TMR1=0; initADC( ); intensity=read_averageADC(); _RB9=0; while(1) { if (_RB9==1) { _RB6=1; //_RB7=0; intensity=0; reff=0; read=0; intensity=read_averageADC();//capture the background light intensity

reff2=intensity*1.2;// set the intensity as reference while(TMR1<DELAY) { //WAIT } _RB6=0; _RB9=0; } TMR1=0;

if (_RB9==0) { _RB5=1; read=read_averageADC(); reff=((((read-reff2)/2))+reff2);//compensating the background light. Recovering the attenuated signal. if(reff>read) { _RB4=0; _RB7=0; } if(reff==read) { _RB4=1; _RB7=0; } if(reff<read) { _RB7=1;

_RB4=0; } } _RB5=0; }//syetem working loop (while) return 0;

} void initADC( ) { AD1CON1 = 0x00E0; // auto convert after end of sampling AD1CSSL = 0; // no scanning required AD1CON3 = 0x1F02; // max sample time = 31Tad, Tad = 2 x Tcy = 500ns >75ns AD1CON2 = 0x0000;// use MUXA, Vss and Vdd are used as Vref+/AD1CON1bits.ADON = 1; // turn on the ADC //initADC(); } int read_averageADC() { int temp,j;

initADC(); temp = 0; T3CON = 0x8030; for ( j= 8; j >0; j--)//16 { TMR3 = 0; temp += readADC( SENSOR); } temp >>= 4; //get the average of 16 readings temp = temp;//*330/1024; //temp*330/1024 return temp; } int readADC( int tsensor) { AD1CHS =0x0000; // input at AN0 AD1CON1bits.SAMP = 1; // start sampling, auto-conversion will follow
49

while (!AD1CON1bits.DONE); // wait to complete the conversion return ADC1BUF0; // read the conversion result

You might also like