今天写了一个流水灯程序,刚开始思路还不错,这个程序写成功了。当我再回头来想改进的时候,在主函数中添加了一个变量来接收函数的返回值的时候,编译没有问题,一切都变了:流水灯不再按照预先那样工作了,而且当你按键的时候,灯在不停的闪烁。(除主函数外,其余都一样)希望有人能伸出友爱之手,把我从疑惑的边缘解救,无以为报,谢谢!!!
错误问题程序
#include <reg51.h>
#include <intrins.h>
void delay(unsigned char ms);
void process(unsigned char key_cess);
unsigned char key_scan();
sbit K1=P0^0;
sbit K2=P0^1;
main()
{
unsigned char key_cess,K3,key_s;
P2=0xfe;
K3=0x03;
while(1)
{
key_s=key_scan();
if(K3!=key_s)
{
delay(10);
key_s=key_scan();
if(key_s!=K3)
{
key_cess=key_s;
process(key_cess);
}
}
}
}
unsigned char key_scan()
{
unsigned char key_s;
key_s=0x00;
key_s |=K2;
key_s <<=1;
key_s |=K1;
return key_s;
}
void process(unsigned char key_cess)
{
if((key_cess & 0x01) == 0)
{
P2 = _cror_(P2,1);
}
else if((key_cess & 0x02) == 0)
{
P2 = _crol_(P2, 1);
}
}
void delay(unsigned char ms)
{
unsigned char i;
while(ms--)
{
for(i = 0; i < 120; i++);
}
}
正确程序:
#include <reg51.h>
#include <intrins.h>
void delay(unsigned char ms);
void process(unsigned char key_cess);
unsigned char key_scan();
sbit K1=P0^0;
sbit K2=P0^1;
main()
{
unsigned char key_cess,key_s;
P2=0xfe;
key_cess=0x03;
while(1)
{
key_s=key_scan();
if(key_cess!=key_s)
{
delay(10);
key_s=key_scan();
if(key_s!=key_cess)
{
key_cess=key_s;
process(key_cess);
}
}
}
}
unsigned char key_scan()
{
unsigned char key_s;
key_s=0x00;
key_s |=K2;
key_s <<=1;
key_s |=K1;
return key_s;
}
void process(unsigned char key_cess)
{
if((key_cess & 0x01) == 0)
{
P2 = _cror_(P2,1);
}
else if((key_cess & 0x02) == 0)
{
P2 = _crol_(P2, 1);
}
}
void delay(unsigned char ms)
{
unsigned char i;
while(ms--)
{
for(i = 0; i < 120; i++);
}
} |