数码管倒计时led闪烁和蜂鸣器作响
实验单片机晶振为11.0592
#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar num = 0;
sbit led0 = P2^0;
sbit led2 = P2^2;
sbit led3 = P2^3;
sbit led4 = P2^4;
sbit beep = P1^5;
uchar code duanxuan[] = {0x3f,0x06,0x5b,0x4f, //0,1,2,3
0x66,0x6d,0x7d,0x07, //4,5,6,7
0x7f,0x6f,0x77,0x7c, //8,9,A,B
0x39,0x5e,0x79,0x71}; //C,D,E,F 段选
void fp(int i) //调整蜂鸣器音调
{
while(i--);
}
void Display(int i,int j,int k) //数码管动态显示
{
switch(i)
{
case(0):P0=duanxuan[j];led2=1,led3=1,led4=1;break;
case(1):P0=duanxuan[k];led2=0,led3=1,led4=1;break;
case(2):led2=1,led3=0,led4=1;break; //2-7暂时没用到,可忽略
case(3):led2=0,led3=0,led4=1;break;
case(4):led2=1,led3=1,led4=0;break;
case(5):led2=0,led3=1,led4=0;break;
case(6):led2=1,led3=0,led4=0;break;
case(7):led2=0,led3=0,led4=0;break;
}
}
void main()
{
int i=0,time=60,j=time/10,k=time%10;
TMOD = 0X01; //定时器模式为0,1;16位定时器
TH0 = (65536-45872)/256; //高八位赋初值
TL0 = (65536-45872)%256; //低八位赋初值
EA = 1; //中断总开关
ET0 = 1; //定时器中断开关
TR0 = 1; //定时器开始计时
led0 = 0;
while(1)
{
if(num == 20)
{
led0 = ~led0;
num = 0;
time--;
if(time < 0) //当计时结束从新开始
{
time=60;
}
j=time/10,k=time%10; //将数字分为十位和个位分别输入数码管
}
if(led0 == 0) //led亮时蜂鸣器作响
{
beep = ~beep;
fp(1);
}
Display(i,j,k); //数码管显示
i = (i+1)%2;
fp(100);
P0=0; //消影,注意消影的间隔和视觉暂留的间隔不能太短,否则灯会不太明亮
} //因此前面需要延时100
}
void TR0_time() interrupt 1 //定时器中断程序
{
TH0 = (65536-45872)/256;
TL0 = (65536-45872)%256;
num++;
}