-
Notifications
You must be signed in to change notification settings - Fork 3
Tutorial 05: Using Preferences
In a previous tutorial, our lifter subsystem had commands to move up and down at fixed speeds. Rather than putting the values for the speed in the code directly, I recommended making constants at the start of the file. This makes it easy to find values and adjust them during testing, something that happens very frequently. However, changing a constant still requires recompiling, and redeploying to the robot, for changes to take effect. In this tutorial, I'll show you how to use preferences to allow us to change values at run-time, speeding up the program-test-tweak cycle.
Instead of declaring constants, we'll declare special preference
objects, with a string to identify it, like "LifterUpSpeed"
, and a
default value. Whenever we need to use the value, we call the get()
method on this object, which returns the current value of the
preference.
Open up LifterSubsystem.java
. We can replace those constants with
preferences as follows:
public class LifterSubsystem extends Subsystem {
private PreferencesSet prefs = new PreferencesSet("Lifter");
private DoublePreference upSpeed = prefs.addDouble("UpSpeed", 0.5);
private DoublePreference downSpeed = prefs.addDouble("DownSpeed", -0.5);
private VictorSP liftMotor = new VictorSP(RobotMap.Lifter.LIFT_MOTOR);
public Command upCmd() {
return QuickCommand.continuous(this, () -> {
liftMotor.set(upSpeed.get());
});
}
public Command downCmd() {
return QuickCommand.continuous(this, () -> {
liftMotor.set(downSpeed.get());
});
}
// ... and all the other stuff we had before ...
}
Now, when you run this code, it should initially be the same as before. Open the dashboard, open the NetworkTables tab on the right under Sources. Right-click on Preferences, and hit Show as: Robot Preferences. Resize the new widget until it looks how you like.
(You have no idea the Hell I went through to get these screenshots)
Now you can modify the preferences in the table, and it should change the speed of the motors. These preferences will be saved to the robot, so changes will persist between reboots and redeployments.
The way we handle preferences is far from perfect. The fact that there's a search bar now makes it a bit better, but there is still room for improvement. Check out the project ideas for more info, and message @blucoat on Slack if you're interested in improving it.