jung6717 / arduino

Automatically exported from code.google.com/p/arduino
0 stars 0 forks source link

Calling delay() from within library class constructors halts execution #129

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Global class constructors gets called before the init() routine 
initializing timers is called. As a consequence calls to delay() from 
within a global class constructor will never return.

Rather than calling init() explicitly from within main(), the Arduino init
() code should be moved to run as part of the avr-gcc startup code before 
class constructors get called.

The following two patches are needed:

In wiring.h (change declaration of init)

void init(void) __attribute__ ((naked)) __attribute__ ((section 
(".init5")));
//void init(void);

In main.cxx (remove explicit call of init)

int main(void)
{
    //init();

    setup();

    for (;;)
        loop();

    return 0;
}

A forum post on the issue is here:

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1255288430

Original issue reported on code.google.com by bflaglie@c2i.net on 12 Oct 2009 at 5:43

GoogleCodeExporter commented 9 years ago
Applying this patch (as is) has an issue with leaving global interrupts 
disabled for 
a sketch with no reference to millis(). More on this here:

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1259776743/0#4

Original comment by bflaglie@c2i.net on 3 Dec 2009 at 3:22

GoogleCodeExporter commented 9 years ago
I think one should not be calling delay() inside class constructors. Instead, a 
begin() method should be provided, where the necessary hardware initialization 
would be done.

So I think the reported issue should not be fixed in code, but just documented 
in the "writing your own library" section.

My 2 cents.

Original comment by marcello...@gmail.com on 1 Oct 2012 at 9:35

GoogleCodeExporter commented 9 years ago
Ooops, sorry, just noticed how old this is. Sorry!

Original comment by marcello...@gmail.com on 1 Oct 2012 at 9:35

GoogleCodeExporter commented 9 years ago
This problem could not be easily solved for AVR, the suggested fix has some 
side-effects as reported on the linked forum thread.

Another workaround may be to use delayMicroseconds instead of delay, since 
delayMicroseconds doesn't rely on any hardware timer. BTW this won't avoid you 
the C++ static initialization order fiasco:

https://isocpp.org/wiki/faq/ctors#static-init-order

So, the suggestion to use a begin() method in your class to do the 
initialization is the most valid suggestion for an Arduino library.

Original comment by c.mag...@arduino.cc on 3 Jul 2015 at 1:26