Timer0


Timer 0 interrupt

Toolkit:AVR Development System

Location:/bipom/devtools/WinAVR/minimaxavrc/Examples/Labs/Lab06/Lab6_2

Code Example


#define ONE_SECOND  500

#define LED_RED          6        //PB6

#define LED_YELLOW       4        //PB4

#define LED_GREEN        5        //PB5


#define LED_RED_ON() 		(PORTB	&=~ 0x40)
#define LED_YELLOW_ON()  	(PORTB	&=~ 0x10)
#define LED_GREEN_ON()  	(PORTB	&=~ 0x20)

#define LED_RED_OFF() 	    (PORTB	|= 0x40)
#define LED_YELLOW_OFF()   	(PORTB	|= 0x10)
#define LED_GREEN_OFF()   	(PORTB	|= 0x20)

unsigned int Ticks = 0 ;
unsigned char RedFlag;         // Flag for Red LED state


ISR (TIMER0_OVF_vect)
{
	// Interrupt every 2 mS


	if(Ticks == ONE_SECOND)
		{
			if(RedFlag)   // Changing Red LED state

			{
				RedFlag=0;
				LED_RED_ON(); // Turn on RED LED

			}
			else
			{
				RedFlag=1;
				LED_RED_OFF();// Turn off RED LED 

			}
			Ticks = 0;
		}
	Ticks++;
}



int main(void)
{
	//Initialize port pins

 	/* Define pull-ups and set outputs */
	/* Define directions for port pins */
	PORTB = (1<<LED_RED)|(1<<LED_YELLOW)|(1<<LED_GREEN);
	DDRB  = (1<<LED_RED)|(1<<LED_YELLOW)|(1<<LED_GREEN);
	
	//Initialization Timer0

	// Timer/Counter 0 initialization

	// Clock source: System Clock

	// Clock value: 125,000 kHz

	// Interrupt every 2mS

	TCCR0A=0x00;
	TCCR0B=0x03;
	TCNT0=0x00;
	OCR0A=0x00;
	OCR0B=0x00;	

	//Timer0 Overflow Interrupt Enable													

	TIMSK0 = 0x01;
	Ticks = 0;

	// Global enable interrupts

	sei();

	while (1) ;
}