Skip to content

Commands and Mechanisms, Part 2

Most mechanisms define a “default command” that runs when no other commands requiring it are active. The default command of an intake or a shooter, for instance, would be setting the throttle of all motors to 0, forever.

Note

In humans, this is like our brain telling our arms to hang by our shoulders when they aren’t in use.

To set a mechanism’s default command, simply call setDefaultCommand(Command), which is an instance method of all mechanisms:

class Intake implements Mechanism {
// Placeholder for TalonFX, SparkMax or SparkFlex
private final ExampleMotor motor = new ExampleMotor();
public Intake() {
setDefaultCommand(idle());
}
public Command idle() {
return run(coroutine -> {
while (true) {
motor.setThrottle(0);
coroutine.yield();
}
})
.named("Idle");
}
}

Use coroutine.wait() to wait for a predefined amount of time within the body of a command:

public Command wait5SecsThenPrintHi() {
return run(coroutine -> {
coroutine.wait(Seconds.of(5));
System.out.println("This will show up 5 seconds later.");
})
.named("Wait 5 Secs, Then Print Hi");
}

You can also give an existing command a timeout with the withTimeout() modifier:

public Command fullThrottleForFiveSeconds() {
return fullThrottle().withTimeout(Seconds.of(5));
}
public Command fullThrottle() {
return null; // placeholder for actual command
}

The following information isn’t strictly needed for the exercises in stage 1b; however, they will be very useful for future exercises and coding a real robot.

Sometimes, you need to create a command that doesn’t require any mechanisms. To do so, you can replace run(...) with Command.noRequirements(...).

class Robot {
public Command justPrintHi() {
return Command.noRequirements(coroutine -> {
System.out.println("Hello World!");
})
.named("Hello World!");
}
}

coroutine.awaitAll(a, b, c) will run the commands a, b, and c in parallel, waiting for all 3 to finish before proceeding.

public Command parallelCommands() {
return run(coroutine -> {
System.out.println("Hi!");
coroutine.awaitAll(deployIntake(), runIntakeRollers());
})
.named("Parallel Commands");
}
private Command deployIntake() {
return null; // placeholder for actual command
}
private Command runIntakeRollers() {
return null; // placeholder for actual command
}

On the other hand, coroutine.awaitAny(a, b, c) runs a, b, and c in parallel until any of a, b, or c finishes. Then, it will cancel the remaining commands.