Skip to content

Instantly share code, notes, and snippets.

@technoburst
Last active November 9, 2021 10:01
Show Gist options
  • Save technoburst/5451983 to your computer and use it in GitHub Desktop.
Save technoburst/5451983 to your computer and use it in GitHub Desktop.
Sample program to test ADC of PIC16F877A
//ADC example program written for PIC programming tutorial.
//Target Device PIC16F877A
//Compiler: XC8
//Author : Anil C S
//Website : www.technoburst.net
//Email : anil@technoburst.net , technoburst@gmail.com
#include <stdio.h>
#include <stdlib.h>
#define _XTAL_FREQ 20000000 //defining crystal frequency to 20 MHz
// PIC16F877A Configuration Bit Settings
#include <xc.h>
// 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 = ON // Brown-out Reset Enable bit (BOR enabled)
#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)
void main()
{
unsigned short ADCResult;
TRISD = 0b00000000; //Setting PORTD as output port
PORTD = 0b00000000; //Initializing PORTD
ADCON0bits.ADCS = 0; //Selecting the clk division factor = FOSC/2
ADCON1bits.ADCS2 = 0; //Selecting the clk division factor = FOSC/2
ADCON1bits.ADFM = 1; //Result right justified
ADCON1bits.PCFG = 0; //Setting all the analog ports as Analog inputs
ADCON0bits.ADON = 1; //Turns on ADC module
ADCON0bits.CHS = 0; //Selects channel 0 ( AN0 )
while(1)
{
__delay_us(25); //Waits for the acquisition to complete
ADCON0bits.GO = 1; //Starts ADC conversion
while (ADCON0bits.nDONE) continue; //wait till ADC conversion is over
ADCResult = (ADRESH<<8) + ADRESL ; //Merging the MSB and LSB
if(ADCResult>512)
PORTD = 255;
else
PORTD = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment