What is probably happening is that since you are using a button.pressing function, the loop runs many times while the button is being pressed, since the spinToPosition function is also set to continue before completion.
Let’s say that you run your code and press the y button. What ends up happening is that the arm receives instruction to spin to 450, and then sets armposition to false, like you want it. However, the code then moves on to the armposition == false portion of the code, and sends instruction to the motor to spin back to 0. The code then cycles through the loop, over and over again until the button is no longer being pressed.
The reason this sometimes works is that sometimes the last instruction the code is to spin to 450, and sometimes to 0.
There are a couple of ways you can solve this:
a) Remove the “false” from each spinToPosition function. This will make the motor finish its movements before moving on in the code. Assuming your press is short enough, this should work. However, any other part of the code will not work during this stage. This is a simple fix, but not one I would recommend unless all else fails.
b) Use a button.pressed function instead. You will have to define the functions in a different part of the code, and call the function on button press. This is the method I would recommend using. It should look something like this:
void buttonY(){
if(armposition == true){
arm.spinToPosition(450,rotationUnits::deg,90,velocityUnits::pct, false);
armposition = false;
}
else if (armposition == false){
arm.spinToPosition(0,rotationUnits::deg,90,velocityUnits::pct, false);
armposition = true;
}
}
void buttonR(){
if(armposition == true){
arm.spinToPosition(550,rotationUnits::deg,90,velocityUnits::pct, false);
armposition = false;
}
else if (armposition == false){
arm.spinToPosition(0,rotationUnits::deg,90,velocityUnits::pct, false);
armposition = true;
}
}
bool armposition = true;
Controller1.ButtonY.pressed(buttonY());
Controller1.ButtonR.pressed(buttonR());
One more note: I would suggest that you create shorthand variables for each button, so that you don’t have to type out the whole thing every time. It’ll look something like this:
int BY = Controller1.ButtonY.pressing();
int BR = Controller1.ButtonR.pressing();
Then, in your code, you can simply use “BY” or “BR” instead. It’ll look something like:
if(BY){
//code
}
if(BR){
//code
}
While this doesn’t seem like much now, as you start making more complex macros using with multiple cases depending on sensor values or multiple button presses, it’ll come in handy.
Edit: Code error fixed