bouton-led.ino

Teensy 3.2 · 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 3.2 (NXP Kinetis MK20DX256, Cortex-M4 @ 72 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

Install the Teensyduino plugin in the Arduino IDE, select the « Teensy 3.2 » board, click Upload then the Teensy Loader button. Note: 3.3 V pins.

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