Hi everyone,
Question on programming principle: Suppose I want to instance 5x of a class that turns on a led after a number of milliseconds have passed. I also want to use the function from within a library.
So, for example:
.h (header)
class LED{
private:
static bool timer_setup;
static unsigned long prevMillis;
static bool block_loop;
public:
static bool LedOn(unsigned long time, uint8_t x); //set time before lighting led and output to which it is connected
};
.cpp
bool LED::LedOn(uint8_t x, unsigned long timeOn){
if(!timer_setup)
{
prevMillis = millis();
timer_setup = true; //recording current time at 1st pass
}
if(!block_loop) //will block reentrance
{
if((millis() - prevMillis) <= timeOn) //compare to locked time from timer_setup
{
return(false); //exits instance and reenters at next scan
}
else
{
//Do stuff
digitalWrite(x);
//Do some more stuff
block_loop = true; //apparently not a good idea
return(true);
}
}
else
{
return(true); //operation has been completed, do not reenter decisory tree
}
}
and at the "user" .cpp
#include the lib we just talked about above
//some user vars and defines
//ok, let's instance 5 times
LED led0;
LED led1;
LED led2;
LED led3;
LED led4;
void setup(){
//user initializes "stuffff"
}
void loop{
//non-blocking stuff
led0.LedOn(1000, 0);
led1.LedOn(2000, 1);
led2.LedOn(3000, 2);
led3.LedOn(4000, 3);
led4.LedOn(5000, 4);
//non-blocking stuff
}
Now, these instances will run concurrently and light up the leds at 1,2,3,4 and 5 seconds, so it appears that the leds are turning on 1 sec apart from the other, so it's good. However, using the block_loop
bool var in the library to setup a flag that prevents the free running of the instance itself, I effectively block all the instances but the first one.
But since the lib variables are declared in the private section and set as static, I was under the impression that these were separated from each instance but still they seem to be connected.
So, how can I avoid the instance to be re-entered within the loop without actually blocking the others?
I could add a function to "unblock" (reset the bool) from a public function if I could make it work for each instance, but definitely Id like to not keep the processor reentering a one-time instance. am I missing a class characteristic? What is the most efficient way to achieve this?
Thanks