Driving

These custom functions for driving the robot use the wheel encoders:

  • driveStraight() — drive straight continuously

  • driveDistance() — drive straight for specific distance

driveStraight()

A custom function named driveStraight() uses the wheel encoders to make your robot drive in a straight line.

Driving perfectly straight requires the left and right motors to rotate at the same rate. It is common for a robot to drift slightly (to the left or right) when driving. This indicates the motors aren't rotating at the same rate, even though they're using the same motor power.

You can compare the left and right wheel encoder counts as your robot drives to see whether they are the same or not. If they aren't the same, the left and right motor powers can be individually adjusted, so they rotate at similar rates, making the robot drive in a straight line.

In order to work, the driveStraight() function must be continuously called by the loop() function (or continuously called by a loop within another function).

Driving straight continuously is usually combined with other robot behaviors, such as: detecting collisions, avoiding collisions, avoiding a line, counting lines crossed, etc.

The driveStraight() function requires these objects as part of your global variables before the setup() function:

RedBotMotors motors;
RedBotEncoder encoder(A2, 10);

The driveStraight() function uses global variables to track the left and right motor powers, as well as the left and right encoder counts. Add this code before the setup() function:

// global variables needed for driveStraight() function
int leftPower = 150, rightPower = leftPower;
long prevLeftCount = 0, prevRightCount = 0;

The wheel encoder counters should be reset to zero when your app first starts. Add this code statement within the setup() function:

Add the driveStraight() custom function after the loop() function:

driveDistance()

A custom function named driveDistance() uses the wheel encoders to make your robot drive straight for a specified distance.

Remember that for the RedBot, the following is true:

192 ticks of wheel encoder = 1 wheel revolution = 8.04 inches traveled

This information can be used to convert any encoder count into distance traveled — or to convert a desired distance into a target encoder count. The driveDistance() function uses the encoder counters to control how long the motors are allow to drive.

When calling the driveDistance() function, you must pass in a value for the desired distance (inches) by listing the value inside the parentheses after the function's name.

For example, to make your robot drive 24 inches:

You can even drive backward by passing in a negative value for the distance:

The driveDistance() function requires these objects as part of your global variables before the setup() function:

Add the driveDistance() custom function after the loop() function: