0
\$\begingroup\$

I am loading the following code into ATmega32A PU 1535 to flash the LED on pin 40, PORTA 0:

#include <avr/io.h>
#include <util/delay.h>


#define __DELAY_BACKWARD_COMPATIBLE__

#ifndef F_CPU
#define F_CPU 16000000UL    /* 16 MHz clock speed */
#endif

int
main(void)
{
    DDRA |= (1<<PA0);              /* Nakes PORTA as output */

    while (1)
    {
        PORTA |= (1<<PA0);         /* turn 1st led on */
        _delay_ms(150);            /* 0.15s delay, but is on by 10ms actually */
        PORTA &= ~(1<<PA0);        /* turn led off */
        _delay_ms(10);             /* delay 0.01s, but is off by 150ms actually*/
    }
}

LED blinks but as pointed in the comments LED is on 10ms and off 150ms. How it is so? The only way I can get this result is that delays are actually called before IO, like this:

        _delay_ms(150)
        PORTA |= (1<<PA0);         /* turn 1st led on */
        _delay_ms(10);
        PORTA &= ~(1<<PA0);        /* turn led off */

Since _delay_ms doesn't warn against compiler optimizations nor it gives any special hints in that direction I must be doing something wrong.

\$\endgroup\$
2
  • \$\begingroup\$ How is the LED connected to the mega? it looks like your logic is inverted, so setting PA0 High turns the LED off not on. \$\endgroup\$
    – Gorloth
    Commented Apr 28, 2016 at 14:45
  • \$\begingroup\$ @Gorloth yeah... That is it. Thank you. Please post as an answer. \$\endgroup\$
    – 4pie0
    Commented Apr 28, 2016 at 14:55

1 Answer 1

1
\$\begingroup\$

I would double check how the LED is connected to the ATmega32. If PA0 is connected to the cathode (negative terminal) of the LED then setting the pin to low (ground) would cause it to turn on and not off. This is refereed to as an 'active low' setup as the LED is active (lit) when the output is low. You can also have active low controls when using transistors to switch a load depending on how things are connected.

\$\endgroup\$
1
  • \$\begingroup\$ Indeed, it was because the legs were inverted. Thank you very much. \$\endgroup\$
    – 4pie0
    Commented Apr 28, 2016 at 15:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.