There are numerous situations in which an analog quantity (voltage and or current) is required to be measured and the PIC (or other) microcontroller use the value in either a calculation, store to datafile, display on LCD etc. For example, in the fruit/vegetable dehydrator project, a LM35 temperature sensor provides a voltage output that is linearly related to temperature (10mV/oC). Analog-to-digital converter (ADC) circuitry is required to perform this function.
Many PIC (and other) microcontrollers have on-board ADC modules that conveniently enable the measurement of analog values and use of the result in the PIC controller firmware/associated circuitry. To explore the capability of the ADC module on a PIC16F876, a 2.5V reference source was established that via a voltage divider/potentiometer enabled a known voltage to be produced, which provided the test input to the PIC ADC.
The PIC16F876 datasheet steps through the process of performing ADC (setting various registers, configuring the ADC module and I/O pins, starting conversion timers, waiting for the result and reading the resultant value from the specified memory register). However, using the CSS C Compiler for PIC microcontrollers makes the use of ADC very easy. The following code snippet is all that is required to read an analog input on PIN A0 and display the result to LCD.
Code Snippet 1:
#include "PWM_PIC16F876A.h"
#include "lcd.c"
#define LCD_ENABLE_PIN PIN_B0
#define LCD_RS_PIN PIN_B1
#device adc=10
void main()
{
int i;
long value, min, max;
float vMin, vMax;
lcd_init();
//following sets the Vref as input to RA3 (pin 5) on the PIC
setup_adc_ports(RA0_RA1_ANALOG_RA3_REF);
setup_adc(ADC_CLOCK_INTERNAL);
set_adc_channel(0); //0 = AN0 (pin2), 1=AN1 (pin3), etc
lcd_putc("Sampling (volts)");
do {
min=0xffff;
max=0; and
for(i=0; i<=10; ++i) {
delay_ms(100);
value = Read_ADC();
if(valuemax) max=value;
}
//#device adc=10 or adc=8
vMin=min*0.00244; // 8bit -> 2.5V/255 = 0.0098v/count
vMax=max*0.00244; //10bit -> 2.5V/1024 = 0.00244v/count
printf(lcd_putc,"Min%1.2f Max%1.2f",vMin,vMax);
} while (TRUE);
}
Note that either 8-bit or 10-bit resolution of the ADC value can be selected, and there is also the ability to set the upper and lower Vref. Depending upon the particular PIC part, there are generally a number of ADC channels available. The positive and negative reference voltage for the ADC module can be Vdd (circuit positive voltage), Vss (circuit ground) or the input voltage at either pins RA2 or RA3 (the reference voltages need to be specified in the setup of the ADC). So this means the following:
- If the ADC input = Vref (-) then the ADC result will be 0x00
- If the ADC input = Vref (+) then the ADC result will be 0xFF (8-bit), 0x400 (10-bit)
Therefore, each step of the ADC module on the PIC is equal to (Vref+ minus Vref-)/(bit-mode - 1) where bit-mode is either 256 or 1024 for 8-bit and 10-bit respectively.
Only Logged-In Members can add comments