There are two ways to drive for distance:
-The way you show (except your example can only drive forwards)
-By controlling the speed setpoint based on another controller. In this way, you will ramp down the speed setpoint as you approach the target distance, to gracefully stop. You would do this with a simple proportional controller and range coerce, which is conceptually like this:
Code:
while(not_at_target) {
distance_error = distance_target - distance_traveled
int setpoint = distance_error * kp
if(setpoint > 9000) setpoint = 9000; //limit setpoint to a maximum velocity
do_speed_control();
}
Like the speed control, I would do this for each wheel (but condition the while loop based on either the maximum or average distance). This allows you to command a higher velocity to whichever side lags.
Since the example above does not have an integral term, I usually do the following:
-Lead the setpoint that the controller tries to achieve by setting it a few inches/feet in front of the point where you actually want to go, so you're still applying a little power at the point you actually want to go (you can't get stuck with too little power to move).
-Gracefully stop with a separate call to the velocity controller - I had a separate controller to allow me to tune the decel acceleration, so the robot would not jump as it quickly stopped. I also did this primarily with a PI controller since I cared more about stopping than holding a velocity of 0.
Both of those are more advanced topics which I am providing as food for thought. The example you showed will work fine (provided you think about negative distances).