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;
};

程序源码

链接:https://pan.baidu.com/s/1aLcoJyXVrSYCXHQcTH18OQ 
提取码:neli

枫桥夜泊 唐朝·张继
  月落乌啼霜满天,江枫渔火对愁眠。
  姑苏城外寒山寺,夜半钟声到客船。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值