interrupt-bouton.ino

Arduino Nano Every · File : interrupt-bouton.ino · Language : Arduino · Use case : Réagir à un bouton par interruption, sans polling

On the 4809, external interrupts escape the 328P INT0/INT1 cage: digitalPinToInterrupt works on most pins. This button toggles the LED without ever polling its state, leaving the main loop fully available.

Hardware

An Arduino Nano Every (ATmega4809 at 20 MHz, same footprint as the Nano, micro-B USB, separate UART chip, 5 V pins, drop-in compatibility with the classic Nano). Nano Every, push button on pin 2, LED on 13 (or LED_BUILTIN).

Wiring

Button between D2 and GND (internal pull-up enabled); LED via 330 Ω resistor to D13.

How it works

The ISR only raises a volatile flag with a 50 ms debounce guard; heavy processing stays in loop(), the golden rule of short interrupts.

Running it

Install the Arduino megaAVR Boards package in the IDE, select Arduino Nano Every, upload. The USB Serial is separate from hardware Serial1 (RX/TX pins): classic serial code works as is.

Variants

Use CHANGE to count both edges of a simple encoder, or wake the board from deep sleep with the same mechanism.

interrupt-bouton.ino

// Interruptions externes sur le Nano Every : n'importe quelle broche
// peut generer une interruption (le 4809 n'a pas que INT0/INT1).
volatile bool appui = false;
unsigned long dernierAppui = 0;
bool etatLed = false;

const int BOUTON = 2;
const int LED = 13;

void surChangement() {
  unsigned long m = millis();
  if (m - dernierAppui > 50) { // anti-rebond 50 ms
    appui = true;
    dernierAppui = m;
  }
}

void setup() {
  pinMode(BOUTON, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  // RISING ou FALLING ou CHANGE : ici chaque flanc compte
  attachInterrupt(digitalPinToInterrupt(BOUTON), surChangement, FALLING);
  Serial.begin(9600);
}

void loop() {
  if (appui) {
    appui = false;
    etatLed = !etatLed;
    digitalWrite(LED, etatLed);
    Serial.println(etatLed ? F("LED ON") : F("LED OFF"));
  }
  // la boucle reste libre pour l'I2C, l'UART, les mesures...
  delayMicroseconds(100);
}

← Back to the board