Welcome To Sculland.com

My Notes On The Atmel 8-bit AVR ATmega168 Microcontroller

Interrupts And Timers How to Control 30 LEDS With Only 6 Pins
Create Sounds Using A PC Speaker

Timers And Interrupts On The ATMEGA168 Microcontroller

There are three timers available to you on the ATmega168. There is one 16-bit timer, called Counter 1 and two 8-bit timers called Counter 0 and Counter 2. The 16-bit timer can count up from 0 to 65,535 (Which in Binary is 11111111 11111111). The 8-bit timers can only count up from 0 to 255 (Which in Binary is 11111111).

How To Setup The 8-bit Timers How To Setup The 16-bit Timers
Now For the Software End Of Things Timer Counting Speed Table
8-bit Timer Example - Use Software To Control A LED 16-bit Timer Example - Use Software To Control A LED
8-bit Timer Example - Use Hardware To Control A LED 16-bit Timer Example 2 - Use Software To Control A LED
Show All

8-bit Timer Example - Software Controlled

#include <avr/io.h>
#include <avr/interrupt.h>

int main(void)
{
	//*****************************************      Setup 8-bit Timer 0      *****************************************//
	TCCR0A = 0b00000010;		// |COM0A1|COM0A0|COM0B1|COM0B0|0|0|WGM01|WGM00|
					// COMA and COMB are set to normal,  OC0A and OC0B are disconnected respectively
					// WGM is set to CTC - Clear Timer on Compare (of OCR0A) Mode#2 = 010

	TCCR0B = 0b00000000;		// |FOC0A|FOC0B|0|0|WGM02|CS02|CS01|CS00|
					// FOC set to default - WGM02 set to 0 - Clock set to off

	TIMSK0 = 0b00000110;		// |0|0|0|0|0|OCIE0B|OCIE0A|TOIE0|
					// Timer Output Compare Match Interrupt A and B are enabled

	TIFR0  = 0b00000000;		// |0|0|0|0|0|OCFOB|OCF0A|TOV0|
					// Flags are set to 0 - Default settings
	
					// IE If running at 1 mhz (1000000 ticks per second), and selection set to 1024.
					// Duration of one timer tick - 1024/1000000 sec = 0.001024
	OCR0A = 244;			// Set to trip every 0.249856 sec (244 * 0.001024) Which is about 0.25sec, 1/4 of a second.
	OCR0B = 122;			// Set to trip every 0.124928 sec (122 * 0.001024) Which is about 0.125sec, 1/8 of a second.

					// We need to set Port B's Data Direction Register for pin PB0 for output.
	DDRB = DDRB | 0b00000001;	// Leave all the other bits alone, just set bit 0 for output

	sei();				// Enables the global registers.
	
	TCCR0B = 0b00000101;		// |FOC0A|FOC0B|0|0|WGM02|CS02|CS01|CS00|
					// Turn On Clock and set speed selection to Clock/1024
    while(1)
    {
    }
}

ISR#TIMER0_COMPA_vect#
{
	PORTB = PORTB & 0b11111110; 	// Turn off pin PB0 on Port B, leave all other bits alone.
}
	
ISR#TIMER0_COMPB_vect)
{
	PORTB = PORTB | 0b00000001; 	// Turn on pin PB0 on Port B, leave all other bits alone.
}

References