Toggle in vexcode pro

Struggling to make a simple toggle work.

bool toggle=0
void toggleTest(){
  toggle=!toggle
}

while (1){
  Controller1.ButtonA.pressed(toggleTest);
}

This is pretty much the code. It will rarely actually flip the boolean. Why could this be? Thanks

1 Like

This registers a callback and should only ever be called once, never place it in a while loop, add near the beginning of main or some other suitable place.

7 Likes

Would it be better to use “if pressing”?

Why is the Button.pressed() command like this. It took me ages to figure out how to use it. Why couldn’t it be the same as a Button.pressing() command, where you can use it in a while loop. How it is right now means that you can only use it with a subroutine, which makes certain things a lot trickier to do.

If you wish to use that then you have to put the if statement in the while loop

while(1){
 if buttonpressed{
toggleTest()
}
}

Button.pressing() returns a boolean (true/false) status of the button at that moment. This can be continuously evaluated inside of a while loop and works well for a driver to control motors.

while(true) {
   if(button1.pressing()) {
      motor1.spin(forward);
   }
}

Button.pressed(DoSomething) fires an event when the button is pressed. This example calls the DoSomething() function one time and will not call it again until the button is released and pressed again. Events are great if you want to robot to do a subset of commands.

void DeployEndgame()
{
    motor1.spinTo(90, degrees);
    motor2.spinTo(30, degrees);
}

int DriverControl(){

   //register button event
   button1.pressed(DeployEndgame);

   while(true) {
     //Code to operate robot.
   }
}
5 Likes

I didn’t realize how simple of a fix that was. Works great now, thank you.