Index multiple speeds in a toggle control

We are trying to turn on a motor and keep it on with the toggle control using Conner’s design so when we toggle the motor to spin at a set speed, it will work as intended. To index the speeds, we want to change the value of the rpm by pressing a separate button. So what it should do is start at 390 rpm when we press the up button, then cycle to a higher speed, e.g., 600, and if it is pressed again, it should cycle to the lowest speed, e.g., 200 rpm. Through trial it won’t accept a new value for it

void usercontrol(void){
  bool toggleEnabled = false; // two-choice toggle, so we use bool
  bool buttonPressed = false; // logic variable

  int i=2;
  int x;

  while(1){
   bool buttonA = Controller1.ButtonA.pressing();

  if (Controller1.ButtonUp.pressing()){
    i++;
  }

  if(i==1){
    x = 300;
  } else if (i==2) {
    x = 390; 
  } else if (i==3) {
    x = 600;
  } else {
    i=1;
  }

    // Toggle Logic
    if (buttonA && !buttonPressed){
      buttonPressed = true; 
      toggleEnabled = !toggleEnabled;
    }
    else if (!buttonA) buttonPressed = false;

    // Code For toggle Enabled or Disabled
    if(toggleEnabled){
      FlyWheel.spin(fwd, x, rpm);
    } else{
     FlyWheel.stop(coast);
    }

Thanks :slight_smile:

How is this code failing? Knowing how a program fails provides valuable information to us to fix the program.

As for me, I see two potential problems:

  1. x is uninitialized. Uninitialized variables could cause a problem, but I don’t think it is causing a problem here. My suggestion would be to originally set x to 0
  2. There is no button latch on the up button. This will cause the program to endlessly change speeds as long as the button is being pressed, this means that when the button is released, the new speed will be essentially random. This endless speed changing will also cause the motor to throttle and dethrottle multiple times per second which will burn it out rapidly. My suggestion would be to add button latch code to the up button in a similar way to the way you already did that with button A.
1 Like

You may want to separate your programming concerns by using functions. It makes it easier to maintain your code.

//Define your variables. 
int SelectedSpeed = 0;
double FlywheelSpeed = 300.0;

//This function is responsible for setting the speed.
//Every time your press the button it will index by one.
void ChangeFlywheelSpeed() {
  SelectedSpeed++;
  if (SelectedSpeed > 2 {
    SelectedSpeed = 0;
  }
  if (SelectedSpeed == 0) {
    FlywheelSpeed = 200.0;
  } else if (SelectedSpeed == 1) {
    FlywheelSpeed = 300.0;
  } else if (SelectedSpeed == 2) {
    FlywheelSpeed = 400.0;
  }
}

int DriverControl() {
  while (true) {
    Controller1.ButtonX.pressed(ChangeFlywheelSpeed);
    Flywheel.setVelocity(FlywheelSpeed, rpm);
	wait(20, msec);
  }
  return 0;
}
3 Likes

I was just able to test it. Thanks for helping :grin:

1 Like