// For: https://forum.arduino.cc/t/push-button-long-vs-short-press/995531/
//
// Checking used pins at: https://randomnerdtutorials.com/esp32-pinout-reference-gpios/
// Pin number 12 should not be high at startup.
// That means a extra external pullup is not allowed and the button might need one.
// Pin 13 and 33 are okay to use.
//
// The button is default HIGH, but lastState is initialized as LOW.
// The if-statements are missing '{' and '}'
//
#define BUTTON_PIN 12 // ESP32 GIOP12 pin connected to button's pin
#define BUZZER_PIN 13 // ESP32 GIOP13 pin connected to buzzer's pin
#define MOTOR_PIN 33 // ESP32 GPIO33 pin connected to vibrator motor pin
// The ESP32 has 16 channels which can generate 16 independent waveforms
// We'll just choose PWM channel 0 here
const int TONE_PWM_CHANNEL = 0;
#define SHORT_PRESS_TIME 500 // 500 milliseconds
#define LONG_PRESS_TIME 3000 // 3000 milliseconds
// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP); // set ESP32 pin to input pull-up mode
pinMode(MOTOR_PIN, OUTPUT);
ledcAttachPin(BUZZER_PIN, TONE_PWM_CHANNEL);
}
void loop() {
// read the state of the switch/button:
int currentState = digitalRead(BUTTON_PIN);
if (lastState == HIGH && currentState == LOW) // button is pressed
pressedTime = millis();
else if (lastState == LOW && currentState == HIGH) { // button is released
releasedTime = millis();
long pressDuration = releasedTime - pressedTime;
if ( pressDuration < SHORT_PRESS_TIME )
ledcWrite(0, 0);
digitalWrite(MOTOR_PIN, LOW);
Serial.println("A short press is detected DO NOT SEND NOTIFICATIONS");
if ( pressDuration > LONG_PRESS_TIME )
Serial.println("A long press is detected");
ledcWriteNote(TONE_PWM_CHANNEL, NOTE_C, 4);
digitalWrite(MOTOR_PIN, HIGH);
delay(500);
}
// save the the last state
lastState = currentState;
}