//简易秒表,T1定时器,方式1,9999秒定时
#include<reg51.h>
#define uchar unsigned char
#define TH1_DATA (65536-50000)/256
#define TL1_DATA (65536-50000)%256
#define count_1s 20
int time_value=0;
#define SET_PORT P0
sbit DIS_TENS=P1^1; //显示数码秒值十位的公共端
sbit DIS_UNIT=P1^0; //显示数码秒值个位的公共端
sbit DIS_HUND=P1^2; //显示数码秒值百位的公共端
sbit DIS_THOU=P1^3; //显示数码秒值千位的公共端
sbit key=P3^2; //定义按键接口P3^2
bit flag_1s; //定义1秒时间到标志
void delay(uchar);
uchar dis_number[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; //0~9的字形码
void main(void)
{
uchar time_thou=0,time_hund=0,time_tens=0,time_unit=0;
TMOD=0x10;
TH1=TH1_DATA;
TL1=TL1_DATA;
ET1=1;
EA=1;
TR1=1; //启动定时器
IT0=1; //外部中断0
EX0=1;
EA=1;
while(1)
{
if(flag_1s == 1) //如果1s到了
{
flag_1s=0; //标记重新清0
time_value++; //1S次数加1
if(time_value >= 10000) //如果到了10000秒
{
time_value=0; //1s的次数归0
}
time_thou=time_value / 1000; //计算当前秒表计时值的千位
time_hund=(time_value % 1000) / 100; //计算当前秒表计时值的百位
time_tens=(time_value % 100) / 10; //计算当前秒表计时值的十位
time_unit=time_value % 10; //计算当前秒表计时值的个位
}
//显示千位数字
SET_PORT=dis_number[time_thou]; //送段码
DIS_THOU=0; //送位码
delay(4); //延时
DIS_THOU=1; //关闭当前显示位
//显示百位数字
SET_PORT=dis_number[time_hund];
DIS_HUND=0;
delay(4);
DIS_HUND=1;
//显示十位数字
SET_PORT=dis_number[time_tens];
DIS_TENS=0;
delay(4);
DIS_TENS=1;
//显示个位数字
SET_PORT=dis_number[time_unit];
DIS_UNIT=0;
delay(4);
DIS_UNIT=1;
}
}
void int_t3() interrupt 3 using 1
{
static uchar count_50ms=0;
TH1=TH1_DATA;
TL1=TL1_DATA;
count_50ms++;
if(count_50ms >= count_1s)
{
count_50ms=0;
flag_1s=1;
}
}
void int_t1() interrupt 1 using 1 //当按键按下时
{
TR1=~TR1; //定时器的状态取反
}
void delay(uchar x)
{
uchar i,j;
for(i=x;i>0;i--)
{
for(j=250;j>0;j--)
{
;
}
}
}
|