|
單片機作業分享:
電子時鐘1602顯示。
具體計時到每一天,年月恒定(太麻煩)。
僅供學習和參考。
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
uint tt = 0;
uint nian,yue,ri,shi,fen,miao;
sbit RS = P2^5;
sbit RW = P2^6;
sbit E = P2^7;
void delay(uint z ) //1ms延時程序
{
uint x,y;
for(x=0;x<z;x++)
for(y=0;y<114;y++)
;
}
void wrcom(uchar com) //1602寫指令
{
RS = 0;
_nop_();
RW = 0;
delay(2);
P0 = com;
delay(2);
E = 1;
delay(2);
E = 0;
}
void wrdat(uchar dat) //1602寫數據
{
RS = 1;
_nop_();
RW = 0;
delay(2);
P0 = dat;
delay(2);
E = 1;
delay(2);
E = 0;
}
void init_1602() //1602初始化
{
wrcom(0x38);
delay(15);
wrcom(0x38);
delay(5);
wrcom(0x38);
delay(5);
wrcom(0x38);
wrcom(0x38);
wrcom(0x08);
wrcom(0x01);
wrcom(0x06);
wrcom(0x0c);
}
void busy() //1602忙檢測
{
bit busy_flag;
P0 =0x80;
RS = 0;
_nop_();
RW = 1;
delay(2);
E = 1;
while(1)
{
busy_flag = (bit)(P0&0x80);
if(busy_flag == 0)
break;
}
E = 0;
RW = 0;
}
void init_timer() //定時器0 方式2初始化
{
TMOD = 0x02;
TH0 = 0xa4;
TL0 = 0xa4;
ET0 = 1;
EA = 1;
TR0 = 1;
}
void init_time() //時間設定
{
nian = 2012;
yue = 11;
ri = 16;
shi = 20;
fen = 30;
miao = 0;
}
void time()
{
if(tt > 10000) //時間狀態判定
{
miao++;
tt = 0;
if(miao == 60)
{
miao = 0;
fen++;
if(fen == 60)
{
fen = 0;
shi++;
if(shi == 24)
{
shi = 0;
ri++;
if(ri == 30)
{
ri = 0;
yue ++;
}
}
}
}
}
}
void main(void) //主函數
{
uchar table1[10] = {'2','0','1','2','/','1','1','/','0','0'}; //時間裝入字符數組為了1602
uchar table2[8] = {'0','0',':','0','0',':','0','0'};
uchar i;
init_time();
init_timer();
init_1602(); //初始化
while(1)
{
time();
table1[8] = (char)(ri/10+48);
table1[9] = (char)(ri%10+48);
table2[0] = (char)(shi/10+48);
table2[1] = (char)(shi%10+48);
table2[3] = (char)(fen/10+48);
table2[4] = (char)(fen%10+48);
table2[6] = (char)(miao/10+48);
table2[7] = (char)(miao%10+48);
busy();
wrcom(0x80+0x03);
for(i=0;i<10;i++)
{
busy();
wrdat(table1[i]); //1602第一排寫入年月日
}
busy();
wrcom(0x80+0x44);
for(i=0;i<8;i++)
{
busy();
wrdat(table2[i]); //1602第二排寫入時分秒
}
}
}
void timer()interrupt 1
{
tt++;
}
|
|