#include <p33Exxxx.h>
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <libpic30.h>
#pragma config ICS = PGD3 // Comm Channel Select (Communicate on PGC1/EMUC1 and PGD1/EMUD1)
#pragma config JTAGEN = OFF // JTAG Port Enable (JTAG is Disabled)
#pragma config FNOSC= FRC
#pragma config IESO= OFF
#pragma config FCKSM= CSECMD
#pragma config OSCIOFNC=OFF
#pragma config POSCMD=NONE
void initAdc1(void);
void Delay_us(unsigned int);
int ADCValue, i, j;
int main()
{
// Configure PLL prescaler, PLL postscaler, PLL divisor
PLLFBD=63; // M=65
CLKDIVbits.PLLPOST=0; // N2=2
CLKDIVbits.PLLPRE=1; // N1=3
// Initiate Clock Switch to FRC oscillator with PLL (NOSC=0b001)
__builtin_write_OSCCONH(0x01);
__builtin_write_OSCCONL(OSCCON | 0x01);
// Wait for Clock switch to occur
while (OSCCONbits.COSC!= 0b001);
// Wait for PLL to lock
while (OSCCONbits.LOCK!= 1);
TRISB=0X0000;
initAdc1();
while(1)
{
Delay_us(100); // Sample for 100 us
AD1CON1bits.SAMP = 0; // Start the conversion
while (!AD1CON1bits.DONE); // Wait for the conversion to complete
AD1CON1bits.DONE = 0; // Clear conversion done status bit
ADCValue = ADC1BUF0; // Read the ADC conversion result
// LATB=ADCValue;
if(ADCValue >= 1300)
{
LATBbits.LATB6=1;
}
else
{
LATBbits.LATB6=0;
}
}
}
void initAdc1(void)
{
/* Set port configuration */
TRISAbits.TRISA0=1;
ANSELA = ANSELB = 0x0000;
ANSELAbits.ANSA0 = 1; // Ensure AN5/RB5 is analog
/* Initialize and enable ADC module */
AD1CON1 = 0x0004;
AD1CON2 = 0x0000;
AD1CON3 = 0x00FF;
AD1CON4 = 0x0000;
AD1CHS0 = 0x0005;
AD1CHS123 = 0x0000;
AD1CSSH = 0x0000;
AD1CSSL = 0x0000;
AD1CON1bits.ADON = 1;
Delay_us(20);
}
void Delay_us(unsigned int delay)
{
for (i = 0; i < delay; i++)
{
__asm__ volatile ("repeat #39");
__asm__ volatile ("nop");
}
}