วันนี้ได้มีโอกาศใช้งาน LCD20*4 กับภาษา C ก็เลยอยากกระจายความสะดวกให้คนที่ทำทีหลัง โดยการเอา source code มาวางให้ครับ
โดยผมใช้ ภาษา C Qt Creator cross-compile บน linux ubuntu16.04 กับ rpi-3b และต่อ LCD ด้วย I2C
//============== mylcd.h =================//
#ifndef MYLCD_H
#define MYLCD_H
#define I2C_ADDR_LCD1 0x26 // LCD I2C Address
#define LCD_CHR 1 // Mode sending data
#define LCD_CMD 0 // Mode sending command
#define LINE1 0x80 // 1st line
#define LINE2 0xc0 // 2nd line
#define LINE3 0x94 // 1st line
#define LINE4 0xd4 // 2nd line
#define LCD_BACKLIGHT 0x08 // on
//#define LCD_BACKLIGHT 0x00 // off
#define ENABLE 0b00000100 // enable bit
void typeInt(int i);
void typeFloat(float myFloat);
void lcdLoc(int line); // move cursor
void ClrLcd(void); // clr LCD return home
void typeln(const char *s);
void typeChar(char val);
void lcd_init(void);
void lcd_byte(int bits, int mode);
void lcd_toggle_enable(int bits);
int fd;
#endif // MYLCD_H
//============== main.c =================//
#include <QCoreApplication>
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include <stdlib.h>
#include <stdio.h>
#include <mylcd.h>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
if(wiringPiSetup()==-1){
qDebug() << "can't open wiring pi";
}
else
{
qDebug() << "open wiring pi!!!";
}
fd = wiringPiI2CSetup(I2C_ADDR_LCD1);
lcd_init();
char array1[] = "Hello world!";
while(1)
{
ClrLcd();
lcdLoc(LINE1);
typeln("Using wiringPi");
lcdLoc(LINE2);
typeln("Niran editor");
lcdLoc(LINE3);
typeln("I2c programmed");
lcdLoc(LINE4);
typeln("In C not python");
delay(2000);
ClrLcd();
lcdLoc(LINE1);
typeln(array1);
delay(2000);
ClrLcd();
typeln("Int ");
int value = 20125;
typeInt(value);
delay(2000);
lcdLoc(LINE2);
typeln("Float ");
float Floatvalue = 10045.25989;
typeFloat(Floatvalue);
}
return a.exec();
}
void typeln(const char *s){
while(*s){
lcd_byte(*(s++), LCD_CHR);
}
}
// float to string
void typeFloat(float myFloat){
char buffer[20];
sprintf(buffer,"%4.2f", myFloat);
typeln(buffer);
}
// int to string
void typeInt(int i){
char array1[20];
sprintf(array1,"%d", i);
typeln(array1);
}
void ClrLcd(void){
lcd_byte(0x01,LCD_CMD);
lcd_byte(0x02,LCD_CMD);
}
void lcdLoc(int line){
lcd_byte(line, LCD_CMD);
}
void typeChar(char val){
lcd_byte(val,LCD_CHR);
}
void lcd_byte(int bits, int mode){
int bits_high;
int bits_low;
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT;
bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT;
wiringPiI2CReadReg8(fd,bits_high);
lcd_toggle_enable(bits_high);
wiringPiI2CReadReg8(fd,bits_low);
lcd_toggle_enable(bits_low);
}
void lcd_toggle_enable(int bits){
delay(10);
wiringPiI2CReadReg8(fd,(bits|ENABLE));
delay(10);
wiringPiI2CReadReg8(fd,(bits|~ENABLE));
delay(10);
}
void lcd_init(){
lcd_byte(0x33,LCD_CMD);
lcd_byte(0x32,LCD_CMD);
lcd_byte(0x06,LCD_CMD);
lcd_byte(0x0C,LCD_CMD);
lcd_byte(0x28,LCD_CMD);
lcd_byte(0x01,LCD_CMD);
delay(500);
}