0

I have a simple function to catch the edge of a button press and do something:

  bool SetLED(int Button,int LED, bool LED_State, bool Button_Pressed)
{
  //Get Button State
  bool LiveButtonPress = (digitalRead(Button) == LOW);

  if ( LiveButtonPress && not(Button_Pressed)) // Pos Edge of Button Press
    {
        LED_State = not(LED_State);
        if (LED_State)
        {
          digitalWrite(LED,HIGH);
        }else
        {
          digitalWrite(LED,LOW);
        }

        digitalWrite(LED_BUILTIN,HIGH);
    }
    else
    {
        digitalWrite(LED_BUILTIN,LOW);
    }
    
  Button_Pressed = LiveButtonPress;

  return false;
}

I want to be able to manipulate the variable I am passing to the function for both LED_State and ButtonPressed so I can reference that state elsewhere in pascal I would do this via a var in the function arguments, is there something similar in C++?

levi Clouser
  • 338
  • 1
  • 4
  • 14
  • 3
    "so I can *reference* that state..." what you want is actually called passing by reference. `bool SetLED(int Button, int LED, bool& LED_State, bool& Button_Pressed)` instead of copying the value of `LED_State` and `Button_Pressed`, a change in a reference changes the variable being referenced. – JohnFilleau Oct 20 '20 at 02:28
  • 2
    I really recommend that you get [a few good books](https://stackoverflow.com/q/388242/440558) and learn C++ properly. – Some programmer dude Oct 20 '20 at 02:28
  • 2
    Consider naming your function something besides `SetLED`, since it does more than that. You're performing state machine actions, so something like `do_LED_state_machine` or similar might be appropriate. – JohnFilleau Oct 20 '20 at 02:29
  • [When I change a parameter inside a function, does it change for the caller, too?](https://stackoverflow.com/q/1698660/995714) – phuclv Oct 20 '20 at 07:42

1 Answers1

0

as Stated in the Comments by johnfilleau the answer was to pass by Reference

so the function Declaration should be:

bool SetLED(int Button,int LED, bool LED_State, bool Button_Pressed)

but as this was a simple snippet, more things should be done to make good code out of it before using

levi Clouser
  • 338
  • 1
  • 4
  • 14