#include <avr/io.h>
#include <avr/interrupt.h>
unsigned int n_compare_matchs = 0;
ISR(TIMER2_COMPA_vect) {
// Toggle D12 on every interrupt
PORTB ^= (1 << PB4); // Toggle D12 (pin 12 on the ATmega328P)
// Increment the counter
n_compare_matchs++;
// Toggle D13 every 125 interrupts (1 second)
if (n_compare_matchs >= 125) {
PORTB ^= (1 << PB5); // Toggle D13 (pin 13 on the ATmega328P)
n_compare_matchs = 0; // Reset the counter for the next second
}
}
int main() {
// Set prescaler for Timer2 to 1024
TCCR2B |= (1 << CS22) | (1 << CS21) | (1 << CS20); // Prescaler 1024
// Set Wave Generation mode to CTC (Clear Timer on Compare Match)
TCCR2A = 0; // Normal mode
TCCR2B |= (1 << WGM22); // Set CTC mode
// Set OCR2A value to 124 for a 125 Hz interrupt rate
OCR2A = 124; // Compare match value for interrupt every 125 cycles
// Enable Timer2 interrupt on compare match
TIMSK2 |= (1 << OCIE2A); // Enable compare match interrupt
// Set D12 and D13 as outputs (PB4 and PB5 for ATmega328P)
DDRB |= (1 << PB4) | (1 << PB5); // Set D12 (PB4) and D13 (PB5) as outputs
// Enable global interrupts
sei();
// Main loop does nothing, all work is done in ISR
while (1) {
}
return 0;
}