vex c++ help for flywheel

I need help making a toggle button for my flywheel that I can toggle multiple speeds for the flywheel I have code for the flywheel but have to keep it pressed for to keep the flywheel going

code for non toggle:
if(Controller1.ButtonUp.pressing()) {
Flywheel.spin(directionType::fwd, 200, velocityUnits::rpm);
}
else {
Flywheel.stop(brakeType::coast);
}

add a void function above the main task to set the flywheel speed, use variable that holds the desired speed, and change that variable value by button presses:


void setFlywheelRPM(int _rpm){
    if (_rpm == 0){
        Flywheel.stop(); // stop flywheel if rpm is 0
    }
    else {
     Flywheel.spin(directionType::fwd, _rpm, velocityUnits::rpm);       
    }
}

// ... then in the user control section...
void usercontrol( void ) {

    int FlywheelRPM = 0; // declare a variable to hold the desired flywheel rpm
    Flywheel.setStopping(brakeType::coast); // always coast flywheel motor

  while (1){

      if(Controller1.ButtonUp.pressing()) { 
          FlywheelRPM = 600;  // high rpm on up
      }
      
      if(Controller1.ButtonLeft.pressing()) { 
          FlywheelRPM = 400;  // low rpm on left
      }
      
      if(Controller1.ButtonDown.pressing()) {
          FlywheelRPM = 0;   // stop flywheel on down
      }
      setFlywheelRPM(FlywheelRPM); // send the desired rpm to setFlywheelRPM function

    vex::task::sleep(20); //Sleep the task for a short amount of time to prevent wasted resources. 
  }
}

You can have the button that toggles speeds by putting in the loop

int flywheelspeed = 0;

Flywheel.spin(vex::directionType::fwd, flywheelspeed, vex::velocityUnits::rpm);

if(Controller1.ButtonUp.pressing())
{
flywheelspeed = 200; //this will be for max speed
}
else if(Controller1.ButtonLeft.pressing())
{
flywheelspeed = 100; //half speed
}
else if(Controller1.ButtonRight.pressing())
{
flywheelspeed = 50; //quarter speed
}
else if(Controller1.ButtonDown.pressing())
{
flywheelspeed = 0; //off
}
else
{
}

There are a few other ways of doing it, but the main principle is in your code it is testing for every moment the flywheel button is not pressed, the else immediately shuts off your flywheel because of the brake command. If you need some more help or would like your new system reviewed feel free to PM me, I’d be happy to assist.

-tk