Sadlercomfort
Ash
Hi Guys,
I'm having trouble programming an 16x2 LCD, I wondered if someone could check my code. It compiles ok.
Still don't fully understand how to program this LCD, the order of which to execute commands seems confusing.
What is the sequence of writing data to the LCD, for example selecting the line cursor position?
I'm having trouble programming an 16x2 LCD, I wondered if someone could check my code. It compiles ok.
Still don't fully understand how to program this LCD, the order of which to execute commands seems confusing.
What is the sequence of writing data to the LCD, for example selecting the line cursor position?
Code:
#include <htc.h>
#include <pic.h>
#define _XTAL_FREQ 4000000
__CONFIG(FOSC_XT & WDTE_OFF & PWRTE_OFF & CP_OFF & BOREN_OFF );
/****************** PIN Mapping *******************/
#define BF RC0
#define RS RA3
#define RW RA4
#define EN RA5
#define D0 RC7
#define D1 RC6
#define D2 RC5
#define D3 RC4
#define D4 RC3
#define D5 RC2
#define D6 RC1
#define D7 RC0
/************ LCD Command Mapping LSB-BITFLIP *****************/
#define CLRDISP 0b01000000
#define DISPLAY_ON 0b00110000
#define DISPLAY_OFF 0b00010000
#define CURSOR_ON 0b01010000
#define CURSOR_OFF 0b00010000
#define CURSOR_INC 0b01100000
#define MODE_8BIT 0b00011100
#define MODE_4BIT 0b00010100
/************** Line Addr Mapping LSB-BITFLIP******************/
#define LCD_LINE1 0b00000001
#define LCD_LINE2 0b00000011
#define LCD_LINE3 0b00101001
#define LCD_LINE4 0b00101011
void LCD_cmd(unsigned char cmd);
void LCD_busy(void);
void LCD_data(unsigned char data);
void LCD_init(void);
void LCD_string(const char *ptr);
void LCD_init(void){
TRISB = 0x00;
TRISC = 0x00;
LCD_cmd(MODE_8BIT); //2 Line, 5x8 disp, 8 bit
LCD_cmd(CLRDISP); //Clear Display
LCD_cmd(CURSOR_INC); //Increment Cursor on each write
LCD_cmd(DISPLAY_ON | CURSOR_OFF); //Bitwise OR
return;
}
void LCD_cmd(unsigned char cmd){
LCD_busy(); //Check if LCD busy
RS=0; //Register set to CMD
RW=0; //Write data
EN=1; //Ensure Enable is HIGH
PORTC=cmd; //Send data to PORTC
__delay_ms(50);
EN=0; //Enable is LOW
}
void LCD_busy(){
TRISCbits.TRISC0=1; //Make D7 as input
EN=0; //Ensure Enable is LOW
RS=0; //Register set to CMD
RW=1; //Read Data
EN=1; //Enable LOW too HIGH transition
__delay_ms(50);
while(BF);
TRISCbits.TRISC0=0; //Make D7 as output
EN=0;
}
void LCD_data(unsigned char data){
RS=1;
RW=0;
EN=1;
PORTC=data;
__delay_ms(50);
EN=0;
}
void LCD_string(const char *buffer){
while(*buffer) // Write data to LCD up to null
{
LCD_busy(); // Wait while LCD is busy
LCD_data(*buffer); // Write character to LCD
buffer++; // Increment buffer
}
}
void main(){
LCD_init();
LCD_cmd(LCD_LINE1);
__delay_ms(50);
LCD_string(" Welcome to ");
__delay_ms(50);
LCD_cmd(LCD_LINE2);
__delay_ms(50);
LCD_string("Handicare");
__delay_ms(2000);
}