🛠 Apprivoiser les registres modernes de l'ATmega4809 : le timer TCB
Objectives
Leave the Arduino API behind and access registers directly: the ATmega4809 does NOT have the old T0/T1/T2 timers found on the 328P, but rather modern TCA and TCB peripherals. Here we configure a TCB (16-bit, periodic interrupt mode) that toggles LED 13 at 0.5 Hz without using delay or millis, by manipulating TCB0.CTRLA, TCB0.CCMP, TCB0.INTCTRL, and the INTFLAGS flag.
Hardware
- 1 × Arduino Nano Every
- Micro-USB cable
- Optional: logic analyzer on pin 13 to measure the period
Complete Code
// TCB0 en interruption periodique : toggle LED 13 sans delay
// Horloge noyau 20 MHz, diviseur /256 -> 78125 Hz
// CCMP = 78124 -> debordement 1 Hz -> LED basculee a 0,5 Hz
ISR(TCB0_OVF_vect) {
TCB0.INTFLAGS = TCB_CAPT_bm; // acquitter l'interruption
digitalToggle(LED_BUILTIN); // 13
}
void setup {
pinMode(LED_BUILTIN, OUTPUT);
TCB0.CTRLB = TCB_CNTMODE_INT_gc; // periode simple
TCB0.CCMP = 78124; // 78125 / (78124+1) = 1 Hz
TCB0.INTCTRL = TCB_CAPT_bm; // irq sur comparaison
TCB0.CTRLA = TCB_CLKSEL_CLKDIV256_gc | TCB_ENABLE_bm;
sei; // autoriser les irq
}
void loop {
// Le CPU ne fait rien : c'est le peripherique qui travaille.
}
Expected Verification
LED 13 blinks at 0.5 Hz (one toggle per second) while loop is empty. Remove the INTFLAGS acknowledgment: the LED stays lit (the interrupt re-triggers in a loop) — a pedagogical experiment on flags. Compare with tutorial 1: here the counting is done by hardware, and the application code remains 100% available.
Common Errors
- Looking for
TCCR1B,OCR1A,TIMSK1: these registers do not exist on the 4809; the AVRex family uses TCA0/TCA1, TCB0 to TCB3, etc. Read the pinout diagram and thepins_arduino.hfile of thenona4809variant. - Forgetting to acknowledge
INTFLAGSin the ISR: permanent interrupt, the program seems frozen. - Wrong clock divider:
CLKSELoffers SYSCLK, /2, /16, /128, /256, or external clock — a CCMP calculated for /256 with /2 results in a frequency 128 times too high. - Writing to the registers of a TCB already requisitioned by the core for PWM (
analogWrite): check which timer serves which pin beforehand. seiforgotten: global interrupts remain masked, no ISR executes.
Other tutorials for this board
Code examples for this board
multi-serie.inoArduinoadc-filtre.inoArduinointerrupt-bouton.inoArduinonvm-consignes.inoArduinosommeil-every.inoArduinowatchdog-secours.inoArduino