Using A/D converter
The PIC16F887 A/D converter is used in this example. Is it necessary to mention that everything is rather simple?! A variable analog signal is applied to the AN2 pin, while the 10-bit result of conversion is shown on ports B and D (8 LSBs on port D and 2 MSBs on port B). GND is used as negative voltage reference Vref-, while positive voltage reference is applied to the AN3 pin. It enables voltage measurement scale to 'stretch and shrink'. In other words, the A/D converter always generates a 10-bit binary result, which means that it detects a total of 1024 voltage levels (210=1024). The difference between two voltage levels is not always the same. The less the difference between Vref+ and Vref-, the less the difference between two of 1024 levels. As seen, the A/D converter is able to detect slight changes in voltage./*Header******************************************************/ unsigned int temp_res; void main() { ANSEL = 0x0C; // Pins AN2 and AN3 are configured as analog TRISA = 0xFF; // All port A pins are configured as inputs ANSELH = 0; // Rest of pins is configured as digital TRISB = 0x3F; // Port B pins RB7 and RB6 are configured as // outputs TRISD = 0; // All port D pins are configured as outputs ADCON1.F4 = 1 ; // Voltage reference is brought to the RA3 pin. do { temp_res = ADC_Read(2); // Result of A/D conversion is copied to temp_res PORTD = temp_res; // 8 LSBs are moved to port D PORTB = temp_res >> 2; // 2 MSBs are moved to bits RB6 and RB7 } while(1); // Endless loop }In order to make this example work properly, it is necessary to tick off the ADC library in the Library Manager prior to compiling: