#include <avr/io.h>
#include <avr/interrupt.h>
#define LED_PIN PB4 // Pin 12 on Arduino Uno corresponds to PB5 on ATmega328P
void setupTimer1() {
// Set Timer1 in CTC (Clear Timer on Compare Match) mode
TCCR1A = 0; // Normal port operation, CTC mode
TCCR1B = (1 << WGM12); // CTC mode with OCR1A as top
// Set compare match value for 1 Hz blink
// Formula: OCR1A = (F_CPU / (Prescaler * DesiredFrequency)) - 1
// For 16 MHz, prescaler = 256, DesiredFrequency = 1 Hz:
// OCR1A = (16,000,000 / (256 * 1)) - 1 = 62449
OCR1A = 62499;
// Set prescaler to 256
TCCR1B |= (1 << CS12);
// Enable Timer1 Compare Match A interrupt
TIMSK1 = (1 << OCIE1A);
}
int main(void) {
// Configure LED_PIN as output
DDRB |= (1 << LED_PIN);
// Initialize Timer1
setupTimer1();
// Enable global interrupts
sei();
// Main loop does nothing; the ISR handles the LED toggling
while (1) {
// Idle loop
}
}
// Timer1 Compare Match A interrupt service routine
ISR(TIMER1_COMPA_vect) {
// Toggle LED_PIN
PORTB ^= (1 << LED_PIN);
}
// Assignment:
// 1. Change the delay to 300ms
// 2. Control a Green LED using SW in while(1)
// 3. Control Green LED with Switch connected at INT0 interrupt