running code once to set a boolean

I want this void, if run sometime into the sketch to set a boolean after x time.

I used this code for it:

boolean off = false;
boolean set = false;

void switchOff()
{
unsigned long previousMillis2;
unsigned long currentMillis2 = millis();
if (set == false){
previousMillis2 = millis();
set = true;}
if (currentMillis2 - previousMillis2 >= interval2)
{off = true;}}

void loop(){

switchOff();

}

My thought is, it runs the code, sets previousMillis2 to "5000".
Now it compares those "5000" to millis(), and if there is a difference of "2000" (interval2) it sets boolean off to true.

Thanks in advance :

unsigned long previousMillis2;
unsigned long currentMillis2 = millis();

Every time you call the function previousMillis2 will be set to a new, unspecified value and currentMillis2 will be set to millis()

if (currentMillis2 - previousMillis2 >= interval2)

As previousMillis2 has an unknown value how likely is this to be true when you want it to be ?

If you want the value of previousMillis2 to persist between calls to the function declare it as static but set it equal to currentMills2 before exiting the function.

Alright, I moved the unsigned long… outside of the void.

UKHeliBob:
is2 will be set to millis()

If you want the value of previousMillis2 to persist between calls to the function declare it as static but set it equal to currentMills2 before exiting the function.

By that you mean writing static rather than unsigned, right?

If thats what you mean I’ve tried it but I didnt get it to work yet.

I’ve added a LED on inside the “if (set == false)” function and I know its called, however in the next function “off” doesnt get set to true.

Thanks in advance.

How do you know that

in the next function “off” doesnt get set to true

?

In any case, I cannot deal with snippets of code.

To post code and/or error messages:

  1. Use CTRL-T in the Arduino IDE to autoformat your code.
  2. Paste the autoformatted code between code tags (the </> button)
    so that we can easily see and deal with your code.
  3. Paste the complete error message between code tags (the </> button)
    so that we can easily see and deal with your messages.

Before posting again, you should read the three locked topics at the top of the Programming Questions forum, and any links to which these posts point.

If your project involves wiring, please provide a schematic and/or a wiring diagram and/or a photograph of the wiring.

Good Luck!

Chackster:
Alright, I moved the unsigned long... outside of the void.

By that you mean writing static rather than unsigned, right?

We need a page about variable scope. It's going to have to discuss the stack.