标题51单片机实现LED数码管0-9999秒的计时功能
一.实现原理:
P0口给高低电平控制LED灯亮暗,来显示数字;
74HC138实现数码管高低电平状态,循环实现数码管动态扫描显示。
LED1-LED8要给到低电平,P00-P07给到高电平,数码管即可显示,
循环实现LED1-LED4的动态显示。
二.逻辑算法:
P22-P24逻辑关系
P0显示数字逻辑:
DotNumMatrix[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};分别对应0-9;
定时器定时:
初始化设定(把timer0设成16位模式):
TH0和TL0设定:
晶振频率 freq_xtal=11.0592MHz
传统8051单片机定时器一般计数速率为12T mode
即12个晶振周期定时器加一;
mode0模式下定时器计时到0xFFFF(65535)再加1即触发中断;
(TH0<<8)|TL0=65536-freq_xtal/12/1000=0xFC67;//1ms timer calculation method in 12T mode
三.功能函数
void DisplayLED(u16 sec)
{
u8 Thous,Hundr,Tens,Single;
Thous=sec/1000;
Hundr=(sec-Thous*1000)/100;
Tens=(sec-Thous*1000-Hundr*100)/10;
Single=sec%10;
while1_counter++;
switch(while1_counter%4)
{
case 0:
P2=0x00;
P0=DotNumMatrix[Single];
break;
case 1:
P2=0x04;
P0=DotNumMatrix[Tens];
break;
case 2:
P2=0x08;
P0=DotNumMatrix[Hundr];
break;
case 3:
P2=0x0C;
P0=DotNumMatrix[Thous];
break;
case 4:
P2=0x10;
P0=DotNumMatrix[sec/10000];
break;
case 5:
P2=0x14;
P0=DotNumMatrix[sec/100000];
break;
case 6:
P2=0x18;
P0=DotNumMatrix[sec/1000000];
break;
case 7:
P2=0x1C;
P0=DotNumMatrix[sec/10000000];
break;
}
delay(100);
P0=0;
}
void Init_Timer(void)
{
EA = 0;
ET0=1; // enable timer 0 interrupt
TH0 = 0xFC;
TL0 = 0x18; // timer 0 counter
TF0=0; // timer 1 flag
/* -------------initialize Timer 0 -----------------------------*/
ET1=0; // disable timer 1 interrupt
TH1=0;
TL1=0; // timer 1 counter
TF1=0; // timer 1 flag
// setup Timer mode
// TMOD=0x11; // set timer 1 as timer(1) , timer 0 as counter(5)
TMOD=0x01;
// enable/disable timer
TR0=1; // disable timer 0
TR1=0; // disable timer 1
EA = 1;
}
void Timer0() interrupt 1
{
TH0 = 0xFC;
TL0 = 0x67; // timer 0 counter
ms_Counter--;
if (ms_Counter == 0)
{
Set_SecondFlag();
ms_Counter=SystemTick;
// LED=~LED;
}
}
void TimerHandler()
{
if(SecondFlag)
{
Second++;
Clr_SecondFlag();
if(Second>=9999)
Second=0;
}
}
void main()
{
Init_Timer();
while(1)
{
DisplayLED(Second);
TimerHandler();
}
}
四.实际效果图片:
计时到4387