Embedded C program for LCD interfacing with PIC18F in MPLAB IDE

Note: PORT's connection will be different based on the kit you are using by the manufacturer for PIC18F.

Program:

#include <pic18f4550.h>
#define LCD_EN PORTCbits.RC1   // LCD Enable
#define LCD_RS PORTCbits.RC0   // Register Set

// To generate delay
void delay()
{
    unsigned int i;
    for(i=0;i<5000;i++);
} 

unsigned char string1[] = {'C','O','D','I','N','G'};
unsigned char string2[] = {'A','T','H','A','R','V','A'};

// To Write Data in Command Register
void sendCommand(unsigned char command)
{
    LCD_RS = 0; // To Select Command Register
    delay();
    
    // Whatever data you want to store in command register
    // that data should be placed on data bus
    // PORTB is connected to Data-bus
    // to latch this data enable terminal should be at logic 1 and 0
    // i.e High to Low pulse 
    LCD_EN = 1;
    delay();
    PORTB = command;
    delay();
    LCD_EN = 0;
    
    delay();
}


// To Write Data in Data Register
void sendData(unsigned char lcd_data)
{
    LCD_RS = 1; // Select Data Register
    delay();
    
    LCD_EN = 1;
    delay();
    PORTB  = lcd_data;  // ACSII value of data
    delay();
    LCD_EN = 0;
    delay(); 
}


void main() 
{
    unsigned int i;
    unsigned char p;
    
    TRISB = 0x00; // PORTB as Output
    
    TRISCbits.RC0 = 0;  // PORTC 0 as Output
    TRISCbits.RC1 = 0; // PORTC 1 as Output
    
    // Initialize LCD
    sendCommand(0x38); // Select 16X2 LCD
    sendCommand(0x0E); // Display on and Cursor On
    sendCommand(0x0E); // Clear LCD
    
    // to display 2 string
    while(1)
    {
        sendCommand(0x80); // First Position of First Row
        for(i=0;i<6;i++)
        {
            p = string1[1];
            sendData(p);
            
        }
        
        sendCommand(0xC0); // First Position of Second Row
        for(i=0;i<7;i++)
        {
            p = string2[i];
            sendData(p);
        }
        
        delay();
    }
    
    
    return;
}

Previous
Next Post »