I came across a class which sole purpose was to create blinking leds. He used the class for 2 objects which had a different blinking interval. I started thinking in how I could use constants but nothing came to me.
Is it possible to use a const int in combination with the constructor to use different constants for objects?
I am aware that a const int is to be initialized at the same place where it is declared, so I'd guess that the answer is 'no'
If not, are there workarounds to achieve the same thing? That is using different constants (so less memory usage) for different objects of the same type.
The used platform in question is the arduino IDE and an atmega328P. May it perhaps be that the compiler recognizes that the variables are actually used as constants and treat them as such?
.h
class BlinkingLed
{
private:
int blPin;
short blinkInterval; // <-- the contant
bool blinking;
bool ledOn;
long lastTime;
public:
BlinkingLed(int, int);
void setBlinkInterval(int); // never used, should not exist
int getBlinkInterval(); // never used, should not exist
void setLedOn(bool);
bool getLedOn();
void attachPin();
void heartBeat();
};
.cpp
BlinkingLed::BlinkingLed(int aPin, int aBlinkInterval) // constructor
{
blPin = aPin;
blinking = false;
ledOn = false;
blinkInterval = aBlinkInterval; // <-- the contant
}
The objects are made with this line. The aki class needs 2 BlinkingLed objects.
AKI aki(new BlinkingLed(23,333), new BlinkingLed(22,667), 24); // Red blinks 90/minute, green 45/minute
This is the constructor of aki:
AKI::AKI(BlinkingLed *aRedLight, BlinkingLed *aGreenLight, int aBellPin)
{
redLight = aRedLight;
greenLight = aGreenLight;
bellPin = aBellPin;
}
The 333 and 367 are stored in variables and I want these to become constants to preserve memory space. How do I do that?