Driving and maneuvering using just time as the controlling variable can be unpredictable and lack in accuracy when precision is needed. This is where motor encoders come in. Encoders track speed and position of a motor shaft, which makes getting to specific targets and having accurate movement much easier if speed and position can now be tracked.
LM.velocity(rpm); //returns velocity of motor, can take rpm or pct
LM.rotation(rev); //returns the amount of rotations completed, can take revolutions or degrees
Inch Drive is a function that tells the robot to drive a certain distance, in inches, and stop. It uses the encoder position of the motor axle and some basic geometry. This is also the basic version of a proportional controller from a PID, though it is somewhat different in design.
In this function we are setting up a global variable dia (diameter) of the wheel which is 4 inches. Using the diameter of the wheel we could calculate how far a wheel rolls when the robot moves forward using circumference
Circumference = dia * Pi
The gear ratio internal to the smart motor is set in the device set up. Any external gear ratio must be included in the distance calculation using a global variable. To use the gear ratio correctly we multiply the motor revolutions by the number of teeth on the gear that is on the motor and divide by the number of teeth on the gear that is on the wheel. Any extra gears between the motor and the wheel do not change the ratio. Also be careful to use float variables not integers. Integers will drop any decimal values so a ratio of 1.5 cast as an integer is 1.
float G=Teeth on motor gear / Teeth on wheel gear. The motor gear is sometimes called the driving gear while the gear on the wheel is the driven gear.
$$ x=Encoder(rev)piwheelDiameter*GearRatio $$
expressed in code:
x=LM.position(rev)PiD*G;