Units Library - hammerheads5000/Team-Documentation GitHub Wiki

We use the Units library to help us keep track of the units on variables and convert between different units. This avoids problems like a constant with unknown or forgotten units, or a value of the wrong unit passed into a function (we don't want to pull a Mars Climate Orbiter). See the full documentation at WPILib's Documentation Page.

Creating Variables

When you create a variable with the units library it has the type Measure. You need to provide what type (dimension) of measure as well: Distance, Time, Angle, etc. To actually define the value, you have to give the measure in some unit (Inches, Seconds, Degrees, etc.):

Measure<Distance> length = Inches.of(5); // defines length as a distance of 5 inches
Measure<Time> delay = Seconds.of(1.5); // defines a 1.5 second delay
Measure<Angle> angle = Degrees.of(90); // defines a 90-degree angle

Make sure that whatever dimension or unit you use, you import it. If you let VSCode autocomplete the unit (press tab/enter midway through typing), it will import it automatically for you! To make it easier, you can also end imports with .* to import all units. Imports look like:

import edu.wpi.first.units.Distance;
import edu.wpi.first.units.Units.*; // imports all units

Complex Units

You can also use units more complicated than a simple distance or time. What about velocity? The Units library conveniently provides just that. Wrapping your dimension in Velocity will make it that dimension over time. For example:

Measure<Velocity<Distance>> speed = FeetPerSecond.of(13); // defines linear speed (distance/time) of 13 feet/sec
Measure<Velocity<Angle>> angularVelocity = DegreesPerSecond.of(20); // defines angular velocity (angle/time) of 20 degrees/sec

You can even add multiple Velocity wrappers to make acceleration:

Measure<Velocity<Velocity<Distance>>> gravity = MetersPerSecondPerSecond.of(9.8); // defines gravitational acceleration (distance/time^2) as 9.8 m/s^2

Converting

Converting from a Measure back into a number is very simple! You simply call the in method on the Measure with the argument of what unit you want the result in. For example, if there is a constant length:

length_in_inches = length.in(Inches);
length_in_feet = length.in(Feet);

And that's it!

Calculations

Calculating with units is also quite easy, though sadly not as easy as using + and -. Instead, use the plus method for +, the minus method for -, the 'times' method for multiplication, etc. You can also evaluate with boolean operators like == or < with gt for >, gte for >=, isEquivalent for ==, etc. Some examples:

Measure<Distance> length1 = Inches.of(13);
Measure<Distance> length2 = Feet.of(2.3);
Measure<Distance> length3 = length1.plus(length2);

Inches.of(11).gte(Feet.of(2)) // false
⚠️ **GitHub.com Fallback** ⚠️