Embedded C Program
Embedded C Program
//Includes
#include <p18f4550.h> //Include controller specific .h file
//Function Prototypes
void ADC_Init(void); //Function to initialize the ADC
void ADC_Init1(void); //Function to initialize the ADC
void ADC_Init2(void); //Function to initialize the ADC
unsigned int Get_ADC_Result(void); //Function to Get ADC result after
conversion
void Start_Conversion(void); //Function to Start of Conversion
void msdelay (unsigned int time); //Function to generate delay
void init_LCD(void); //Function to initialise the LCD
void LCD_command(unsigned char cmd); //Function to pass command to the LCD
void LCD_data(unsigned char data); //Function to write character to the
LCD
void LCD_write_string(static char *str);//Function to write string to the
LCD
while(1)
{
if(k==0)
{
ADC_Init(); // Init ADC peripheral
LCD_command(0x01); // clear LCD
msdelay(15);
LCD_command(0x06); // Shift curser right
msdelay(15);
LCD_command (0x80); // Goto first line, 0th place of LCD
LCD_write_string(msg2); // Display Message
Start_Conversion(); //Trigger conversion
adc_val= Get_ADC_Result();//Get the ADC output by polling GO bit
k=2;
msdelay(300); //Delay between conversions. It is a library
function,refer delays.h file in MCC18 installation directory
}
else if (k==2)
{
ADC_Init2(); // Init ADC peripheral
LCD_command(0x01); // clear LCD
LCD_command (0x80); // Goto first line, 0th place of LCD
LCD_write_string(msg4); // Display Message
Start_Conversion(); //Trigger conversion
k=0;
msdelay(300); //Delay between conversions.
}
}
}
//Function Definitions
void ADC_Init()
{
ADCON0=0b00000000; //A/D Module is OFF and Channel 0 is selected
ADCON1=0b00001110; // Reference as VDD & VSS, AN0 set as analog pins
ADCON2=0b10001110; // Result is right Justified
//Acquisition Time 2TAD
//ADC Clk FOSC/64
ADCON0bits.ADON=1; //Turn ON ADC module
}
void ADC_Init1()
{
ADCON0=0b00000100; //A/D Module is OFF and Channel 1 is selected
ADCON1=0b00001101; // Reference as VDD & VSS, AN1 set as analog pins
ADCON2=0b10001110; // Result is right Justified
//Acquisition Time 2TAD
//ADC Clk FOSC/64
ADCON0bits.ADON=1; //Turn ON ADC module
}
void ADC_Init2()
{
ADCON0=0b00001000; //A/D Module is OFF and Channel 2 is selected
ADCON1=0b00001100; // Reference as VDD & VSS, AN2 set as analog pins
ADCON2=0b10001110; // Result is right Justified
//Acquisition Time 2TAD
//ADC Clk FOSC/64
ADCON0bits.ADON=1; //Turn ON ADC module
}
void Start_Conversion()
{
ADCON0bits.GO=1;
}
//If you do not wish to use adc conversion interrupt you can use this
//to do conversion manually. It assumes conversion format is right
adjusted
unsigned int Get_ADC_Result()
{
unsigned int ADC_Result=0;
while(ADCON0bits.DONE);
ADC_Result=ADRESL;
ADC_Result|=((unsigned int)ADRESH) << 8;
return ADC_Result;
}