写了一个程序:利用51
单片机的独立键盘S1控制数码管跑数的开始。但是显示结果一直是0000,是哪里错了呢,我觉得逻辑是对的啊。程序和原理图如下:
#include<reg52.h>
#define uchar unsigned char
void delay(uchar z);
void
timer_init();
void display(short num);
sbit S1 = P3^5;
sbit S2 = P3^4;
sbit S3 = P3^3;
sbit S4 = P3^2;
uchar cunter;
int shu;
uchar code leddata[]={
0xC0, //"0"
0xF9, //"1"
0xA4, //"2"
0xB0, //"3"
0x99, //"4"
0x92, //"5"
0x82, //"6"
0xF8, //"7"
0x80, //"8"
0x90 //"9"
};
int main(void)
{
/*按下S1开始计时*/
if(S1 == 0)
{
delay(5);//软件消抖
if(S1 == 0)
{
timer_init();
while(!S1);
}
}
while(1)
{
if(TF0 == 1)
{
TF0 = 0;
TH0 = (65536 - 9216) / 256;
TL0 = (65536 - 9216) % 256;
cunter++;
}
if(cunter == 10)
{
cunter = 0;
shu++;
}
if(shu == 9999)
shu = 0;
display(shu);
}
return 0;
}
/*定时器初始化*/
void timer_init()
{
TMOD = 0x01;
TH0 = (65536 - 9216) / 256;
TL0 = (65536 - 9216) % 256;
TR0 = 1;
}
/*软件延时*/
void delay(uchar z)
{
uchar x , y;
for(x = z; z > 0; z--)
for(y = 116; y > 0; y--);
}
/*数码管显示函数*/
void display(short num)
{
int ge , shi , bai , qian;
qian = num / 1000;
bai = num % 1000 / 100;
shi = num % 100 / 10;
ge = num % 10;
P0 = 0xff;
P2 = 0xf7;
P0 = leddata[ge];
delay(1);
P0 = 0xff;
P2 = 0xfb;
P0 = leddata[shi];
delay(1);
P0 = 0xff;
P2 = 0xfd;
P0 = leddata[bai];
delay(1);
P0 = 0xff;
P2 = 0xfe;
P0 = leddata[qian];
delay(1);
}
这个怎么解决呢,为了实现功能就需要这么多语句啊
谢谢,我的问题解决了,看来我还是没有深刻的理解while(1)这个死循环
#include<reg52.h>
#define uchar unsigned char
void delay(uchar z);
void timer_init();
void display(short num);
sbit S1 = P3^5;
sbit S2 = P3^4;
sbit S3 = P3^3;
sbit S4 = P3^2;
uchar cunter;
short shu;
uchar code leddata[]={
0xC0, //"0"
0xF9, //"1"
0xA4, //"2"
0xB0, //"3"
0x99, //"4"
0x92, //"5"
0x82, //"6"
0xF8, //"7"
0x80, //"8"
0x90 //"9"
};
int main(void)
{
while(1)
{
/*按下S1开始计时*/
if(S1 == 0)
{
delay(5);//软件消抖
if(S1 == 0)
{
timer_init();
//while(!S1);这条语句加上和不加,
//按下S1时的显示结果不同,来学习的同学自己试试吧
}
}
if(TF0 == 1)
{
TF0 = 0;
TH0 = (65536 - 9216) / 256;
TL0 = (65536 - 9216) % 256;
cunter++;
}
if(cunter == 10)
{
cunter = 0;
shu++;
}
if(shu == 9999)
shu = 0;
display(shu);
}
return 0;
}
/*定时器初始化*/
void timer_init()
{
TMOD = 0x01;
TH0 = (65536 - 9216) / 256;
TL0 = (65536 - 9216) % 256;
TR0 = 1;
}
/*软件延时*/
void delay(uchar z)
{
uchar x , y;
for(x = z; z > 0; z--)
for(y = 116; y > 0; y--);
}
/*数码管显示函数*/
void display(short num)
{
short ge , shi , bai , qian;
qian = num / 1000;
bai = num % 1000 / 100;
shi = num % 100 / 10;
ge = num % 10;
P0 = 0xff;
P2 = 0xf7;
P0 = leddata[ge];
delay(1);
P0 = 0xff;
P2 = 0xfb;
P0 = leddata[shi];
delay(1);
P0 = 0xff;
P2 = 0xfd;
P0 = leddata[bai];
delay(1);
P0 = 0xff;
P2 = 0xfe;
P0 = leddata[qian];
delay(1);
}
一周热门 更多>