Arduino ESP32:测试GPIO中断功能二

Posted perseverance52

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Arduino ESP32:测试GPIO中断功能二相关的知识,希望对你有一定的参考价值。

Arduino ESP32:测试GPIO中断功能二


实例代码

/*
 测试功能中断
  接线说明: 按键1接16,按键2接17
*/

#include <Arduino.h>
#include <FunctionalInterrupt.h>

#define BUTTON1 16
#define BUTTON2 17

class Button{
public:
        Button(uint8_t reqPin) : PIN(reqPin){
                pinMode(PIN, INPUT_PULLUP);
                attachInterrupt(PIN, std::bind(&Button::isr,this), FALLING);//下降沿触发
        };
        ~Button() {
                detachInterrupt(PIN);
        }

        void IRAM_ATTR isr() {
                numberKeyPresses += 1;
                pressed = true;
        }

        void checkPressed() {
                if (pressed) {
                        Serial.printf("Button on pin %u has been pressed %u times\\n", PIN, numberKeyPresses);
                        pressed = false;
                }
        }

private:
        const uint8_t PIN;
    volatile uint32_t numberKeyPresses;
    volatile bool pressed;
};

Button button1(BUTTON1);
Button button2(BUTTON2);


void setup() {
    Serial.begin(115200);
}

void loop() {
        button1.checkPressed();
        button2.checkPressed();
}

将相关的按键中断函数分开写

  • 主程序:
/*
 测试功能中断
  接线说明: 按键1接16,按键2接17
*/

#include <Arduino.h>
#include <FunctionalInterrupt.h>
#include "Button.h"
#define BUTTON1 16
#define BUTTON2 17

Button button1(BUTTON1);
Button button2(BUTTON2);


void setup() {
    Serial.begin(115200);
}

void loop() {
        button1.checkPressed();
        button2.checkPressed();
}

  • Button.h文件
#include <FunctionalInterrupt.h>
class Button{
public:
        Button(uint8_t reqPin) : PIN(reqPin){
                pinMode(PIN, INPUT_PULLUP);
                attachInterrupt(PIN, std::bind(&Button::isr,this), FALLING);//下降沿触发
        };
        ~Button() {
                detachInterrupt(PIN);
        }

        void IRAM_ATTR isr() {
                numberKeyPresses += 1;
                pressed = true;
        }

        void checkPressed() {
                if (pressed) {
                        Serial.printf("Button on pin %u has been pressed %u times\\n", PIN, numberKeyPresses);
                        pressed = false;
                }
        }

private:
    const uint8_t PIN;
    volatile uint32_t numberKeyPresses;
    volatile bool pressed;
};

以上是关于Arduino ESP32:测试GPIO中断功能二的主要内容,如果未能解决你的问题,请参考以下文章

Arduino ESP32 WIFI &蓝牙模式触控按键切换

Arduino ESP32自带触摸传感器功能测试

IoTESP32 Arduino GPIO 使用简析

Arduino ESP32 看门狗定时器

Arduino ESP32 读写查看SD信息示例

Arduino ESP32 读取Micro sd卡容量信息示例