If a variable is only used in the one function, but needs to be static, I've started declaring it there, rather than at the beginning of my sketch with all the globals, to keep things easier to read and so I don't have lots of extra variables at the beginning that I can forget what they are.
as seen in this little example. The variable LEDmillis will never be used anywhere else, so I just put it right there. Is this a good practice?
void loop() {
if (settings.systemShutdown) { //nothing should be on
digitalWrite(pumpPin, LOW); //turn off pump
analogWrite(redPin, 0); //turn off LEDS
analogWrite(greenPin, 0); //turn off LEDS
analogWrite(bluePin, 0); //turn off LEDS
analogWrite(whitePin, 0); //turn off LEDS
LightsOn = false; //LEDupdate won't turn them on
static unsigned long LEDmillis; //timer for blink
if (millis() - LEDmillis > 1000UL) { //update the status LEDS
LEDmillis = millis(); //update timer
int state = digitalRead(PUMPstatusPin)); //get the pump LED status state
digitalWrite(PUMPstatusPin, !state); //toggle it
digitalWrite(LEDstatusPin, state); //toggle the secondary indicator as well
}
}
I do this whenever possible, I think it's good practice. But other than scope, I don't think there is much difference between a static local and a global..
Edit: What the link in my signature says about it:
[...]On the other hand, local variables inside a function should be avoided being declared
as static. A “static” local variable’s value needs to be preserved between calls to the
function and the variable persists throughout the whole program. Thus it requires
permanent data space (SRAM) storage and extra codes to access it. It is similar to a
global variable except its scope is in the function where it’s defined.
It is not used once, but rather it's used only in one place. But it keeps track of time, so it has to be 'remembered' from one pass thru the loop to the next.
guix:
I do this whenever possible, I think it's good practice. But other than scope, I don't think there is much difference between a static local and a global..
I also use static variables instead of global even to the point of preferring to pass a reference to said variable. However, in your example LEDmillis is updated with a new value every time through loop so it doesn't require a static.
I would simply use:
unsigned long LEDmillis = millis(); //timer for blink
Jimmy60:
I also use static variables instead of global even to the point of preferring to pass a reference to said variable. However, in your example LEDmillis is updated with a new value every time through loop so it doesn't require a static.
You want to read that code again? The value of LEDmiliis is updated conditionally, and, in part, based on the current (remembered) value in LEDmillis.
(Though that name is stupid. The value may have come from millis(), but it represents a time.)