#define PRESSED 1 // 按下的标识
#define NOT_PRESSED 0 // 松开的标识
#define TOUCH_PIN 15 //监听的触摸引脚
const unsigned long SHORT_PRESS = 100; // 单机的时间间隔
const unsigned long LONG_PRESS = 3000; // 长按的时间间隔
/**
定义一个按钮的结构体
*/
typedef struct Buttons
{
unsigned long counter = 0; // 计时器
bool prevState = NOT_PRESSED; // 前一状态
bool currentState; // 当前状态
} Button;
// 该函数判断GPIO按下的状态
int getState()
{
// TOUCH_PIN 是某一个pin
// 具体的触摸pin 可以去这里看https://github.com/espressif/arduino-esp32#esp32dev-board-pinmap
if (touchRead(TOUCH_PIN) > 50)
{
return NOT_PRESSED;
}
else
{
return PRESSED;
}
}
Button button;
// touch中断函数
void gotTouch()
{
button.currentState = getState();
if (button.currentState != button.prevState)
{
if (button.currentState == PRESSED)
{
button.counter = millis();
}
else
{
unsigned long diff = millis() - button.counter;
if (diff >= SHORT_PRESS && diff < LONG_PRESS)
{
// 单机
Serial.println("pressed");
}
else if (diff >= LONG_PRESS)
{
// 长按
Serial.println("long pressed");
}
}
button.prevState = button.currentState;
}
}
void setup()
{
Serial.begin(115200);
// 初始化触摸中断
touchAttachInterrupt(TOUCH_PIN, gotTouch, 80);
}
void loop()
{
}
以上为Arduino IDE环境下的代码示例