2.5 - Triggers
Now that we’re familiar with commands, it’s time we learn how to bind those commands to triggers.
The Trigger class
The Trigger class is provided with WPILib and is effectively a much more
powerful BooleanSupplier. It can even be treated as a BooleanSupplier
because it implements that interface.
It can be constructed by giving it a BooleanSupplier to wrap.
Trigger trigger = new Trigger(() -> arm.getPosition() > 0);
Just like with BooleanSuppliers, you can call trigger.getAsBoolean()
to get the latest value from the supplier.
But we can do a lot more as well. We can combine triggers using logical operators, such as:
Trigger a = new Trigger(arm::isAtSetpoint);
Trigger b = new Trigger(intake::holdingPiece);
Trigger both = a.and(b);
Trigger either = a.or(b);
Trigger neither = either.negate();
Bindings commands to triggers
Once a trigger has been constructed, we can tell commands to run when a certain
condition regarding the trigger occurs (i.e. trigger changes from false to
true, etc.).
Here is a table of common trigger bindings:
Method |
Result |
|---|---|
|
Schedules the given command when the trigger’s value goes from |
|
Schedules the given command when the trigger’s value goes from |
|
Schedules the given command when the trigger’s value goes from |
|
Schedules the given command when the trigger’s value goes from |
|
Schedules the command if the trigger’s value changes. |