Skip to content

Instantly share code, notes, and snippets.

@ryanamaral
Created February 21, 2024 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanamaral/63798f3070f03592e43fd83df216c1ef to your computer and use it in GitHub Desktop.
Save ryanamaral/63798f3070f03592e43fd83df216c1ef to your computer and use it in GitHub Desktop.
BOOTSEL Button Long Press Detection (Raspberry Pi Pico RP2040)
/*
* BOOTSEL Button Long Press Detection
*
* This Arduino sketch is based on the bootsel.ino example for the Raspberry Pi Pico RP2040.
* It detects both short and long presses on the BOOTSEL button and counts the number of each type of press.
*
* Hardware:
* - Raspberry Pi Pico RP2040
*
* Software Requirements:
* - Arduino IDE or compatible software
* - Pico SDK Arduino environment
*
* Instructions:
* 1. Upload the provided sketch to the Pico board using the Arduino IDE or compatible software.
* 2. Open the serial monitor to view the output messages.
* 3. Press the BOOTSEL button for short presses or hold it for long presses to observe the detection results.
*
* Sketch Description:
* - LONG_PRESS_DURATION: Duration in milliseconds for a press to be considered a long press.
* - pressCounter: Counter for short presses.
* - longPressCounter: Counter for long presses.
* - pressStartTime: Timestamp for press start time.
* - longPressDetected: Flag indicating a long press.
* - longPressHandled: Flag indicating if a long press has been handled.
*
* Output:
* - Short press: "You pressed BOOTSEL [pressCounter] times!"
* - Long press: "You held BOOTSEL for a long press [longPressCounter] times!"
*
* License:
* This sketch is released into the public domain.
*/
#include <Arduino.h>
#include "pico/stdlib.h"
#define LONG_PRESS_DURATION 1000 // Duration for a long press in milliseconds
int pressCounter = 0;
int longPressCounter = 0;
unsigned long pressStartTime = 0;
bool longPressDetected = false;
bool longPressHandled = false;
void setup() {
Serial.begin(115200);
delay(3000);
Serial.println("I dare you to long press the BOOTSEL button...");
}
void loop() {
if (BOOTSEL) {
pressStartTime = millis();
while (BOOTSEL) {
if ((millis() - pressStartTime) > LONG_PRESS_DURATION) {
longPressDetected = true;
break;
}
delay(1);
}
if (longPressDetected && !longPressHandled) {
Serial.printf("\a\aYou held BOOTSEL for a long press %d times!\n", ++longPressCounter);
longPressHandled = true;
} else if (!longPressDetected && !longPressHandled) {
Serial.printf("\a\aYou pressed BOOTSEL %d times!\n", ++pressCounter);
}
longPressDetected = false;
} else {
longPressHandled = false; // Reset the long press handled flag when the button is released
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment