Use A/D converter
An A/D converter provided on the PIC16F887 is used in this example. Is it necessary to say that everything is simple?! A variable analog signal is applied to the AN2 pin, while the 10- bit result of conversion is shown on ports PORTB and PORD (8 LSBs on PORTD and 2 MSBs on PORTB). GND is used as a negative voltage reference Vref-, while the VCC is used as a positive voltage reference. If you use varriable voltage as Vref+ (refer to dashed part of the schematic) you'll be able to ‘stretch and shrink’ the range of voltage measurement. In other words, the A/D converter always generates a 10-bit binary number, which means that it detects 1024 voltage levels (210=1024) in total. 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 you can see, the A/D converter is able to detect slight changes in voltage.'Header****************************************************** program example_7 ' Program name dim temp_res as word ' Variable temp_res is of word type main: ' Start of program ANSEL = 0x0C ' Pin AN2 is configured as analog TRISA = 0xFF ' All PORTA pins are configured as inputs ANSELH = 0 ' Other pins are configured as digital TRISB = 0x3F ' PORTB pins RB7 and RB6 are configured as ' outputs TRISD = 0 ' All PORTD pins are configured as outputs ADCON1.B4 = 0 ' Positive voltage reference is VCC. while 1 ' Endless loop temp_res = ADC_Read(2) ' Result of A/D conversion is copied to temp_res PORTD = temp_res ' 8 LSBs are moved to PORTD PORTB = temp_res >> 2 ' 2 MSBs are moved to bits RB6 and RB7 wend end. ' End of programIn order to make this example work properly, it is necessary to check the ADC library in the Library Manager prior to compiling: