🛠 Registres AVR et interruption timer
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
- 1 × Classic Arduino Nano (ATmega328P @ 16 MHz, ceramic resonator)
- The built-in LED (pin 13); an oscilloscope or logic analyzer is a plus for measuring the period
- No external connections required
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
- ISR too long: calling Serial.print or delay inside an ISR blocks other interrupts and corrupts millis; the ISR must remain minimal.
- Forgetting the WGM12 bit (CTC mode) or CS12|CS10 (prescaler): the timer never starts, and no toggling is observable.
- Modifying a variable shared between ISR/loop without volatile or a critical section: the compiler optimizes the read, and loop never sees the change.
- Confusing PB5 and pin 13: the physical mapping is specific to the Arduino bootloader on the 328P; check the pinout sheet for the TQFP/MLF package.
- >
Other tutorials for this board
Code examples for this board
buzzer-melodie.inoArduinoservo-sweep.inoArduinoultrason-hcsr04.inoArduinolcd-i2c.inoArduinoeeprom-contre.inoArduinosommeil-watchdog.inoArduino