Hi, I'm trying to use the timer 0 to generate a 1 ms delay and repeat that delay to generate a 0.5 sec between LED state changes. I don't know what is missing. The LED just turns on but don't blink. Thanks for your help.
void setup()
{
PORTB = 0;
DDRB = 1 << DDB5; // LED is wired to the DDB5 pin. configures this pin as output
// timer 0 config.
OCR0A = 249; // timer 0 will count 250 pulses
TCCR0A = 1 << WGM01; // disconnect comp. A and B from the pins. Select CTC mode.
TCCR0B = (1 << CS01) | (1 << CS00); // timer 0 prescaler=64. For Fosc=16000000 the compare match will be every 1 ms. T=250*64/16000000
}
void loop()
{
PORTB |= 1<<PORTB5; // turns on the LED
// 500 ms delay
for( int counter=0; counter<500; counter++ )
{
// waits for the OCF0A flag
while( (TIFR0 & (1<<OCF0A)) == 0 )
{
}
TIFR0 = 1 << OCF0A; // clears the OCF0A flag
}
PORTB &= ~(1<<PORTB5); // turns off the LED
// the same 500 ms delay
for( int counter=0; counter<500; counter++ )
{
while( (TIFR0 & (1<<OCF0A)) == 0 )
{
}
Thanks Coding, reading another post I found a simple solution. Just set the TCCR's registers to 0. Here's the code modified:
void setup()
{
PORTB = 0;
DDRB = 1 << DDB5; // LED is wired to the DDB5 pin. configures this pin as output
// returns the TCCR's to their Reset state. This fixed the problem
TCCR0A=0;
TCCR0B=0;
// timer 0 config.
OCR0A = 249; // timer 0 will count 250 pulses
TCCR0A = 1 << WGM01; // disconnect comp. A and B from the pins. Select CTC mode.
TCCR0B = (1 << CS01) | (1 << CS00); // timer 0 prescaler=64. For Fosc=16000000 the compare match will be every 1 ms. T=250*64/16000000
}
void loop()
{
PORTB |= 1<<PORTB5; // turns on the LED
// 500 ms delay
for( int counter=0; counter<500; counter++ )
{
// waits for the OCF0A flag
while( (TIFR0 & (1<<OCF0A)) == 0 )
{
}
TIFR0 = 1 << OCF0A; // clears the OCF0A flag
}
PORTB &= ~(1<<PORTB5); // turns off the LED
// the same 500 ms delay
for( int counter=0; counter<500; counter++ )
{
while( (TIFR0 & (1<<OCF0A)) == 0 )
{
}