Passing a variable from a function to the loop function for an 'if' statement

Hello - I’m new to Photon and this question might seem very simple. I have a (int) variable defined that would be either 0 or 1. I have a function that I call and as part of that function is equal this (int) variable to 1 if call (“ON”) and set the variable to 0 if I call (“OFF”).

I would like to pass this variable to the loop() function and only run the code for reading the sensors only if this (int) variable is equal to 1.

I have trying putting an if statement inside loop() with the condition being (variable = 1) do this and else if (variable = 0) do that.

However, no matter what, the sensors still give me readings.

My question is, how do you pass a variable form a call function to the loop()?

Have that (int) variable as global variable so no need to pass it around?

As long as a variable is declared outside of setup() and loop(), or any other function, it is considered a “global” variable and should be accessible from any function (there are caveats outside the scope of this question). If a variable needs accessed from a ISR, then it needs declared as volitile. If you want better direction for your scenario, you should share some code.

I think your primary issue is: You are dealing with C/C++ here so equality checks are done with a double equal sign (e.g. if (variable == 1)).
The syntax you used there would overwrite the previous value of variable by assigning (=) a new value to it.

But as for your question

You can use global variables (as previous posters suggested) or - usually preferable when possible - have the function return the value.

int someFunction(const char* parameter) {
  int retVal = 0;
  // do stuff to change retVal
  return retVal;

void loop() {
  char someString[16];
  int localVar = 0;
  // something happens to someString
  localVar = someFunction(someString);
  if (localVar == 1)
    // do something
    // do something else
1 Like