0

I'm trying to blink an LED on an ATMega328P (same MCU as Arduino I think..) using the internal timer but I'm stuck since it doesn't seem to light the LED at all....

#include <avr/io.h>
//#include <avr/delay.h>
void delay(void);
void delay_long(void);
int main(void) {
 DDRB = 0xFF; // port B is configured as output DDRB : 0b11111111
 DDRB &= ~(1<<PB1); // pin 1 of port B is configured as input DDRB : 0b11111101
 PORTB = 0x00; // pins of port B are low (output) and with no pull-up resistor (input)
 PORTB |= (1<<PB0)|(1<<PB1); // pin 0 is high (output) and pin 1 is pulled high (input) PORTB : 0b00000011
 while(1) {
 PORTB &= ~(1<<PB0);
 delay();
 PORTB |= 1<<PB0;
 delay();
 PORTB = ~(1<<PB0);
 delay_long();
 PORTB = 1<<PB0;
 delay_long(); 
 }
 return 1;
}
void delay(void) {
 TCNT0 = 0x00;
 TCCR0B = 0x05;
 while ( (TIFR0 & TOV0) == 0 ) 
 ;
 TCCR0B = 0x00;
 TIFR0 |= 1<<TOV0;
}
void delay_long(void) {
 TCNT0 = 0x00;
 TCCR0B = 0x05;
 while ( (TIFR0 & TOV0) == 0 ) 
 ;
 TCCR0B = 0x00;
 TIFR0 |= 1<<TOV0;
 TCCR0B = 0x05;
 while ( (TIFR0 & TOV0) == 0 ) 
 ;
 TCCR0B = 0x00;
 TIFR0 |= 1<<TOV0;
}

if I remove the body of the event loop it lights up... so I think I must be missing something in the delay functions...

Greenonline
3,1527 gold badges36 silver badges48 bronze badges
asked Feb 13, 2016 at 17:09
1
  • 2
    This looks like an AVR question. You are not using the Arduino core functions (that actually abstract what you are trying to do). In any case you are missing some of the timer configuration. Commented Feb 13, 2016 at 17:26

1 Answer 1

1

It seems that the offending line is:

while ( (TIFR0 & TOV0) == 0 )

TOV0 by itself equals 0, so the above loop will never end.

You should use:

 while ( (TIFR0 & (1<<TOV0)) == 0 )

instead.

answered Feb 13, 2016 at 23:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.