flowchart LR A["Press"] --> B["Contacts toggle<br/>ON/OFF for a few ms"] --> C["Stable ON"]
5.1 Polling vs. interrupts
There are two ways to know the state of a button.
| Method | Mechanism | Drawback |
|---|---|---|
| Polling | Repeatedly read digitalRead() in loop() |
Misses presses that happen while you are not reading. The CPU cannot rest |
| Interrupt | The hardware detects the pin change and calls an interrupt handler (ISR) | There are restrictions on what you can do inside an ISR |
On the nRF52840, a peripheral called GPIOTE (GPIO Tasks and Events) detects pin changes and raises interrupts. Arduino’s attachInterrupt() configures it.
5.2 Implementation
#ifndef DRV_BUTTON_H
#define DRV_BUTTON_H
#include <Arduino.h>
#define BUTTON_PIN 8 // connect a tactile switch between D8 and GND
#define BUTTON_DEBOUNCE_MS 30 // time regarded as bounce
#define BUTTON_LONG_PRESS_MS 1000
void button_init();
#endif // DRV_BUTTON_H#include "drv_button.h"
#include "app_event.h"
// variables touched from both the interrupt and the main code get volatile
static volatile uint32_t s_pressed_at = 0; // time pressed
static volatile uint32_t s_last_edge_at = 0; // time the last edge was accepted
static volatile bool s_is_pressed = false;
// Interrupt handler (ISR): finish quickly. No heavy processing, Serial or delay
static void button_isr()
{
uint32_t now = millis();
if (now - s_last_edge_at < BUTTON_DEBOUNCE_MS)
return; // bounce: ignore if not enough time has passed since the previous edge
s_last_edge_at = now;
bool level_low = (digitalRead(BUTTON_PIN) == LOW); // pulled up, so LOW when pressed
if (level_low && !s_is_pressed)
{
s_is_pressed = true;
s_pressed_at = now;
}
else if (!level_low && s_is_pressed)
{
s_is_pressed = false;
uint32_t held = now - s_pressed_at;
event_post(held >= BUTTON_LONG_PRESS_MS ? EVT_BUTTON_LONG : EVT_BUTTON_SHORT);
}
}
void button_init()
{
pinMode(BUTTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), button_isr, CHANGE);
}5.2.1 Catching both press and release with CHANGE
With attachInterrupt(..., CHANGE), the ISR is called both when pressed (HIGH → LOW) and when released (LOW → HIGH).
- On press: record the time
- On release: decide short press / long press from how long it was held, and post an event
5.2.2 Contact bounce
At the moment a mechanical switch is pressed or released, its contacts rapidly toggle ON/OFF for a few ms to over ten ms (chatter, bounce). If you do nothing, the ISR is called many times for a single press and multiple short-press events occur.
This sample takes the simple approach of ignoring edges within 30 ms of the last accepted edge. You can also add an RC filter in hardware.
5.2.3 Rules to follow in an ISR
| Don’t | Reason |
|---|---|
delay(), long loops |
During the ISR, other interrupts and all tasks stop. BLE communication timing is disturbed too |
Serial.print() |
Internally it waits and manipulates buffers. Calling it from an ISR can hang |
| I²C / SPI communication (reading sensors) | Communication takes time, and the library may itself use interrupts |
| Normal FreeRTOS APIs | From an ISR use only the ...FromISR versions (event_post() chooses between them) |
The principle is: in the ISR, only post “what happened” as an event, and do the processing in the main loop’s handlers.
5.2.4 volatile
static volatile uint32_t s_pressed_at = 0;Variables that are read and written by both the ISR and the main processing get volatile. Without it, the compiler may assume “this variable does not change midway” and optimize by continuing to use an old value kept in a register.
volatile only guarantees “read/write from memory every time”; it does not guarantee consistency across several variables together (that the ISR does not overwrite them while you are reading). When you want to pass several values, it is safe to copy them into the event payload and pass them through the queue, as this sample does.
5.3 Deferred interrupt execution (ISR_DEFERRED)
The Adafruit nRF52 core’s attachInterrupt() has a flag called ISR_DEFERRED.
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), button_isr, CHANGE | ISR_DEFERRED);With it, the callback is called not inside the ISR but later, from within a task. You no longer need to worry about ISR restrictions, but there is a delay before it is called. This sample does not use it because the work done in the ISR is short.
5.4 Exercises
- Set
BUTTON_DEBOUNCE_MSto 0 and try a few short presses. In the serial monitor, can you see measurement starting and stopping several times for a single press? (Depending on the switch you may not see it) - In the current implementation, a long press is decided on release. Think about how to emit the long-press event at the moment the button has been held for 1 second
At the moment of pressing, start a one-shot timer (called just once, 1 second later), and
- when the timer expires, if the button is still pressed, post
EVT_BUTTON_LONG(set a “long press confirmed” flag) - on release, if the “long press confirmed” flag is not set, post
EVT_BUTTON_SHORTand stop the timer
A FreeRTOS software timer can be made one-shot with SoftwareTimer::begin(ms, cb, nullptr, false) (last argument false = do not repeat). However, to start a timer from an ISR you must use xTimerStartFromISR().