#pragma config PLLDIV = 5 // PLL Prescaler Selection bits (No prescale (4 MHz oscillator input drives PLL directly))
#pragma config CPUDIV = OSC1_PLL2 // System Clock Postscaler Selection bits ([Primary Oscillator Src: /1][96 MHz PLL Src: /2])
#pragma config USBDIV = 2 // USB Clock Selection bit (used in Full-Speed USB mode only; UCFG:FSEN = 1) (USB clock source comes directly from the primary oscillator block with no postscale)
// CONFIG1H
#pragma config FOSC = HSPLL_HS // Oscillator Selection bits (HS oscillator, PLL enabled (HSPLL))
#include <pic18f4550.h>
#include <delays.h>
unsigned int adc_data[2];
unsigned char analog_selected = 1;
void interrupt(){
if (PIR1bits.ADIF)
{
PIR1bits.ADIF=0; // clear AD interrupt flag
switch (analog_selected)
{
case 0:
adc_data[0] = (ADRESH << 8) | ADRESL; // read data from channel 0
analog_selected = 1; // return channel 1
ADCON0 = 0b11000101; // select channel 1;
if (adc_data[0] >= 512)
{
LATBbits.LATB2 = 1;
}
else
{
LATBbits.LATB2 = 0;
}
break;
case 1:
adc_data[1] = (ADRESH << 8) | ADRESL; // read data from channel 1
analog_selected--; // decrease channel index
ADCON0 = 0b11000001; // select channel 0
if (adc_data[1] >= 512)
{
LATCbits.LATC2 = 1;
}
else
{
LATCbits.LATC2 = 0;
}
break;
}
Nop(); // wait acquisition time for next sample to be available for sample and hold
Nop();
Nop();
ADCON0bits.GO = 1; // start conversion again
}
}
void main()
{
int a, b;
unsigned int i=0, temp;
int first = 1;
PORTA = 0;
TRISA = 0xFF; // initialise PortA as input Port
ADCON2 = 0b10001110; // 1 Right justified; 001 == 2*T_ad; 110 = F_osc/64
ADCON1 = 0b00001100; // AN0 and AN1 set as Analog Inputs
ADRESH = 0;
ADRESL = 0;
PORTB = 0;
TRISBbits.TRISB3 = 0;
TRISBbits.TRISB2 = 0;
TRISBbits.TRISB1 = 0;
PORTC = 0;
TRISCbits.TRISC2 = 0;
OSCCON = 0b01000110; // set internal oscillator at 8 MHz
while(1)
{
ADCON0 = 0b11000001; // select channel0(AN0) and power on A/D Module (ADON =1)
ADCON0bits.GO = 1; // start conversion
while (ADCON0bits.GO == 1) // wait until conversion is complete
{
if(first == 1)
{
adc_data[0] = (ADRESH << 8) | ADRESL; // read dadta from channel 0
ADCON0 = 0b11000101; // select channel 1
if (adc_data[0] >= 512)
{
LATBbits.LATB2 = 1;
}
else
{
LATBbits.LATB2 = 0;
}
first = 0;
}
interrupt();
}
}
}