Tutorial 11_Working with ADC (LO3)
Tutorial 11_Working with ADC (LO3)
Write a program in micro C to convert an analog signal to digital using PIC16F877A ADC.
Solution
// CONFIG
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled)
#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit
(RB3 is digital I/O, HV on MCLR must be used for programming)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code
protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all
program memory may be written to by EECON control)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)
#include <xc.h>
//#include <htc.h>
//#include <math.h>
void ADC_Init()
{
ADCON0 = 0x41; //ADC Module Turned ON and Clock is selected
ADCON1 = 0x80; //All pins as Analog Input
//With reference voltages VDD and VSS
}
void main()
{
unsigned int a;
TRISB = 0x00; //PORTB as output
TRISC = 0x00; //PORTC as output
TRISA = 0xFF; //PORTA as input
ADC_Init(); //Initializes ADC Module
do
{
a = ADC_Read(0); //Reading Analog Channel 0
PORTB = a; //Lower 8 bits to PORTB
PORTC = a>>8; //Higher 2 bits to PORTC
__delay_ms(100); //Delay
}while(1); //Infinite Loop
}