用 定时/计数器中断 和 动态八段数码管做一个秒表
学以致用,简单把定时器中断和数码管动态显示结合一下。
1.思路
使用定时器来计数,然后把秒数变化显示到数码管上。
定时器
数码管
2.主要代码讲解
void main()
{
u16 a;
a = 0;
Time0Init();//定时器0中断的初始化操作
while(1)
{
if(i == 1000)//设定一次中断是1ms,1000次是1s
{
i = 0; //把计数的i清零,方便下一秒计数1000次
led = ~led; //起到提示作用
a++; //累计的秒数
}
else if(i%25 == 0) //每25ms刷新一次
{
fenbian(a); // 数码管显示函数
}
}
}
3.全部代码参考(代码写的很烂,欢迎提出建议)
#include<reg51.h>
typedef unsigned char u8;
typedef unsigned int u16;
sbit led = P2^0;
static u16 i;
static u16 a;
sbit LSA = P2^2;
sbit LSB = P2^3;
sbit LSC = P2^4;
u8 code smgduan[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
void delay(u16 i)
{
while(i--);
}
void Time0Init()
{
TMOD|=0x01;
TH0 = 0xFC;
TL0 = 0x66;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void fenbian(u16 a)
{ int b;
int c;
if(a<10)
{
LSC=0;LSB=0;LSA=0;
delay(100);
switch(a)
{
case(0):P0=smgduan[0];delay(100);break;
case(1):P0=smgduan[1];delay(100);break;
case(2):P0=smgduan[2];delay(100);break;
case(3):P0=smgduan[3];delay(100);break;
case(4):P0=smgduan[4];delay(100);break;
case(5):P0=smgduan[5];delay(100);break;
case(6):P0=smgduan[6];delay(100);break;
case(7):P0=smgduan[7];delay(100);break;
case(8):P0=smgduan[8];delay(100);break;
case(9):P0=smgduan[9];delay(100);break;
}
P0 = 0x00;
}
else if(a>=10 && a<100)
{
LSC=0;LSB=0;LSA=0;
b = a/1%10;
switch(b)
{
case(0):P0=smgduan[0];delay(100);break;
case(1):P0=smgduan[1];delay(100);break;
case(2):P0=smgduan[2];delay(100);break;
case(3):P0=smgduan[3];delay(100);break;
case(4):P0=smgduan[4];delay(100);break;
case(5):P0=smgduan[5];delay(100);break;
case(6):P0=smgduan[6];delay(100);break;
case(7):P0=smgduan[7];delay(100);break;
case(8):P0=smgduan[8];delay(100);break;
case(9):P0=smgduan[9];delay(100);break;
}
P0 = 0x00;
LSC=0;LSB=0;LSA=1;
c = a/10%10;
switch(c)
{
case(0):P0=smgduan[0];delay(100);break;
case(1):P0=smgduan[1];delay(100);break;
case(2):P0=smgduan[2];delay(100);break;
case(3):P0=smgduan[3];delay(100);break;
case(4):P0=smgduan[4];delay(100);break;
case(5):P0=smgduan[5];delay(100);break;
case(6):P0=smgduan[6];delay(100);break;
case(7):P0=smgduan[7];delay(100);break;
case(8):P0=smgduan[8];delay(100);break;
case(9):P0=smgduan[9];delay(100);break;
}
P0 = 0x00;
}
}
void main()
{
u16 a;
a = 0;
Time0Init();
while(1)
{
if(i == 1000)
{
i = 0;
led = ~led;
a++;
}
else if(i%25 == 0)
{
fenbian(a);
}
}
}
//中断函数,但是我把处理放在主函数中,这样可以保证计数的准确
void Time0() interrupt 1
{
TH0 = 0xFC;
TL0 = 0x66;
i++;
}
参考:https://blog.csdn.net/m0_50679156/article/details/120097808