#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
uchar code disp1[]="HELLO WORLD";
uchar code disp2[]="LCD1602 TEST";
//LCD1602引腳定義
//采用8位并行方式,DB0~DB7連接至P20~P27
sbit RS=P1^2;
sbit RW=P1^1;
sbit CS=P1^0;
#define LCDDATA P2
//功能:延時1毫秒
void Delay_xms(uint x)
{
uint i,j;
for(i=0;i<x;i++)
for(j=0;j<122;j++);
}
//功能:12us延時
void Delay_xus(uint t)
{
for(;t>0;t--)
{
_nop_();
}
}
//控制LCD寫時序
void LCD_en_write(void)
{
CS=1;//EN端產生一個高電平脈沖,控制LCD寫時序
Delay_xus(20);
CS=0;
Delay_xus(20);
}
//寫指令函數
void Write_Instruction(uchar command)
{
RS=0;
RW=0;
CS=1;
LCDDATA=command;
LCD_en_write();//寫入指令數據
}
//寫數據函數
void Write_Data(uchar Wdata)
{
RS=1;
RW=0;
CS=1;
LCDDATA=Wdata;
LCD_en_write();//寫入數據
}
//字符顯示初始地址設置
void LCD_SET_XY(uchar X,uchar Y)
{
uchar address;
if(Y==0)
address=0x80+X;//Y=0,表示在第一行顯示,地址基數為0x80
else
address=0xc0+X;//Y非0時,表時在第二行顯示,地址基數為0xC0
Write_Instruction(address);//寫指令,設置顯示初始地址
}
//在第X行Y列開始顯示,指針*S所指向的字符串
void LCD_write_str(uchar X,uchar Y,uchar *s)
{
LCD_SET_XY(X,Y);//設置初始字符顯示地址
while(*s)//逐次寫入顯示字符,直到最后一個字符"/0"
{
Write_Data(*s);//寫入當前字符并顯示
s++;//地址指針加1,指向下一個待寫字符
}
}
//在第X行Y列開始顯示Wdata所對應的單個字符
void LCD_write_char(uchar X,uchar Y,uchar Wdata)
{
LCD_SET_XY(X,Y);//寫地址
Write_Data(Wdata);//寫入當前字符并顯示
}
//清屏函數
void LCD_clear(void)
{
Write_Instruction(0x01);
Delay_xms(5);
}
//顯示屏初始化函數
void LCD_init(void)
{
Write_Instruction(0x38); //8bit interface,2line,5*7dots
Delay_xms(5);
Write_Instruction(0x38);
Delay_xms(5);
Write_Instruction(0x38);
Write_Instruction(0x08); //關顯示,不顯光標,光標不閃爍
Write_Instruction(0x01); //清屏
Delay_xms(5);
Write_Instruction(0x04); //寫一字符,整屏顯示不移動
//Write_Instruction(0x05); //寫一字符,整屏右移
//Write_Instruction(0x06); //寫一字符,整屏顯示不移動
//Write_Instruction(0x07); //寫一字符,整屏左移
Delay_xms(5);
//Write_Instruction(0x0B); //關閉顯示(不顯示字符,只有背光亮)
Write_Instruction(0x0C); //開顯示,光標、閃爍都關閉
//Write_Instruction(0x0D); //開顯示,不顯示光標,但光標閃爍
//Write_Instruction(0x0E); //開顯示,顯示光標,但光標不閃爍
//Write_Instruction(0x0F); //開顯示,光標、閃爍均顯示
}
void main(void)
{
uchar i;
Delay_xms(50);//等待系統穩定
LCD_init(); //LCD初始化
LCD_clear(); //清屏
LCD_write_str(0,0,disp1);//顯示開機信息
LCD_write_str(0,1,disp2);
Delay_xms(2000);//保持顯示2秒鐘
LCD_clear(); //清屏
for(i=0;i<16;i++)
{
LCD_write_char(i,0,0x41+i);//從第0行第0個位置開始顯示A~P
Delay_xms(500);//延時0.5秒
}
for(i=0;i<16;i++)
{
LCD_write_char(i,1,0x30+i%10);//從第1行第0個位置開始顯示0~9
Delay_xms(500);//延時0.5秒
}
while(1);//程序掛起
}
|