一、創建頭文件lcd1602.h代碼如下:
#ifndef __LCD1602_H_ #define __LCD1602_H_ #include <reg52.h> #include <stdio.h> #define uint unsigned int //定義常用數據類型替代碼 #define uchar unsigned char #define dat P0 //定義LCD1602的數據口為P0 sbit rs=P1^4; //定義RS口為P14 sbit rw=P1^5; //定義RW口為P15 sbit e=P1^6; //定義E口為P16 void display(unsigned int temp); void int_1602(void); //啟動LCM程序 void dat_1602(uchar a); //寫數據到LCM程序 void com_1602(uchar a); //寫指令到LCM程序 void busy_1602(void); //查詢忙碌標志信號程序 void delay_1ms(void); //延時程序 void Delay(unsigned int i); #endif
二、創建編譯文件lcd1602.c代碼如下:
#include "lcd1602.h" //此文件中定義了單片機的一些特殊功能寄存器 uchar busy; //1602判忙標志 uint i=0; uint j=0; uint temp; void Delay(unsigned int i) { while(i--); } void delay_1ms(void) //延時程序 { uchar i,j; for(i=0;i<10;i++) for(j=0;j<20;j++); } void busy_1602(void) //查詢忙碌標志信號程序 { do { e=0; rw=1; rs=0; e=1; busy=dat; e=0; delay_1ms(); } while(busy&&0x10==1); } void com_1602(uchar a) //寫指令到LCM程序 { busy_1602(); e=0; rw=0; rs=0; e=1; dat=a; e=0; } void dat_1602(uchar a) //寫數據到LCM程序 { busy_1602(); e=0; rw=0; rs=1; e=1; dat=a; e=0; } void int_1602(void) //啟動LCM程序 { com_1602(0x38); com_1602(0x0c); com_1602(0x06); } void display(unsigned int temp) //顯示溫度 { uchar rev_data[16]={" -temperature!- "}; com_1602(0x80); for(i=0;i<16;i++) //發送數據第一行 { dat_1602(rev_data[i]); } temp*=10; com_1602(0xc0);//第二行 dat_1602('T'); dat_1602('H'); dat_1602('='); dat_1602(temp/100%10+0x30); dat_1602(temp/10%10+0x30); dat_1602('.'); dat_1602(temp%10+0x30); dat_1602(0xdf); dat_1602('C'); }