Programming the Same Function to One Button

So, we made a miniature flywheel bot capable of shooting ping pong balls and are programming the driver control. However, we want to have a button to both start and stop the flywheel. Is there anyway in RMS C++ that we can tap the L1 bumper to start the flywheel and then tap it again to stop it?

Yes. What you are trying to do is called edge detection. You want something to happen when the button changes from not being pressed to being pressed. When that happens, you want to toggle whether or not the flywheel should run.

This gives you two states that you care about:

  1. The state of the button the last time you checked it
  2. The current state of the flywheel

For this, you can create two boolean variables (outside your control loop) to represent these states:

bool button_pressed_last = false;
bool flywheel_running = false;
while (true) { // start of driver control loop

Next, you construct an if block inside the loop to handle checking the button and changing the flywheel state.

  • If button_pressed_last is false and the button is currently being pressed, flywheel_running should become !flywheel_running (read: not flywheel_running) and button_pressed_last should become true.
  • Otherwise, if button_pressed_last is true, set button_pressed_last to the current state of the button.

All that’s left after controlling the state of flywheel_running is to control the motor based by checking the flywheel_running state (i.e. if (flywheel_running) {/*etc.*/} else {/*etc.*/).

3 Likes

Hello~
John Tyler’s code looks great, but as I am always a fan of variables (and the shortest possible code :), couldn’t you just set a global variable to 1 or 0 for each button press?

Then the code for EVERY button press can be as simple as an infinite loop:

If variable is 0, set to 1
Else
If variable is 1, set to 0
wait. 01 seconds (for debouncing)

Meanwhile, motors can use a separate infinite loop:

If variable is 0, stop
Else
If variable is 1, run

Best of luck!

~Vexatron

1 Like

What happens if the user doesn’t release the button quickly or holds it down? Then it flips back and forth every .01 seconds. You need an extra variable to monitor the state of the button and only change the first variable one time until the button is released.

BTW, If you like efficient code then you could skip the if statements and use:

variable = !variable;
1 Like

Nice!

Hmmm… Or you could use a button “change.” Either way, short code is easier to write. And to debug!

(Btw, wait time was a random number. Can be set to anything, but you point is still valid.)

Thanks for the post,

~Vexatron

@Codec gave very good sample code and explanation here.

1 Like