Module Operations

I want to make it where if Button B is pressed, it does X=X+1. Whenever the variable is even, a motor stays in place (probably a hold command) and when the variable is odd, the motor moves. I have no clue on how to do this so if someone knows, please do tell.

Darth,
Instead of using a number variable, I would recommend a boolean variable. A boolean is just a true/false value. Instead of doing an odd/even comparison, you just change the boolean variable and check if it is true or false to change the motor behavior. Are you using blocks or text code? Practical text code could look something like…

void buttonFunction()
{
  // make a boolean variable
  static bool variable = true;

  // change the true/false state of variable
  variable = !variable;

  // choose what to do with the motor based on variable
  
}

// this line should go in main
Controller.ButtonB.pressed(buttonFunction);

This little example psuedocode(it will not work as is) does a few things. It attaches a function to run when “B” is pressed. The functions changes the boolean to true or false, and then chooses how to change the motor.

6 Likes

I found a forum post somewhere and used it. It works now.image

while this does work, @invalidflaw’s solution is much more elegant, and I would recommend using something like that instead.

1 Like

I’ll expand on @Xenon27 with why my method is better. In general it is better for other users of your code to use the simplest variables possible. Using a number to determine odd/even for an on or off application works but is a bit confusing for other readers.

Another benefit of my code is that the static variable'' = true in my function can only be accessed by that function. Static variables within a function are saved between function uses, and allow the variable of the same name to be used elsewhere. In other words, it prevents you from accidently changing the variable you named “X”.

Having just said that, your method works. You really don’t need to change anything outside of making prettier code.

6 Likes