介绍及代码
一共9个按键9盏灯。
按第一个按键亮一盏灯
按第二个按键亮两盏灯
按第三个按键亮三盏灯
按第四个按键亮四盏灯
依次类推。
例程代码
//#define io_11
//#define io_12
#define button_delay 5 //单按钮消除抖动延时
#define button_every_delay 50 //多按钮操作间隔
//io高低点吧状态标志位,0代表低电平,1代表高电平
bool io_flag[18]={0,0,0,0,0,0,0,0,0,0,0,0,0};
//按钮变化标志位,0代表无变化,1代表有变化
bool button_flag[18]={0,0,0,0,0,0,0,0,0,0,0,0,0};
int i;
void print_s(){
for(int j=11;j<=9+i;j++)
{
digitalWrite(j,HIGH);
}
for(int j=10+i;j<=19;j++)
{
digitalWrite(j,LOW);
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
for(i=2;i<=10;i++)
pinMode(i,INPUT);
for(i=11;i<=19;i++)
{
pinMode(i,OUTPUT);
digitalWrite(i,LOW);
}
Serial.println("Init succ");
}
void loop() {
// put your main code here, to run repeatedly:
for(i=2;i<=10;i++)
{
if(digitalRead(i)==HIGH)
{
delay(button_delay);
if(digitalRead(i)==HIGH)
{
if(io_flag[i]==0)
{
io_flag[i]=1;
print_s(); //按钮按下,打印消息
delay(button_every_delay);
}
}
}
if(digitalRead(i)==LOW)
{
delay(button_delay);
if(digitalRead(i)==LOW)
{
if(io_flag[i]==1)
{
io_flag[i]=0;
//print_s(); //按钮松开,打印消息
delay(button_every_delay);
}
}
}
}
}
扩展
我们上面的例程里,每个按键对应的IO口都要接下拉电阻,其实arduino的IO口内部是有电阻的,我们可以通过程序将其配置为上拉电阻,这样我们的按键就不需要额外增加上拉电阻了,只需要接按键即可。
我用esp32开发板做实验,只需如此这般
pinMode(2,INPUT_PULLUP);
例程1
void setup() {
Serial.begin(9600);
pinMode(2,INPUT_PULLUP);
}
void loop() {
Serial.println(digitalRead(2));
delay(500);
}
例程2
void setup() {
Serial.begin(115200);
pinMode(36,INPUT_PULLUP);
pinMode(39,INPUT_PULLUP);
pinMode(34,INPUT_PULLUP);
pinMode(35,INPUT_PULLUP);
}
void loop() {
Serial.print("36:");
Serial.print(digitalRead(36));
Serial.print(" ");
Serial.print("39:");
Serial.print(digitalRead(39));
Serial.print(" ");
Serial.print("34:");
Serial.print(digitalRead(34));
Serial.print(" ");
Serial.print("356:");
Serial.println(digitalRead(35));
delay(500);
}