如果我按两次按钮中断,我如何告诉 Arduino 中的代码?



我在Arduino中使用esp32。我想做的是: 如果我按下按钮一次,它应该 Serial.print "我被按下了一次" 如果我按两次按钮,它应该 Serial.print "我被按下了两次"

我正在使用 attachInterrupt() 函数,但当我按下按钮两次时,我不知道如何告诉代码如何读取它。 我的代码还做的是在感应到我按下按钮时打开 LED。

这是我迄今为止取得的成就:

int boton = 0; 
int led = 5;
int valorBoton; //value of the button, if it off(1) or on (0) 
unsigned int count = 0 ; //counter
void setup() {
Serial.begin(115200); //velocity
pinMode(led, OUTPUT); //OUTPUT LED
pinMode(boton, INPUT); //INFUPT BUTTON
digitalWrite(led, LOW); //THE LED IS LOW INITIALLY
attachInterrupt(digitalPinToInterrupt(0),button1,RISING);
}
void loop() {
count++; 
Serial.println(count); //printing the counter
delay(1000);
}
void button1(){ //the function button1 is a parameter of attachInterrupt
digitalWrite(led, HIGH); //when it is pressed, led is on 
Serial.println("I was pressed");
count = 0; // if I was pressed, then the count starts from cero all over again 
}

我希望在按下按钮时打印Serial.println("我被按下了两次")

它可以通过多种方式实现。一种方法是创建一个中断函数来增加一个计数器,然后在循环函数中检查用户是否按下了该函数两次(通过计算两次按下之间的延迟),然后决定它是一次还是两次按下。

请记住更改max_delay两次按之间的最大等待时间。

// maximum allowed delay between two presses
const int max_delay = 500;
int counter = 0;
bool done = false;
const byte ledPin = 13;
const byte buttonPin = 0;
unsigned long first_pressed_millis = 0;
void counter_incr()
{
counter++;
}
void setup()
{
Serial.begin(115200);
pinMode(ledPin, OUTPUT);          //OUTPUT LED
pinMode(buttonPin, INPUT_PULLUP); //INPUT BUTTON as pullup
digitalWrite(ledPin, LOW);        //THE LED IS LOW INITIALLY
attachInterrupt(digitalPinToInterrupt(buttonPin), counter_incr, RISING);
}
void loop()
{
if (counter > 0)
{
first_pressed_millis = millis();
// wait for user to press the button again
while (millis() - first_pressed_millis < max_delay)
{
// if button pressed again
if (counter > 1)
{
Serial.println("Button pressed twice!");
done = true;
break;
}
}
// if on timeout no button pressed it means the button pressed only one time
if (!done)
Serial.println("Button pressed once!");
counter = 0;
}
}

最新更新