//一个简单的时钟程序
#include<reg52.h> //89C52包含的头文件
unsigned char w=2,h=3,n=5,m=9,q=5,p=9;//时钟初值,依次代表时分秒
unsigned char k=10; //初值为10,用于显示show[10],即中间的横线
unsigned char show[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xbf,0xff};//数码显示0~9+中间横线显示
void display2();//时钟显示模块
unsigned char i=0;
unsigned char tcount=0;
void delay(unsigned int k)//软件延时子程序
{
while(k--);
}
void main() //主函数入口
{
TMOD=0X01; //设置定时器0为工作方式1
TH0=(65536-50000)/256; //设置定时器初值高8位
TL0=(65536-50000)%256; //设置定时器初值低8位
//工作方式1为16进制计数器,当计数超过65535到65536则清零,并调用定时器中断
EA=1; //总中断打开
ET0=1; //定时器0中断打开
TR0=1; //启动定时器0。开始计时
while(1) //主程序循环入口
{
display2();
}
}
void display2() //时钟显示程序,P2表示位选,即为第几个数码管,P0表示段选,即显示什么数字
{
while(1)
{
P2=0x80;
P0=show[p];
delay(80);
P2=0x40;
P0=show[q];
delay(80);
P2=0x20;
P0=show[k];
delay(80);
P2=0x10;
P0=show[m];
delay(80);
P2=0x08;
P0=show[n];
delay(80);
P2=0x04;
P0=show[k];
delay(80);
P2=0x02;
P0=show[h];
delay(80);
P2=0x01;
P0=show[w];
delay(80);
}
}
void time() interrupt 1//定义中断子程序,其中interrupt 1即对应定时器0的中断,调用不同中断按参考序号
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256; //调用中断后再次给初值,使得下次计数依然从初值开始,而不是从0开始
tcount++; //调用一次中断计数器加1
if(tcount==20) //因为定时器0为12M时钟,故50000个机器周期才50ms,需要20次才能精确定义1S
{
tcount=0; //20次后清零
//下面程序即为时分秒之间的循环关系了
p++;
if(p==10) //秒的第二位
{
p=0;
q++;
if(q==6)//秒的第一位
{
q=0;
m++;
if(m==10) //分的第二位
{
m=0;
n++;
if(n==6)//分的第一位
{
n=0;
h++;
if((w<=2)&&(h==10))
{
h=0;
w++;
}
}
}
}
}
}
//判断是否为24小时,24小时则执行时位清零
if((w==2)&&(h==4))
{
h=0,w=0;
}
}