这段代码功能是通过一个按键控制8个灯的几种情况的闪烁,现在该如何改程序可以让它有开启和关闭延迟5秒的功能?
#include<reg51.h>
void delay(unsigned char ms) //延时函数
{
unsigned char i,j,k,n;
for (k=0;k<ms;k++)
for(i=0;i<20;i++)
for(j=0;j<13;j++)
for(n=0;n<2;n++);
}
void code xianshi0() //显示模式函
{
P0 = 0xff;
}
void code xianshi1()
{
unsigned char i,j;
j=0x01;
for(i=0;i<8;i++)
{
P0=~j;
delay(50000);
j<<=1;
}
}
void code xianshi2()
{
unsigned char i,j;
j=0x55;
for(i=8;i>0;i--)
{
P0=~j;
delay(50000);
j<<=1;
}
}
void code xianshi3()
{
unsigned char i,j,n;
j=0x01;
for(i=0;i<8;i++)
{
for(n=0;n<3;n++)
{
P0=~j;
delay(20000);
P0=0xff;
delay(20000);
}
j<<=1;
}
}
void code xianshi4()
{
unsigned char i,j,n;
j=0x55;
for(i=0;i<8;i++)
{
for(n=0;n<3;n++)
{
P0=~j;
delay(20000);
P0=0xff;
delay(20000);
}
j<<=1;
}
}
void code xianshi5()
{
P0 = 0x00;
delay(50);
P0=0xff;
delay(50);
}
unsigned char i=0; //切换显示函数用变量
sbit key = P2^0; //按键接口
void (* xianshi)() = xianshi0; //指向函数的指针 用于切换显示模式 初始化显示方式0
void key_scan()
{
TR0 = 0;
TH0 = 0x3c;
TL0 = 0xb0;
TR0 = 1;
key = 1;
delay(1);
if (key == 0 )
{
delay(10); //按键消抖
if (key == 0 )
{
i++;
if(i>5) i=0;
switch(i)
{
case 0 : xianshi=xianshi0;break;
case 1 : xianshi=xianshi1;break;
case 2 : xianshi=xianshi2;break;
case 3 : xianshi=xianshi3;break;
case 4 : xianshi=xianshi4;break;
case 5 : xianshi=xianshi5;break;
}
while( key == 0) //防止按一次键读取多个值
delay(10);
}
}
}
void timer0 () interrupt 1
{
key_scan();
}
void main()
{
TMOD = 0x01;
TH0 = 0x3c;
TL0 = 0xb0;
EA = 1;
ET0 = 1;
TR0 = 1;
while(1)
{
xianshi();
}
}
|