static const int buttonPin = 4; // switch pin
int buttonStatePrevious = HIGH; // previousstate of the switch
unsigned long minButtonLongPressDuration = 500; // Time we wait before we see the press as a long press
unsigned long buttonLongPressMillis; // Time in ms when we the button was pressed
bool buttonStateLongPress = false; // True if it is a long press
const int intervalButton = 50; // Time between two readings of the button state
unsigned long previousButtonMillis; // Timestamp of the latest reading
unsigned long buttonPressDuration; // Time the button is pressed in ms
//// GENERAL ////
unsigned long currentMillis; // Variabele to store the number of milleseconds since the Arduino has started
void setup() {
Serial.begin(9600); // Initialise the serial monitor
pinMode(buttonPin, INPUT_PULLUP); // set buttonPin as input
Serial.println("Press button");
}
// Function for reading the button state
void readButtonState(int btn) {
// If the difference in time between the previous reading is larger than intervalButton
if(currentMillis - previousButtonMillis > intervalButton) {
// Read the digital value of the button (LOW/HIGH)
int buttonState = btn;
// If the button has been pushed AND
// If the button wasn't pressed before AND
// IF there was not already a measurement running to determine how long the button has been pressed
if (buttonState == LOW && buttonStatePrevious == HIGH && !buttonStateLongPress) {
buttonLongPressMillis = currentMillis;
buttonStatePrevious = LOW;
Serial.println("Button pressed");
}
// Calculate how long the button has been pressed
buttonPressDuration = currentMillis - buttonLongPressMillis;
// If the button is pressed AND
// If there is no measurement running to determine how long the button is pressed AND
// If the time the button has been pressed is larger or equal to the time needed for a long press
if (buttonState == LOW && !buttonStateLongPress && buttonPressDuration >= minButtonLongPressDuration) {
buttonStateLongPress = true;
Serial.println("Button long pressed");
}
// If the button is released AND
// If the button was pressed before
if (buttonState == HIGH && buttonStatePrevious == LOW) {
buttonStatePrevious = HIGH;
buttonStateLongPress = false;
Serial.println("Button released");
// If there is no measurement running to determine how long the button was pressed AND
// If the time the button has been pressed is smaller than the minimal time needed for a long press
// Note: The video shows:
// if (!buttonStateLongPress && buttonPressDuration < minButtonLongPressDuration) {
// since buttonStateLongPress is set to FALSE on line 75, !buttonStateLongPress is always TRUE
// and can be removed.
if (buttonPressDuration < minButtonLongPressDuration) {
Serial.println("Button pressed shortly");
}
}
// store the current timestamp in previousButtonMillis
previousButtonMillis = currentMillis;
}
}
void loop() {
currentMillis = millis(); // store the current time
readButtonState(digitalRead(buttonPin)); // read the button state
}