Programming Using A Toggle Function

Is there a way to make a function on the robot to be able to toggle? I have tried things like

int variable = 0;

if (buttonPressed && variable%2 == 0) {
//do something
variable += 1;
} else if (otherButtonPressed && variable%2 == 1) {
//do the other thing
variable += 1;
}

But I am having problems with this as the program is constantly switching between the two when I press the button. If I hold down the button, the variable will switch from 1 to 0 and then from 0 to 1 infinitely until I stop holding the button down. So if I just tap the button, it probably switches like 5 times or 6 or maybe 4 because every tap can’t be exactly the same. It is not accurate and fails a lot. Am I just a noob or is this a common problem?

My solution to this is set a variable when button is pressed and reset it when it is not. If the button is being pressed but the variable is still set, it doesn’t run

1 Like

Your program is looping many times a second. So by the time you’ve released the button, the program has looped like 5 times. We can counteract this by not only checking to see if the button is currently pressed, but also checking if the button was not pressed in the last run.

int variable = 0;
bool last = false;

if (buttonPressed && !last && variable%2 == 0) {
//do something
last = true;
variable += 1;
} else if (buttonPressed && !last && variable%2 == 1) {
//do the other thing
last = true;
variable += 1;
}
else if (!buttonPressed) {
last = false;
}

Also, if you have a boolean in C++, you can make the boolean equal to its opposite state using ! (the not operator). We can use this to simplify your code a bit. So if you wanted to toggle a variable called state, you would do state = !state; So the code would look a bit more like

bool state = false;
bool last = false;

while(true) {
   if(button && !last) {
      state = !state;
      last = true;
   } else if(!button) {
      last = false;
   }

   if(state) {
      //Do thing 1
   } else {
      //Do thing 2
   }
}
2 Likes

I am glad that there are good people out there willing to help one another out. I have been on forums before where I will ask a question, and people, even though they probably have the answer, don’t reply. Thank you all!

1 Like