Can somebody please tell me why this isn't allowed?
I was trying to create a library for an SPI device, but when I instantiate a member of my library class at a global level, the whole program seems to go South, and not even the Setup() code gets executed. If I move my member declaration inside the Setup(), or Loop() functions then everything runs fine (except my variable scope is not as desired).
Looking into this I discovered that if I comment out the delay() function, which I'm using to time my chip reset then the program runs. Hmm.
Here is a very simple example that demonstrates this:
(note this program will "crash", i.e. setup code never executes, as shown, although no compile warnings or errors are given)
Library header: Mark.h
// library test - demonstrates problem with use of delay() in constructor
// written by Mark MacDonald, aka Madhusudana das
#ifndef Mark_h
#define Mark_h
//#include "WConstants.h"
#include "WProgram.h"
class Mark
{
public:
Mark();
void test();
private:
};
#endif
Library body: Mark.cpp
// Mark Library test
// created by Mark MacDonald, aka Madhusudana das
#include "Mark.h"
Mark::Mark()
{
// the delay() function seems to kill things right here if class instance is globally declared!
delay(2);
}
/*******************************************************************************/
void Mark::test()
{
Serial.print("test() works!");
}
And the Arduino demo sketch:
//test class constructor with delay
#include <Mark.h>
Mark me; // declaration located here causes crash due to delay() function in member constructor?
void setup()
{
// Mark me; // uncomment this and comment the above declaration to see it not crash
Serial.begin(9600);
Serial.println("Are you ready?");
me.test();
}
void loop()
{
}