Improving my code

As I try to write more readable/better code , I’m trying to use local variables more and more.

I’ve bashed out some demo code below, only to illustrate the question , hopefully its obvious - when the sensor says its dark, I only want to do one thing once when the processor awakes, if its still “dark” I don’t want to repaeat that bit so I use the “waslighflag”:

I was looking at ,say declaring “WaslightFlag” locally within the “test” procedure in this code , but is there a way of doing that? If I declare it at the start of the test loop, then its value is reset everytime the “test” procdure is run.
I might be missing something simple here…

// test local variables...

#include "LowPower.h"
bool Dark = 1;
bool WaslightFlag = 0;
int LDRpin=A0;
void setup()
{
}

void loop()
{
  checklightlevel();
  test();

}

//**************************
void test() // sleepy time if its dark
{
  if (Dark == 0)//its light
  {
    WaslightFlag = 0;
    //do lots of exciting stuff ....
  }
  else
  {
    //do nothing and save some power
    LowPower.idle(SLEEP_4S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF,
                  SPI_OFF, USART0_OFF, TWI_OFF);
    if (WaslightFlag == 0) // it was light last time do this, but if its still dark don't repeat
    {
      // code to do something I only want to do once as it uses power.
      WaslightFlag = 1; // record we've done that once thing
    }
  }


}
//**************************


void checklightlevel()
{
  int Z;
  Z =  analogRead(LDRpin);
  if (Z <= 300) //its light!
  {
    Dark = 0;
  }
  else
  {
    Dark = 1;
  }
  //then use to sleep everything etc, see void test....

}
//************************************

You can put it in the function without resetting on every call if you make it static.

ah ha ! light bulb on.

thx.

Yes [url=https://www.arduino.cc/reference/en/language/variables/variable-scope--qualifiers/static/]static[/url] is the way to make your local variable "sticky" whilst limiting its scope

Note that for improving your code you should also stay true to the type of variables you use. Conceptually a boolean is either true or false not 1 or 0 (even if that works).

if one day you move to more strongly typed languages, you'll be glad you have taken this best practice.

Thanks I'll try to do that.