采用外部中断控制定时器,用两位数数码管显示60秒计时代码,只显示秒位,计时60秒后清零,清零后按下外部中断按键继续计时,按下外部中断按键可使计时器暂停,
时间: 2023-06-16 10:08:01 浏览: 76
下面是基于51单片机的C语言代码实现:
```c
#include <reg51.h>
sbit LED = P1^0; //定义LED控制引脚
sbit INT0 = P3^2; //定义外部中断INT0引脚
sbit INT1 = P3^3; //定义外部中断INT1引脚
sbit DIO = P2^0; //定义数码管DIO引脚
sbit CLK = P2^1; //定义数码管CLK引脚
unsigned char code segCode[]={ //显示0~9的数码管段码
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
unsigned char cnt = 0; //计时器计数值
unsigned char flag = 0; //计时器计时标志
unsigned char pause = 0; //计时器暂停标志
void delay(unsigned int t) //延时函数
{
unsigned int i, j;
for(i = t; i > 0; i--)
for(j = 110; j > 0; j--);
}
void writeByte(unsigned char dat) //写入一个字节到数码管
{
unsigned char i;
for(i = 0; i < 8; i++)
{
DIO = dat & 0x01;
CLK = 0;
delay(1);
CLK = 1;
delay(1);
dat >>= 1;
}
}
void display(unsigned char dat) //数码管显示函数
{
writeByte(segCode[dat]);
}
void timer() interrupt 1 //定时器中断服务函数
{
TH0 = 0x3c;
TL0 = 0xb0;
cnt++; //计时器计数器加1
if(cnt == 60) //计时器计数值达到60
{
cnt = 0;
flag = 1; //计时器计时标志置1
}
}
void main()
{
TMOD = 0x01; //定时器0工作在模式1
TH0 = 0x3c;
TL0 = 0xb0;
ET0 = 1; //开启定时器0中断
EA = 1; //开启总中断
while(1)
{
if(flag) //计时器计时标志为1
{
flag = 0;
if(!pause) //计时器未暂停
{
if(cnt == 0) //计时器计数值清零
{
LED = ~LED; //LED翻转
delay(1000);
LED = ~LED;
}
display(cnt % 10); //显示秒位
}
}
if(!INT0) //外部中断INT0按键按下
{
delay(10);
if(!INT0) //再次检测按键状态,确保按键真正被按下
{
pause = ~pause; //计时器暂停标志置反
while(!INT0); //等待按键释放
}
}
if(cnt == 0 && pause) //计时器计数值清零且计时器已暂停
{
display(0); //显示0
}
}
}
```
注:数码管使用的是共阴数码管,CLK接P2.1,DIO接P2.0。外部中断按键需要使用上拉电阻,按下时引脚会被拉低。