學習LCD1602過程的一個入門程式,在proteus8.3驗證通過
/* Main.c file generated by New Project wizard
*
* Created: 周三 6月 28 2017
* Processor: AT89C52
* Compiler: Keil for 8051
*/
#include <stdio.h>
#include <reg52.h>
#include <string.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit RS = P2^;
sbit RW = P2^;
sbit EN = P2^;
sbit BTN = P3^;
//判斷液晶忙,如果忙則等待,因為1602也是一個CPU,要處理原來的指令,如果不判斷會導緻資料紊亂
void Read_Busy() //讀寫檢查函數
{
uchar busy;
P0 = ; //P0口作為資料端
RS = ;
RW = ; //讀狀态的操作時序為 RS=L,RW=H,E=H,D0~D7輸出狀态字
do
{
EN = ;
busy = P0;
EN = ;
}while(busy & );
//狀态字為busy(8位2進制數)的最高位,
//若為1則禁止讀寫,為0則允許讀寫,該狀态用busy&0x80的結果表示
}
void Write_Cmd(uchar cmd) //寫指令函數
{
Read_Busy();//對控制器每次進行讀寫操作都要判斷是否正忙,即要進行讀寫檢測
RS = ;
RW = ;
P0 = cmd; //寫入十六進制形式的指令(command)
EN = ; //寫指令的操作時序:RS=0,RW=0,EN=高脈沖
EN = ; //獲得高脈沖後使能端重新置零
}
void Write_Dat(uchar dat) //寫入資料
{
Read_Busy(); //寫入資料前進行讀寫檢測
RS = ;
RW = ;
P0 = dat; //P0口寫入資料
EN = ; //寫資料操作時序:RS=0,RW=0,EN=高脈沖
EN = ; //獲得高脈沖後使能端重新置零
}
void LCD1602_Init()
{
Write_Cmd();//設定16*2顯示
Write_Cmd();//開顯示 顯示光标,光标閃爍
Write_Cmd();//清屏
Write_Cmd();//位址指針移位指令
Write_Cmd( | );//顯示位址,0x80是第一行的的首位址。0x80|0x06表示資料從第一行第7個字元位置開始顯示
}
void PrintStr(char *str)
{
char i,len;
len = strlen(str); // 擷取字元串長度
for(i=;i<len;i++)
{
Write_Dat(*str);
str++;
}
}
void main()
{
char *str="hello123";
LCD1602_Init(); // 初始化LCD1602
Write_Dat('H');
Write_Dat('e');
Write_Dat('l');
Write_Dat('l');
Write_Dat('o');
Write_Dat(' ');
Write_Dat(' ');
Write_Dat(' ');
Write_Dat('2');
Write_Cmd( || ); // 顯示第二行
// 顯示位址,0x80|0x40表示第二行,0x40是第二行的的首位址。也可以寫成0x80+0x40或者0xc0,
// 0xc0|0x0c表示資料從第一行第13個字元位置開始顯示
// 由于1602一行隻顯示16個字元,是以從第十三個字元位置顯示的話隻能顯示4位
PrintStr(str);
while();
}
實驗結果如下:
參考文章:http://blog.csdn.net/u013151320/article/details/46663167
2017/6/28更正
更正main函數顯示LCD第二行的程式,之前初始化錯了
添加PrintStr(char *str)函數,輸出字元串
使用到了strlen函數,記得頭檔案要include “string.h”
void PrintStr(char *str)
{
char i,len;
len = strlen(str); // 擷取字元串長度
for(i=;i<len;i++)
{
Write_Dat(*str);
str++;
}
}