luni
Well-known member
I added a helper class which automatically maintains a list of all currently existing instances of a class to my TeensyHelpers repository.
Such a thing comes in handy if you design a class which requires the user to call some update function on all instances periodically. Here detailed usage information https://github.com/luni64/TeensyHelpers#instancelist and here the instanceList source (header only): https://github.dev/luni64/TeensyHelpers/blob/master/src/instanceList/instanceList.h
The following code shows a simple example which implements a Blinker class which periodically toggles a pin. It shows how to call a member function (blink()) on all instances of the Blinker class:
To get the list of instances, all you need to do is to derive your class from the instanceList helper class:
Usage:
The tick() function will automatically call blink() on all currently existing instances of the Blinker class.
Such a thing comes in handy if you design a class which requires the user to call some update function on all instances periodically. Here detailed usage information https://github.com/luni64/TeensyHelpers#instancelist and here the instanceList source (header only): https://github.dev/luni64/TeensyHelpers/blob/master/src/instanceList/instanceList.h
The following code shows a simple example which implements a Blinker class which periodically toggles a pin. It shows how to call a member function (blink()) on all instances of the Blinker class:
To get the list of instances, all you need to do is to derive your class from the instanceList helper class:
Code:
class Blinker : protected InstanceList<Blinker> // <- derive from InstanceList
{
public:
Blinker(int _pin, unsigned ms)
: pin(_pin), period(ms * 1000)
{
pinMode(pin, OUTPUT);
}
void blink()
{
if (t > period)
{
digitalToggleFast(pin);
t -= period;
}
}
static void tick()
{
for (Blinker& b : instanceList) // for each Blinker b in the instance list
{
b.blink();
}
}
private:
elapsedMicros t;
unsigned pin, period;
};
Usage:
Code:
Blinker b0(0, 10);
Blinker b1(1, 60);
Blinker b2(2, 24);
Blinker b3(3, 150);
Blinker LED(13, 500);
void setup()
{
}
void loop()
{
Blinker::tick();
}
The tick() function will automatically call blink() on all currently existing instances of the Blinker class.