Button coding

Can someone help me with the code that would be used to have a motor come on when a button is pressed. I can get the motors to turn on and off with the press of a button but I want the motor to run while the button is pressed then when the button is released the motor stops.

Thanks for all the help on this forum,
what a great resource for new teams.

Oh and I am using iterative


if(joystick.getRawButton(buttonNumber)
{
    speedController.set(1.0);
}
else
{
    speedController.set(0.0);
}

If this code is in the periodic teleop method, it should do what you want.

Great,
thank you very much

So I wrote the code and was able to get this to work for the motors in one direction. I would press and hold the button, the motors would spin, and when I released the button they would stop. We want the motors to spin in both directions so I wrote additional code and set the motors to -1 using a different button. When I ran the code the motor would pulse at different rotational rates. When I would program to use 2 buttons, one for on, one for off the pulsing would stop. Any ideas??? I’m not sure why in one direction the motor spins fine but in the other they pulse.

thanks

This sounds like the common coding error where one button is commanding the motor to go while the other is commanding it to stop.

You need to change your if/then/else logic so that only one command is issued to the motor(s).

if your code looks something like this:


if (button1) {setmotor(1)} else setmotor(0);

if (button2) {setmotor(-1)} else setmotor(0);

… then change it to this:

if (button1) {setmotor(1)} 
else 
if (button2) {setmotor(-1)}
else setmotor(0);

Sounds good,
I will test in about a month when it is legal to unbag our robot.

Thank you very much.

Is there any way to set this to run from multiple joysticks? For instance, having button 1 on joystick 1 start and button one on joystick 2 stop it?

You could do it like this:

if(joystick1.getRawButton(buttonNumber)
{
    speedController.set(1.0);
}
else if(joystick2.getRawButton(buttonNumber)
{
    speedController.set(0.0);
}

Thank you. Looks like it’s working.