bouton-led.ino

Teensy 4.1 · Fichier : bouton-led.ino · Langage : Arduino · Usage : Compteur d'appuis bouton avec anti-rebond matériel

Le bouton est lu par interruption externe : aucun appui perdu même si loop() est occupée. Un filtre de 30 ms dans l'ISR supprime les rebonds, et la section noInterrupts garantit une lecture cohérente du compteur.

Matériel requis

Un Teensy 4.1 (NXP i.MX RT1062, Cortex-M7 @ 600 MHz, logique 3,3 V, Ethernet et stockage flash additionnel) alimenté par USB. 1 bouton poussoir vers GND.

Câblage

Bouton entre la broche 2 et GND (résistance interne activée par INPUT_PULLUP). Broches toutes interruptibles sur Teensy.

Fonctionnement

attachInterrupt() attache surFront descendant ; l'ISR incrémente un compteur volatile. loop() affiche le compteur et allume la LED pour chaque nombre impair.

Exécution

Teensyduino dans l'Arduino IDE, carte « Teensy 4.1 », Téléverser puis bouton du Teensy Loader. Broches 3,3 V ; le 4.1 ajoute Ethernet, USB host et broches supplémentaires.

Variantes

Ajouter un bouton « remise à zéro », ou envoyer le compteur en MIDI (Note On) pour un déclencheur de boîte à rythmes.

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);
}

← Retour à la fiche