一、实验要求:
设计一个基于51单片机的电子时钟, 具有显示年、月、日、星期、时、分、秒、闹钟功能
二、主要电子元件:
- STC89C52单片机
- 1602LCD显示屏
- 无源蜂鸣器
- 11.0592MHz晶振
- 排阻
- 电容、电阻、三极管等
三、原理图
四、程序代码
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit BF = P0^7;
sbit EN = P2^5;
sbit RS = P1^0;
sbit RW = P1^1;
sbit dula=P2^6;
sbit wela=P2^7;
sbit s1=P3^0;
sbit s2=P3^1;
sbit s3=P3^2;
sbit s4=P3^3;
sbit rd=P3^7;
sbit fm=P2^3;
uint num;
unsigned long int dat,nian=2016;
char miao=55,shi=23,fen=59,xingqi=6,kg,ri=31,yue=12,count,s1num,s4num,cshi=0,cfen=0,cmiao=0,zt;
uchar code table[]=" - - ";
uchar code table1[]=" : : ";
uchar code *table2[7]={
"MON","TUE","WED","THU","FRI","SAT","SUN"};
uchar code *table3[2]={
"OF","ON"};
uchar code alarm[]={
" alarm setting "};
void delayms(uint z)//延时
{
uint i,j;
for(j=z;j>0;j--)
for(i=110;i>0;i--);
}
void wait(void)//判忙
{
P0=0xFF;
do{
RS=0;
RW=1;
EN=0;
EN=1;
}
while (BF==1);
EN=0;
}
void w_dat(uchar dat)//数据写入
{
wait();
EN=0;
P0=dat;
RS=1;
RW=0;
EN=1;
EN=0;
}
void w_cmd(uchar cmd)//命令写入
{
wait();
EN=0;
P0=cmd;
RS=0;
RW=0;
EN=1;
EN=0;
}
void w_sfm(uchar add,uchar date)//时分秒写入
{
uchar shi,ge;
shi=date/10;
ge=date%10;
w_cmd(0x80+add);
w_dat(0x30+shi);
w_dat(0x30+ge);
}
void w_nian(uchar add, unsigned long int dat) //年份写入
{
uchar qian,bai,shi,ge;
ge=dat%10;
shi=(dat/10)%10;
bai=(dat/100)%10;
qian=(dat/1000)%10;
w_cmd(0x80+add);
w_dat(0x30+qian);
w_dat(0x30+bai);
w_dat(0x30+shi);
w_dat(0x30+ge);
}
void xianshi(void)//显示函数
{
w_cmd(0x80);
for(num=0;num<16;num++){
w_dat(table[num]);
} //显示日期
w_cmd(0x80+0x40);
for(num=0;num<16;num++){
w_dat(table1[num]);
}
w_nian(1,nian);
w_sfm(6,yue);
w_sfm(9,ri);
w_cmd(0x80+12);
for(num=0;num<3;num++)
w_dat(table2[xingqi][num]);
w_sfm(0x40+4,shi);
w_sfm(0x40+7,fen);
w_sfm(0x40+10,miao); //显示时间
}
void Init_LCD1602(void)//初始化
{
dula=0;
wela=0;
w_cmd(0x38);
w_cmd(0x0c);
w_cmd(0x06);
w_cmd(0x01);
w_cmd(0x80);
xianshi();
TMOD=0x01;
TH0=(65536-50000)/