AVR Timer/Counter: Prof Prabhat Ranjan DA-IICT, Gandhinagar
AVR Timer/Counter: Prof Prabhat Ranjan DA-IICT, Gandhinagar
8-bit Timer/Counter0
with PWM
Frequency Generator
16-bit Timer/Counter
16-bit Timer/Counter
Frequency Generator
8-bit Timer/Counter2
Frequency Generator
Based on
Introduction
ATMega16@1 MHz
Simple Example
(Flash LED every 1/20 s)
int main (void) {
DDRB |= (1 << 0); // Set LED as output
TCCR1B |= (1 << CS10); // Set up timer
for (;;) {
// Check timer value in if statement, true when count matches 1/20 of a
second
if (TCNT1 >= 49999) { PORTB ^= (1 << 0); // Toggle the LED
TCNT1=0 : //Reset timer value
}
}
}
1uS
8uS
64
64uS
256
256uS
1024
1024uS
Value to count
1/20 s = 0.05 s
Pre-scaled Timer
| 999999
| 125000
64
| 15624
256
| 3905.25
1024
| 975.5625
Pseudo Code
WHILE forever
END IF
END WHILE
for (;;) {
if (TIFR & (1 << OCF1A))
Overflow
Compare
Capture
Pseudocode
Set up LED hardware
Set up timer in CTC mode
Enable CTC interrupt
Enable global interrupts
Set timer compare value to one second
WHILE forever
END WHILE
ISR Timer Compare
Toggle LED
END ISR
Setting Registers
DDRB |= (1 << 0); // Set LED as output
TCCR1B |= (1 << WGM12); // Configure timer 1 for
CTC mode
TIMSK |= (1 << OCIE1A); // Enable CTC interrupt
sei(); // Enable global interrupts
OCR1A = 15624; // Set CTC compare value to 1Hz at
1MHz AVR clock, with a prescaler of 64
TCCR1B |= ((1 << CS10) | (1 << CS11)); // Start timer
at Fcpu/64
for (;;) { }
ISR
ISR(TIMER1_COMPA_vect) {
PORTB ^= (1 << 0); // Toggle the LED
}
Code Fragment
for (;;) { }
Ref : http://extremeelectronics.co.in/avr-tutorials/
PWM Generation