// Arduino clock frequency is 16 MHz
#include <avr/io.h>
#include <avr/interrupt.h>
unsigned int n_compare_matchs = 0;
ISR(TIMER2_COMPA_vect)
{
// TASK: Use n_compare_matchs to toggle D12 on each timer interrupt
// and Toggle D13 at 1 sec interval.
// Toggle D12 (PB4) on each interrupt
PORTB ^= (1 << PB4);
// Increment the compare match counter
n_compare_matchs++;
// Toggle D13 (PB5) after 125 interrupts
if (n_compare_matchs >= 125)
{
PORTB ^= (1 << PB5); // Toggle D13
n_compare_matchs = 0; // Reset the counter
}
}
int main()
{
// TASK: set the prescaler for Timer2 to 1024
TCCR2B = (1 << CS22) | (1 << CS21) | (1 << CS20); // Prescaler 1024
// TASK: set Wave Generation mode to CTC (Clear Timer on Compare Match)
TCCR2A = (1 << WGM21);
// TASK: Set upper limit for CTC with OCR2A (remember: ticks start from 0)
OCR2A = 124; // Compare match value for 125 counts
// TASK: Enable Timer2 interrupt on compare match
TIMSK2 = (1 << OCIE2A);
// TASK: Set pin modes for D13 and D12
DDRB |= (1 << PB5) | (1 << PB4); // Set PB5 (D13) and PB4 (D12) as outputs
// TASK: Enable Interrupts
sei(); // Enable global interrupts
// Infinite loop
while (1)
;
}