How to make one button start a motor then stop a motor?

Hello! i was wondering if anyone knew of a way to code it so that something similar too "hitting button “A” will start motor 1 spinning then if you hit button “A” again it will stop the spinning please let me know thank you

You can do this by storing whether the motor is moving in a Boolean variable, and set that variable to the opposite of itself whenever the button is pressed. You can then set the motor to spin or not spin based on the variable.

2 Likes

I have also been wondering about this. If you could publish an example of the code for it in Vexcode Pro that would be awesome. :grinning:

Welcome to the forums!
There are many posts about this already. Next times, please use the search bar.
Anyway, what you will want to do is use variables. for example, you could make a variable called MotorPowered and set its value to -1. On the button press event, you could have an if statement checking the MotorPowered variable. If it is -1, then have it start the motor and change the motor powered variable to 1. do the opposite when the variable is 1.

7 Likes

Thanks. You are right. I’m sorry for not checking the search bar first. Will do so in the future

I don’t have access to vr right now, but heres something you could do (I’m gonna format this like blocks).

When Started
If (Button A pressed)
then (Spin Motor 1)
If (Button A Released)
then (Stop Motor 1)

The blocks for the inputs will show up when you configure your robot in vr, so make sure to get your motors, brain, and controller set up before programming.

Hope this helps!

bool newButtonPress = true;
bool pressing = false;
bool motorRunning = false;

if(controller.button.pressing())
{
    pressing = true;
}

if(pressing && newButtonPress)
{
    if(motorRunning)
    {
        motor.stop();
    }

    else
    {
        motor.spin();
    }
}

//one-line counterpart to the below code 
// newButtonPress = pressing ? false : true;

if(pressing)
{
    newButtonPress = false;
}

else
{
    newButtonPress = true;
}

also note that bool declarations should be outside the while loop.

2 Likes

Feel free to reformat bulk code in your own projects to still retain meaning, but be easier to parse. Personally I think it reads better in this format.

1 Like