LCD 4Bit

From Pinguino-Wiki

Jump to: navigation, search


Here is an example of a 4bit LCD driver.

First of all I would like to thank Marin Purgar for giving me permission to publish his code on Wike. He wrote 'Yes of course it's ok, I wrote it for everyone to use it!'

You'll never get rich this way Marin, but that's all about beeing a geek, I guess :-)

Anyway ... the code :

If the chosen pins don't fit your application, feel free to alter them. Just keep in mind that the 4 datapins must be in consecutive order. For those who are familiar with the PIC itself : You don't have to bother about things like 'PORT A' or 'PORT B' boundaries. Pinguino will keep track of this for you.

Datapins 0..3 of the LCD can be left open.


// LCD4Bits.pde
//
// Author: Marin Purgar - marin.purgar@gmail.com
//
 
#define LCD_RS  8
#define LCD_E   9
 
void lcdPulseEnable() {
        digitalWrite(LCD_E, HIGH);
        delayMicroseconds(1);
        digitalWrite(LCD_E, LOW);
        delayMicroseconds(1);
}
 
void lcdWriteNibble(uchar c){
        int i;
        for(i=0; i<4; i++){
                digitalWrite(4+i, (c >> i) & 0x01);
        }
        lcdPulseEnable();
}
 
void lcdWriteByte(uchar c, int mode) {
        digitalWrite(LCD_RS, mode);
        lcdWriteNibble(c >> 4);
        lcdWriteNibble(c);
}
 
void lcdSendControl(uchar c) {
        lcdWriteByte(c, LOW);
}
 
void lcdSendData(uchar c) {
        lcdWriteByte(c, HIGH);
}
 
void lcdSetAddress(uchar line, uchar column) {
        lcdSendControl( 0x80 + 0x40 * (line - 1) + (column - 1));
}
 
void lcdPrint(char *string) {
        int i;
        for( i=0; string[i]; i++) {
                lcdSendData(string[i]);
        }
}
 
void lcdInit() {
        int i;
 
        pinMode(LCD_E, OUTPUT);
        digitalWrite(LCD_E, LOW);
        pinMode(LCD_RS, OUTPUT);
        digitalWrite(LCD_RS, LOW);
        for(i = 4; i < 8; i++) {
                pinMode(i, OUTPUT);
        }
        delay(20);
        lcdWriteNibble(0x03);
        delayMicroseconds(1);
        lcdWriteNibble(0x03);
        delayMicroseconds(1);
        lcdWriteNibble(0x02);
        delayMicroseconds(200);
        lcdSendControl(0x28);           // 4 Bit, 2 Lines
        delayMicroseconds(1);
        lcdSendControl(0x0C);           // Display On
        delayMicroseconds(1);
        lcdSendControl(0x01);           // Clear display
        delay(2);
        lcdSendControl(0x02);           // Cursor home
        delay(2);
}
 
uchar line1[] = "Pinguino Team ";
uchar line2[] = "Croatia       ";
 
uchar line3[] = "Marin Purgar  ";
uchar line4[] = "Goran Horvatic";
 
void setup() {
        lcdInit();
}
 
void loop() {
        lcdSetAddress(1, 1);
        lcdPrint(line1);
        lcdSetAddress(2, 1);
        lcdPrint(line2);
        delay(3000);
 
        lcdSetAddress(1, 1);
        lcdPrint(line3);
        lcdSetAddress(2, 1);
        lcdPrint(line4);
        delay(3000);
}
Personal tools