Wednesday, March 23, 2016

PIC18F4550 ADC example with CCS PIC C compiler


The microcontroller PIC18F4550 has 13 ADC (Analog to Digital Converter) channels. The resolution of the PIC18F4550 ADC is 10-bit, which means the analog value after conversion is stored as a 10-bit number that varies from 0 to 1023 (0x3FF). 
The analog reference voltage is software selectable to either the device’s positive and  negative supply voltage (VDD and VSS) or the voltage level on the RA3/AN3/VREF+ and RA2/AN2/VREF-/CVREF pins.
The A/D converter has a unique feature of being able to operate while the device is in Sleep mode. To operate in Sleep, the A/D conversion clock must be derived from the A/D’s internal RC oscillator.
PIC18F4550 ADC example with CCS C:
This example shows how to analog data from analog input and display this reading as digital on LCD display as shown in the circuit schematic below:
PIC18F4550 ADC circuit with LCD display CCS C
The internal oscillator of PIC18F4550 is used at 8MHz and MCLR pin function is disabled.
The LCD used to display the analog value after conversion where channel 0 (RA0) is the analog input and analog signal can be changed from the potentiometer. The output analog voltage of the potentiometer varies from 0V to 5V.
The reference voltage is set to VDD (+5V) and GND.
To know how to use LCD display with PIC16F877A microcontroller see the following topic:
PIC18F4550 interfacing with LCD using CCS PIC C compiler
PIC18F4550 ADC example CCS C code:
This is the C code used for this example with some comments.
// PIC18F4550 ADC example with CCS C compiler
// http://ccspicc.blogspot.com/
// electronnote@gmail.com

//LCD module connections
#define LCD_RS_PIN PIN_D0
#define LCD_RW_PIN PIN_D1
#define LCD_ENABLE_PIN PIN_D2
#define LCD_DATA4 PIN_D3
#define LCD_DATA5 PIN_D4
#define LCD_DATA6 PIN_D5
#define LCD_DATA7 PIN_D6
//End LCD module connections

#include <18F4550.h>
#device ADC=10
#fuses NOMCLR INTRC_IO
#use delay(clock=8000000)
#include <lcd.c>

unsigned int16 i;
void main(){
  setup_oscillator(OSC_8MHZ);
  lcd_init();                       // Initialize LCD module
  setup_adc(ADC_CLOCK_DIV_8);      // Set ADC conversion time to 8Tosc
  setup_adc_ports(AN0);             // Configure RA0 (AN0) as analog
  set_adc_channel(0);               // Select channel 0 input
  delay_ms(100);                    // Wait 100ms
  lcd_gotoxy(3, 1);                 // Go to column 3 row 1
  lcd_putc("ADC reading:");
  while(TRUE){
    i = read_adc();
    lcd_gotoxy(7, 2);               // Go to column 7 row 2
    printf(lcd_putc,"%4Lu",i);      // Write i with 4 numbers max
    delay_ms(10);                   // Wait 10ms
   }
}

PIC18F4550 ADC example video:
The following video shows our example in a real hardware circuit.

Reference:
PIC18F4550 datasheet from Microchip