Program 16: ADC – Display Digital Value
PIC18F4550 · Embedded C

#include <xc.h>

   #define _XTAL_FREQ 20000000UL

   #define LCD_RS LATAbits.LATA0
   #define LCD_E LATAbits.LATA1

   void LCD_Command(unsigned char cmd)
   {
       LATB = cmd;
       LCD_RS = 0;
       LCD_E = 1;
       __delay_ms(2);
       LCD_E = 0;
       __delay_ms(2);
   }

   void LCD_Data(unsigned char data)
   {
       LATB = data;
       LCD_RS = 1;
       LCD_E = 1;
       __delay_ms(2);
       LCD_E = 0;
       __delay_ms(2);
   }

   void main(void)
   {
       unsigned int value;

        TRISB = 0x00;                       // LCD data
        TRISAbits.TRISA0 = 0;               // RS
        TRISAbits.TRISA1 = 0;               // E
        TRISEbits.TRISE2 = 1;               // AN7 input (pot)

        ADCON1 = 0x07;                      // AN0-AN7 analog
        ADCON0 = 0x1D;                      // select AN7, ADC ON
        ADCON2 = 0x96;                      // right justified

        __delay_ms(20);
        LCD_Command(0x38);                  // 8-bit, 2 lines
        LCD_Command(0x0C);                  // display ON
        LCD_Command(0x01);                  // clear
        __delay_ms(5);

        while(1)
        {
            ADCON0bits.GO_nDONE = 1;                    // start conversion
            while(ADCON0bits.GO_nDONE == 1);            // wait
            value = (ADRESH << 8) | ADRESL;             // 0 - 1023

             LCD_Command(0x80);                         // line 1
             LCD_Data(value / 1000 + '0');              // thousands
             LCD_Data(value / 100 % 10 + '0');          // hundreds
             LCD_Data(value / 10 % 10 + '0');           // tens
             LCD_Data(value % 10 + '0');                // units

             __delay_ms(200);
        }
   }
