// Arduino Timer 1 CTC Mode Example
// Initialize Timer 1 for CTC mode
void timer1CTC_Init(int max_count, int my_div) {
TCCR1A = 0; // Clear all bits in TCCR1A
TCCR1B = 0; // Clear all bits in TCCR1B
OCR1A = max_count - 1; // Set the compare match register value
TCNT1 = 0; // Reset the counter
TIFR1 = 0x7; // Clear all interrupt flags
TIMSK1 = (1 << OCIE1A); // Enable Timer 1 compare match A interrupt
// Set CTC mode (WGM12 = 1)
TCCR1B |= (1 << WGM12);
// Set prescaler
switch (my_div) {
case 1:
TCCR1B |= (1 << CS10);
break;
case 8:
TCCR1B |= (1 << CS11);
break;
case 64:
TCCR1B |= (1 << CS11) | (1 << CS10);
break;
case 256:
TCCR1B |= (1 << CS12);
break;
case 1024:
TCCR1B |= (1 << CS12) | (1 << CS10);
break;
}
}
void setup() {
// Set PB5 (Pin 13 on Arduino Uno) as output
pinMode(13, OUTPUT);
// Initialize Timer 1 with a frequency of 2 Hz
// 31250 is the value for OCR1A to achieve 2 Hz with prescaler 256
timer1CTC_Init(31250, 256);
}
void loop() {
// The main loop does nothing, the interrupt handles the LED toggling
}
// Timer 1 Compare Match A interrupt service routine
ISR(TIMER1_COMPA_vect) {
PORTB ^= (1 << PORTB5); // Toggle the LED connected to PB5 (Pin 13 on Arduino Uno)
}