LCD1602 四線驅動程序
只用4條數據線就可以驅動1602液晶屏。見有朋友尋找這種方案,特貼出來。源程序來源于網上,但經本人修改驗證并加上注釋。
其中的RS、RW、E與8線驅動一樣。此方案可以省出4條單片機的管腳作別的用途,對于管腳緊張的項目,很有價值。
如果認為好,請加分。
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - 接口定義
# define LCD_DB P2 //
sbit LCD_RS=P0^7; //
sbit LCD_RW=P0^6; //
sbit LCD_E=P0^5; //
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - 自定義數據類型
# define uchar unsigned char
# define uint unsigned int
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - 定義子程序函數
void LCD_init(void); // - - 初始化LCD1602函數
void LCD_write_H4bit_command(uchar dat);
void LCD_write_L4bit_command(uchar dat);
void LCD_delay_10us(uint n); // - - 10微秒的延時子程序
void LCD_delay_50us(uint n); // - - 50微秒的延時子程序
void LCD_write_4bit_command(uchar command); // - - 向LCD1602寫指令函數
void LCD_write_4bit_data(uchar dat); // - - 向LCD1602寫數據函數
/ - - 初始化LCD1602
void LCD_init(void)
{
LCD_delay_50us(20);
LCD_RS=0; // - - 指令
LCD_RW=0; // - - 寫入
LCD_E=0; // - - 使能
LCD_write_L4bit_command(0x03); // - - 設置4位格式,2行,5x7
LCD_delay_50us(2);
LCD_write_L4bit_command(0x03); // - - 設置4位格式,2行,5x7
LCD_delay_50us(10);
LCD_write_L4bit_command(0x03); // - - 設置4位格式,2行,5x7
LCD_delay_50us(2);
LCD_write_L4bit_command(0x02); // - - 設置4位格式,2行,5x7
LCD_delay_50us(2);
LCD_write_4bit_command(0x28); // - - 設置4位格式,2行,5x7
LCD_delay_10us(10);
LCD_write_4bit_command(0x0c); // - - 整體顯示,關光標,不閃爍
LCD_delay_10us(10);
LCD_write_4bit_command(0x06); // - - 設定輸入方式,增量不移位
LCD_delay_10us(10);
LCD_write_4bit_command(0x01); // - - 清除屏幕顯示
LCD_delay_50us(40);
}
/*
上面初始化程序最重要的是連續三次寫入0x03,在液晶控制器的技術手冊中已經有說明,特別是在電壓不足的時候,以這樣的方法進行初始化,
容易成功。*/
//*******************************
// - - 向LCD1602寫數據或指令
特別注意:
//LCD_DB:其實就是P2口,且只用了高四位,這樣低四位可用于別的用途;
//(LCD_DB&0x0F)的結果是保留P2口現存內容的低四位,只有這樣,才不會影響低四位狀態,方便別的應用;
//(dat&0xF0)的結果是屏蔽dat低四位,保留高四位
//(LCD_DB&0x0F)|(dat&0xF0)的結果是將保留的高四位與低四位拼接成8位給P2
void LCD_write_H4bit_command(uchar dat)
{ //調用本函數只能將dat的高四位寫入1602
LCD_delay_10us(10);//延時
LCD_DB=(LCD_DB&0x0F)|(dat&0xF0);
LCD_delay_10us(10);
LCD_E=1; // - - 允許
LCD_delay_10us(10);
LCD_E=0;
}
// 向LCD1602寫低四位指令
void LCD_write_L4bit_command(uchar dat)
{//調用本函數只能將dat的低四位寫入1602
dat<<=4;//首先,將dat低四位移動到高四位
LCD_delay_10us(10);
LCD_DB=(LCD_DB&0x0F)|(dat&0xF0);
LCD_delay_10us(10);
LCD_E=1; // - - 允許
LCD_delay_10us(10);
LCD_E=0;
}
// - - 向LCD1602寫指令
void LCD_write_4bit_command(uchar dat)
{
LCD_delay_10us(10);
LCD_RS=0; // - - 指令
LCD_RW=0; // - - 寫入
LCD_write_H4bit_command(dat);//高四位寫入
LCD_write_L4bit_command(dat);//低四位寫入
}
// - - 向LCD1602寫數據
void LCD_write_4bit_data(uchar dat)
{
LCD_delay_10us(10);
LCD_RS=1; // - - 數據
LCD_RW=0; // - - 寫入
LCD_write_H4bit_command(dat);
LCD_write_L4bit_command(dat);
}
void LCD_delay_10us(uint n) // - - 10微秒的延時子程序
{
uint i,j;
for(i=n*10;i>0;i--) // - - 晶振及單片機修改設置
for(j=2;j>0;j--);
}
void LCD_delay_50us(uint n) // - - 50微秒的延時子程序
{
uint i,j;
for(i=n*10;i>0;i--) // - - 晶振及單片機修改設置
for(j=22;j>0;j--);
}
|