// Arduino clock frequency is 16 MHz
// Debayan Sutradhar
#include <avr/io.h>
#include <avr/interrupt.h>
unsigned volatile 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.
if (n_compare_matchs >= 124) {
n_compare_matchs = 0;
// One second done
// Toggle PB5 (D13)
PORTB ^= (0b00100000);
} else {
n_compare_matchs++;
}
// Toggle PB4 (D12)
PORTB ^= (0b00010000);
}
// Datasheet used:
// https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
int main()
{
// TASK: set the prescaler for Timer2 to 1024
// We need to set TCCR2B bit 0,1,2 (CS20, CS21, CS22) as 1 to set prescaler to 1024
// Source: Page 131
TCCR2B |= (0b00000111);
// TASK: set Wave Generation mode to CTC(clear Timer on Compare match)
// Source: Page 127, 130
// We need to set:
// TCCR2A Bit 0 (WGM20) as 0
TCCR2A &= ~(0b00000001);
// TCCR2A Bit 1 (WGM21) as 1
TCCR2A |= (0b00000010);
// TCCR2B Bit 3 (WGM22) as 0
TCCR2B &= ~(0b00001000);
// TASK: Set upper limit for CTC with OCR2A (remember: ticks start form 0)
// Set to 124 (0 - 124 = 125 ticks)
OCR2A = 124;
// TASK: Enable Timer2 interrupt on compare match
// Source: Page 132
// Set TIMSK2 Bit 1 (OCIE2A) to 1
TIMSK2 |= (0b00000010);
// TASK: Set pin modes for D13 and D12
// Source: Page 66, 72
// Mark Bit 4 and 5 (PB4, PB5) as high on DDRB
DDRB |= (0b00110000);
// TASK: Enable Interrupts
// Source: Page 11, 16
// Mark Bit 7 of SREG as 1 to enable global interrupts
// We need to use SEI/CLI to set/clear
// Direct register manipulation is not allowed
sei();
while (1);
}