bouton-led.ino

Teensy 4.0 · File : bouton-led.ino · Language : Arduino · Use case : Compteur d'appuis bouton avec anti-rebond matériel

The button is read through an external interrupt: no press is lost even when loop() is busy. A 30 ms filter inside the ISR removes bounce, and the noInterrupts section guarantees a coherent counter read.

Hardware

A Teensy 4.0 (NXP i.MX RT1062, Cortex-M7 @ 600 MHz, 3.3 V logic) powered over USB. 1 push button to GND.

Wiring

Button between pin 2 and GND (internal resistor enabled by INPUT_PULLUP). All pins are interrupt-capable on Teensy.

How it works

attachInterrupt() hooks the falling edge; the ISR increments a volatile counter. loop() prints the counter and lights the LED on odd counts.

Running it

With Teensyduino in the Arduino IDE, select « Teensy 4.0 », Upload then confirm in the Teensy Loader. Pins are 3.3 V; the 4.0 is pin-compatible with the 3.2.

Variants

Add a « reset » button, or send the count over MIDI (Note On) as a drum-machine trigger.

bouton-led.ino

// Compteur d'appuis : bouton sur interruption externe (EXTI).
const int BOUTON = 2; // broche interruptible (tout pin Teensy l'est)
const int LED = 13;

volatile unsigned long compteur = 0;
volatile unsigned long dernierFront = 0;

void surAppui() {
  unsigned long maintenant = millis();
  if (maintenant - dernierFront < 30) return; // anti-rebond 30 ms
  dernierFront = maintenant;
  compteur++;
}

void setup() {
  pinMode(BOUTON, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(BOUTON), surAppui, FALLING);
  Serial.begin(9600);
  Serial.println(F("Compteur d'appuis pret"));
}

void loop() {
  static unsigned long derniereAffichage = 0;
  if (millis() - derniereAffichage < 200) return;
  derniereAffichage = millis();

  noInterrupts();          // lecture atomique de la variable 32 bits
  unsigned long n = compteur;
  interrupts();

  digitalWrite(LED, (n % 2) ? HIGH : LOW);
  Serial.print(F("appuis = ")); Serial.println(n);
}

← Back to the board