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

时间:2019-06-22 03:53:00

标签: arduino interrupt arduino-esp8266

我在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(“我被按下过两次”)

1 个答案:

答案 0 :(得分:2)

它可以通过多种方式实现。一种方法是为您的中断函数创建一个函数,以增加一个简单的计数器。然后在循环功能中,检查用户是否按过两次功能(通过计算两次按压之间的延迟),然后确定是一次按压还是两次按压。请记住在两次按下之间将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;
    }
}