🛠 Registres AVR et interruption timer

Arduino Nano (Classic, ATmega328P) · avance · Schéma : IMG-nano-classic-avance-7-nanoc-registres-timer.svg — Arduino Nano, LED sur broche 13, timer1 du ATmega328P en mode CTC déclenché par interruption, chronogramme OCR1A

Objectives

Move beyond Arduino abstractions by programming the ATmega328P registers directly: configure timer1 in CTC mode (Clear Timer on Compare Match) to generate a precise periodic interrupt, without relying on delay or millis. The ISR only toggles the built-in LED — the classic "short ISR" discipline for AVR.

Hardware

Complete Code

// Timer1 en CTC : interruption ~1 Hz, ISR bascule la LED 13
// 16 MHz / (1024 * 15625) = 1 Hz environ
#include <avr/io.h>
#include <avr/interrupt.h>

ISR(TIMER1_COMPA_vect) {     // appelee a chaque compare match
  PINB |= _BV(PB5);          // bascule directe de la broche 13 (PB5)
}

void setup {
  DDRB |= _BV(DDB5);         // PB5 (broche 13) en sortie
  noInterrupts;
  TCCR1A = 0;                // mode normal d'abord
  TCCR1B = _BV(WGM12);       // CTC sur OCR1A
  TCNT1  = 0;
  OCR1A  = 15624;            // 16e6/1024/15625 = 1 Hz
  TCCR1B |= _BV(CS12) | _BV(CS10);  // prescaler 1024 : demarre
  TIMSK1 |= _BV(OCIE1A);     // autorise l'IT compare match A
  interrupts;
}

void loop {
  // Le coeur tourne sans delay : tout est dans l'ISR
}

Expected Verification

The built-in LED toggles exactly once per second, with crystal-stable regularity (the 16 MHz crystal is far more stable than the drifts of nested delay calls). The code occupies a few hundred bytes of flash. By disabling interrupts (cli), the LED freezes immediately — proof that only the timer is working.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials