Analog to Digital
Conversion
The operation of A/D converter is in control of the bits of four
registers:
ADRESH Contains high byte of conversion result;
ADRESL Contains low byte of conversion result;
ADCON0 Control register 0; and
ADCON1 Control register 1.
ADC RESOLUTION
PIC16F877A has 10-bit resolution. So the number of steps is:
1024 = (0000000000 to 1111111111). When Vref 5V(internal
voltage supply) is used, the step size is 5V/1024 = 4.88mV.
So its mean that every bit increment is equal of single step
voltage increment ~ 4.88mV.
For example to calculate the binary value of ADC that use Vref =
5V and the analog input = 1.7V is by using the formula below.
Dout = Vin / Step Size.
Dout = 1.7V / 4.88mV = 348.36
0101011100
In Short
In order to measure voltage on an input pin by the A/D converter, the
following should be done:
Step 1 - Port configuration:
Write a logic one (1) to a bit of the TRIS register, thus configuring the
appropriate pin as an input. Write a logic (1/0) to a bit of the ADCON1
register, thus configuring the appropriate pin as an analog input.
Step 2 - ADC module configuration:
Configure voltage reference in the ADCON1 register.
Select ADC conversion clock in the ADCON0 register.
Select one of input channels CH0-CH7 of the ADCON0 register.
Select data format using the ADFM bit of the ADCON1 register.
Enable A/D converter by setting the ADON bit of the ADCON0 register.
Step 3 - ADC interrupt configuration (optional):
Clear the ADIF bit.
Set the ADIE, PEIE and GIE bits.
Step 4 - Wait for the required acquisition time to pass (approximately
20uS).
Step 5 - Start conversion by setting the GO/DONE bit of the ADCON0
register.
Step 6 - Wait for ADC conversion to complete.
It is necessary to check in the program loop whether the GO/DONE pin is
cleared or wait for an A/D interrupt (must be previously enabled).
Step 7 - Read ADC results:
Read the ADRESH and ADRESL registers.
Task_1
#include
#fuses
#use
#byte
#byte
#byte
#byte
#byte
#byte
#byte
#byte
#bit
#bit
Void
<16f877a.h>
XT,NOWDT
delay (clock=4000000)
ADRESH
ADRESL
ADCON0
ADCON1
PORTA
PORTB
TRISA
TRISB
GO
ON
=
=
=
=
=
=
=
=
0x1E
0x9E
0x1F
0x9F
0x5
0x6
0x85
0x86
= ADCON0.2
= ADCON0.0
{ int
value=0;
TRISA=0xFF;
TRISB=0x00;
ADCON0=0;
ADCON1=0;
ON=1;
while
(1)
{
GO=1;
main ()
while(GO) {}
value=ADRESH;
PORTB=value;
}
//Declaration section
int RD_ADC ();
Void
main ()
{ float x=0;
TRISA=0xFF;
TRISB=0x00;
ADCON0=0b01000000;
ADCON1=0;
while(1)
{
x=
RD_ADC ();
PORTB=x;
x=x *5/255;
lcd_init();
printf(
}
}
int RD_ADC ()
{
int value=0;
bit_set(ADCON0,0);
bit_set(ADCON0,2);
while(bit_test(ADCON0,2)) {}
value=ADRESH;
return value;
}
lcd_putc,"\fvoltage=%g V", x );