#include <REGX51.H>
typedef unsigned int uint;
typedef unsigned char uchar;
sbit LED=P1^7;
sbit KEY1=P3^2;
sbit KEY2=P3^3;
sbit ge=P1^1;
sbit shi=P1^0;
uchar code num_tab[10]= {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//共阳数码管数组
bit start=0;//启动位
uchar count=0;
void Delay1ms() //@12.000MHz
{
unsigned char i, j;
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
}
void delay_ms(uint xms)//毫秒级延时函数
{
uint i=0;
for(i=0;i<xms;i++)
{
Delay1ms();
}
}
void Timer0_Init(void) //1毫秒@12.000MHz
{
TMOD = 0x01; //设置定时器模式
TL0 = 0x18; //设置定时初始值
TH0 = 0xFC; //设置定时初始值
TF0 = 0; //清除TF0标志
TR0 = 0; //定时器0开始计时
ET0=1;
EA=1;
}
void Extern_interrupt_init(void)//外部中断初始化
{
EA=1;
IT0=1;
EX0=1;
IT1=1;
EX1=1;
}
void LED_TASK(void)//LED闪烁任务
{
uchar i=0;
for(i=0;i<4;i++)
{
LED=!LED;
delay_ms(500);
}
}
void Display_num(uchar num,uchar wei)//数码管显示函数
{
P2=0Xff;//为了消隐
ge=1;
shi=1;
switch(wei)
{
case 1:ge=0;break;
case 2:shi=0;break;
}
P2=num_tab[num];//传递数据
}
void Display(void)//数码管动态显示函数
{
if(start==1)
{
Display_num(count%10,2);
delay_ms(5);
Display_num(count/10%10,1);
delay_ms(5);
}
else
{
P2=0XFF;ge=shi=1;
}
}
void main(void)//主函数
{
LED_TASK();
Timer0_Init();
Extern_interrupt_init();
while(1)
{
Display();
}
}
void KEY1_intr() interrupt 0//外部中断0服务函数
{
if(KEY1==0)
{
delay_ms(10);
if(KEY1==0)
{
TR0=1;//开启定时器
count=0;//清空计数值
start=1;//赋值启动位
}
}
}
void KEY2_intr() interrupt 2//外部中断1服务函数
{
if(KEY2==0)
{
delay_ms(10);
if(KEY2==0)
{
TR0=!TR0;//选择开启停止定时器
}
}
}
void TIMER0() interrupt 1//定时器中断服务函数
{
static uint jishu=0;//1ms进一次中断
TL0 = 0x18; //设置定时初始值
TH0 = 0xFC; //设置定时初始值
if(start==1)
{
jishu++;
if(jishu>=1000)//即1s加一次计时
{
count++;
jishu=0;
if(count>=19)
{
TR0=0;
}
}
}
}