C Code for Interfacing ADC module in PIC 16F87X

Microcontroller Topics
Post Reply
User avatar
Magneto
Major
Major
Posts: 430
Joined: Wed Jul 15, 2009 1:52 pm
Location: London

C Code for Interfacing ADC module in PIC 16F87X

Post by Magneto » Sat Oct 24, 2009 9:42 am

adc.h
(658 Bytes) Downloaded 561 times
/*
* Header file for the ADC unit - designed for PIC16F876/7
* BE CAREFUL WITH ADCON1 - IT HAS TO BE MANUALLY ADJUSTED FOR YOUR HARDWARE
* IN THE InitialiseADC ROUTINE.
*/



/*

sample C code

InitialiseADC(--Channel--);

blah = ReadADC(--Channel--);

*/


#include <pic.h> // Pic CPU header file
//#include "control.h"

#define INPUT 1
/*---------------------------------------------------------------
Initialising the ADC channels
---------------------------------------------------------------*/
void InitialiseADC (unsigned char ADC_Channel) {
if (ADC_Channel == 0) TRISA0 = INPUT;
else if (ADC_Channel == 1) TRISA1 = INPUT;
else if (ADC_Channel == 2) TRISA2 = INPUT;
else if (ADC_Channel == 3) TRISA3 = INPUT;

/* ------
Specify all to be analogue inputs, refered to VDD.
Please refer to Page 118 from PIC manual for other configurations.
------ */

/* Analogue-RA0/RA1/RA3 Digital-RA2/RA5 */
ADCON1 = 0b10000100;
}

/*---------------------------------------------------------------
Reads the ADC level input on a specified ADC channel.
Takes in an 10-bit ADC channel number.
Returns an 10 bit number that signifies this level.
Approximate sampling time = 76.8us
---------------------------------------------------------------*/
unsigned int ReadADC(unsigned char ADC_Channel){

volatile unsigned int ADC_VALUE;

/* Selecting ADC channel */
ADCON0 = (ADC_Channel << 3) + 1; /* Enable ADC, Fosc/2 */

ADIE = 0; /* Masking the interrupt */
ADIF = 0; /* Resetting the ADC interupt bit */
ADRESL = 0; /* Resetting the ADRES value register */
ADRESH = 0;

ADGO = 1; /* Staring the ADC process */
while(!ADIF) continue; /* Wait for conversion complete */

ADC_VALUE = ADRESL; /* Getting HSB of CCP1 */
ADC_VALUE += (ADRESH << 8); /* Getting LSB of CCP1 */

return (ADC_VALUE); /* Return the value of the ADC process */
}
Post Reply

Return to “Microcontrollers”