Button Toggle - Vex Code

Hope y’all are well.

I have been struggling with turning the button into a toggle for way too long now in vex code.

What I’m wanting to do is press a button turn on a motor. Press the button again turn motor off.
Basically like a light switch.

In robotC that looked like this:

task main()
{
while(true)
{
untilBump(bumpSwitch, 300);
startMotor(leftMotor, 100);
untilBump(bumpSwitch, 300);
stopMotor(leftMotor);
}
}

I need to be able to count now. I don’t understand that process. If someone could help me out it would be very much appreciated.

bool toggle = false;
if (Bumper.pressing){
if (!(toggle)){
toggle = true;}
else if (toggle){
toggle = false;}
while (Bumper.pressing){
wait(1, msec);}}
if (toggle){
motor.spin();}
else if (!(toggle)){
motor.stop();}

3 Likes

Here is what I have using your program. I’m still not successful. Is there anything you see that would be causing an issue? All my ports are in the correct location and tested using a working program.

int main(){
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();

bool toggle = false;

if (BumperA.pressing()) {
if (!(toggle)) {
toggle = true;
}
else if (toggle) {
toggle = false;
}
while (BumperA.pressing()) {
wait(1, msec);
}
}
if (toggle){
leftMotor.spin(forward);
} else if (!(toggle)) {
leftMotor.stop();
}
}

All that code needs to be placed in your main control loop, it doesn’t work if you just run it once.

2 Likes

You do need a while loop around the whole code so it continues to run the program. I think that you also need a latch to prevent the toggle from flipping back and forth over every loop.

int main(){
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();

bool toggle = false;
bool latch = false;

while(true){

  if (toggle){
    leftMotor.spin(forward);
  } else {
    leftMotor.stop();
  }

  if (BumperA.pressing()) {
    if(!latch){ //flip the toggle one time and set the latch
      toggle = !toggle;
      latch = true;
    }
  } else {
    //Once the BumperA is released then then release the latch too
    latch = false;
  }

  wait(20, msec);
}
8 Likes

Yes! it works! Thank you so much!

all that should be in a while(1) loop

i added the wait while button is pressing so it doesn’t flip back and fourth

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.