🛠 Temps réel : timers matériels et interruptions sur le GIGA R1
Objectives
Move beyond the "delay everywhere" model to generate an audio signal at an exact rate. The GIGA R1's 480 MHz Cortex-M7 features hardware timers and interrupts; we will use a hardware ticker (mbed::Ticker, exposed by the Arduino Mbed core) to sample a waveform on the 12-bit DAC while loop remains available. You will also learn about interrupt precautions related to documented bugs (#789 regarding attachInterrupt).
Hardware
- 1 Arduino GIGA R1 WiFi board
- 1 pair of headphones or an amplifier connected to the onboard jack (DAC0)
- 1 logic analyzer or a simple LED on a pin to observe the rate (optional)
Complete Code
// GIGA R1 WiFi — ton precis genere par ticker materiel, loop reste libre
#include <Arduino.h>
#include "mbed.h"
const int DAC_PIN = DAC0; // jack audio embarque
mbed::Ticker ticker;
uint32_t phase = 0;
const uint32_t PAS = 32; // pas de phase -> frequence du ton
volatile uint32_t compteur = 0; // partage ISR <-> loop : volatile obligatoire
void echantillonner { // s'execute en contexte d'interruption
phase = (phase + PAS) & 0xFFF; // onde 12 bits
analogWrite(DAC_PIN, phase);
compteur++;
}
void setup {
Serial.begin(115200);
analogWriteResolution(12);
ticker.attach(echantillonner, 0.0001); // 10 kHz constants
}
void loop {
static uint32_t dernier = 0;
if (compteur - dernier >= 10000) { // ~1 s d'echantillons a 10 kHz
dernier = compteur;
Serial.print("echantillons 10 kHz : ");
Serial.println(compteur);
// loop peut faire autre chose : capteurs, reseau, I2C...
}
}
Expected Verification
A continuous and stable sound comes out of the jack, without crackling even if loop performs long processing tasks. The Serial Monitor displays a counter that increases by exactly 10,000 per second, proving that the rate is maintained by the hardware timer and not by loop.
Common Errors
- Forgetting
volatileon a variable shared between the ISR and loop: the compiler optimizes it away, and the loop never sees the updates. - Blocking calls (Serial.print, delay) inside the interrupt routine: causes blocking and crashes; the ISR must remain as short as possible.
attachInterrupton poorly supported pins or modes: crashes have been documented (bug #789, closed); prefer mbed tickers when possible and update the core.- Confusion between hardware ticker / software Ticker (millis): only the hardware ticker guarantees the rate under load.
- ISR frequency too high with the DAC: the M7 core is fast (480 MHz), but writing analogWrite in the ISR has a cost; measure before increasing it.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton.inoArduinorespiration.inoArduinoanalogique.inoArduinodac-onde.inoArduinooled-i2c.inoArduino