单片机小白,主页第一篇文章有共通代码详解。
独立按键一:按下数码管显示数值增加(>9999变0000)
独立按键二:按下数码管显示数值减少(<0000变9999)
独立按键三:按下数码管显示数值及退出0-9999的自增
独立按键四:按下数码管显示0-9999的自增,间隔1秒
运行效果:
代码:
#include <reg52.h>
sbit button1=P3^1;
sbit button2=P3^0;
sbit button3=P3^2;
sbit button4=P3^3;
sbit add_1=P2^2;
sbit add_2=P2^3;
sbit add_3=P2^4;
short int n=0;
unsigned char code a[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
//DingshiQi YanShi
void delay_ds(unsigned char ms)
{
unsigned char T=0;
TMOD=0x01;
TH0=0xfb;
TL0=0x80;
TR0=1;
while(T<ms)
{
if(TF0==1)
{
TF0=0;
TH0=0xfb;
TL0=0x80;
T++;
}
}
}//1.25*ms
//shuaxin
void shuaxin()
{
add_1=0;
add_2=0;
add_3=0;
P0=a[n%10];
delay_ds(2);
P0=0x00;
add_1=1;
add_2=0;
add_3=0;
P0=a[n/10%10];
delay_ds(2);
P0=0x00;
add_1=0;
add_2=1;
add_3=0;
P0=a[n/100%10];
delay_ds(2);
P0=0x00;
add_1=1;
add_2=1;
add_3=0;
P0=a[n/1000%10];
delay_ds(2);
P0=0x00;
} //10ms
//1 s
void Ding_shi()
{
unsigned char T=0;
TMOD=0x01;
TH0=0xf7;
TL0=0x00; //2.5ms
shuaxin(); //10ms 12.5ms
TR0=1;
while(T<80)
{
if(TF0==1)
{
TF0=0;
TH0=0xf7;
TL0=0x00; //2.5
shuaxin(); //10ms 12.5ms*80=1000ms
T++;
}
}
}
void main()
{
button1=0xff;
button2=0xff;
button3=0xff;
button4=0xff;
while(1)
{
shuaxin();
if(button1==0)
{
delay_ds(1);
if(button1==0)
{
while(!button1)
{
n++;
if(n>9999)
n=0;
shuaxin();
}
}
}
if(button2==0)
{
delay_ds(1);
if(button2==0)
{
while(!button2)
{
n--;
if(n<0)
n=9999;
shuaxin();
}
}
}
if(button3==0)
{
delay_ds(1);
if(button3==0)
{
while(!button3)
{
shuaxin();
}
}
}
if(button4==0)
{
delay_ds(1);
if(button4==0)
{
while(button3!=0)
{
n++;
if(n>9999)
{
n=0;
break;
}
Ding_shi();
}
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)