C51轮询多个独立按键
注:
P3 [3:0] 分别对应 4个独立按键
P2 [7:0] 分别对应 8个流水灯
#include "reg52.h"
#define LEN 9
unsigned int Dly, i;
unsigned char step = 0;
unsigned char mod = 0;
unsigned char spd = 0;
unsigned char F_LED[3][LEN] = { //通过更改数组来更改流水灯样式
{0x01,0x02,0x04,0x08,0x10,0x10,0x20,0x40,0x80},
{0x18,0x24,0x42,0x81,0x00,0x81,0x42,0x24,0x18},
{0xA5,0x5A,0xA5,0x5A,0xA5,0x5A,0xA5,0x5A,0xA5}
};
void delay(unsigned char i){
while(i--);
}
void key_check(void){
if(P3==0x0F) delay(1000);
else {
delay(1000);
return;
}
P3 &= 0x0F;
if(!(P3&0x01)){ //press k2
mod = mod+2; //mod = 3 + mod-1
mod %= 3;
}
else if(!(P3&0x02)){ //press k1
mod++;
mod %= 3;
}
else if(!(P3&0x04)){ //press k3
spd += 0x40;
}
else if(!(P3&0x08)){ //press k4 func: reset
step = 0;
mod = 0;
spd = 0;
}
return;
}
void main()
{
P3 = 0x0F; //由单片机要求,写 ‘1’ 以正确读取管脚输入信号
while(1){
Dly = 250 + 2*spd;
for(i = 0; i < Dly; i++){ //delay
key_check();
//delay(1)
P2=F_LED[mod][step];
}
step++;
step %= LEN;
P2=F_LED[mod][step];
}
}