Hello, I want to activate and deactivate a function with a single button but I’m new to programming and I’m just learning it on my own but this is getting complicated
You could do something like: make a variable that changes by 1 when you click the button, and when the variable is greater than 1, set the variable to 0. Now, put an if statement where if the variable is 1, do the action; if it is 0, don’t do anything.
Note: I am not a professional coder, I am just trying to give a simple solution, although there might be better solutions.
Then use forever loops to run things when the variable is a certain thing or put things inside the loop like simple start or stop motors
If you use variables, which is a good solution to this problem, remember that good programming practice says to declare them first and set them equal to zero (or some appropriate value). Sometimes code will freak out when it hits a variable with no value (not the same as zero/0).
Instead of using numbers, it may be better to use a boolean (true/false) and simplify the code by setting the boolean to not the the boolean value. Example: boolean = !boolean;
In this case, booleans would be a good replacement, but not always. For example, for our speed adjustment code, It needs to use variables because there are different values other than 1 and 0 that it’ll use, to allow for a more controllable speed system. (It’s going to multiply the joystick inputs by integers which are less than one, the variable will be the integers.
This is a good idea, but remember who the OP is… someone that’s just starting out.
I’ll plug my post. The example uses a bumper switch but that could easily be a button.
Isn’t there a code block that differentiates between a button that’s just been pressed (single event) and a button’s that’s held down (continuing event)???
You can create events with the Broadcast element. I believe that it is a “once per press” but I have not personally tested it.
Which codes the following:
bool IsRunning;
event MotorSwitch = event();
int whenStarted1() {
while (true) {
if (Controller1.ButtonX.pressing()) {
MotorSwitch.broadcast();
}
wait(5, msec);
}
return 0;
}
void onevent_MotorSwitch_0() {
IsRunning = !IsRunning;
if (IsRunning) {
Motor1.setVelocity(50.0, percent);
}
else {
Motor1.stop();
}
}
int main() {
// register event handlers
MotorSwitch(onevent_MotorSwitch_0);
wait(15, msec);
whenStarted1();
}