#define TICK_RATE 1000
uint32_t volatile count = 0;
byte LedState = 0;
void startCounting()
{
// reset Timer 2
TCCR2A = 0;
TCCR2B = 0;
// Timer 2 - gives us our 1 ms counting interval
// 16 MHz clock (62.5 ns per tick) - prescaled by 128
// counter increments every 8 µs.
// So we count 125 of them, giving exactly 1000 µs (1 ms)
TCCR2A = bit(WGM21) ; // CTC mode
OCR2A = 125 - 1; // count up to 125 (zero relative !!!!)
// Timer 2 - interrupt on match (ie. every 1 ms)
TIMSK2 = bit(OCIE2A); // enable Timer2 Interrupt
TCNT2 = 0; // Counter to zero
// Reset prescalers
GTCCR = bit(PSRASY); // reset prescaler now
// start Timer 2
TCCR2B = bit(CS20) | bit(CS22) ; // prescaler of 128
} // Ready to roll !!!
//******************************************************************
// Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
// 16Mhz / 128 / 125 = 1000 Hz
ISR(TIMER2_COMPA_vect)
{
static uint16_t timerTicks = 0;
// see if we have reached timing period
if (++timerTicks >= TICK_RATE)
{
timerTicks = 0; // reset interrupt counter
LedState = !LedState; // inverser l'état (virtuel) de la LED
digitalWrite(LED_BUILTIN, LedState); // commuter la LED
interrupts();
Serial.println(count);
}
} // end of TIMER2_COMPA_vect
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT); // configurer la broche de la LED comme sortie
LedState = 0;
digitalWrite(LED_BUILTIN, LedState);
while (!Serial)
{
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Timer Interrupt LED Blink V2");
Serial.println("Type 'Pxxx' to set Period (ms) & 'Wxxx' to set Width (ms)");
Serial.println("Enjoy !!!");
startCounting();
} // end of setup
void loop() {
// put your main code here, to run repeatedly:
count++;
}