Datasheet

Robot Control with Distance Detection • Chapter 8
Robotics with the BOE Shield-Bot 259
const int setpoint = 2; // Target distances
const int kpl = -50; // Proportional control constants
const int kpr = -50;
The convenient thing about declaring constants for these values is that you can change them
in one place, at the beginning of the sketch. The changes you make at the beginning of the
sketch will be reflected everywhere these constants are used. For example, by changing the
declaration for
kpl from -50 to -45, every instance of kpl in the entire sketch changes
from -50 to -45. This is exceedingly useful for experimenting with and tuning the right and
left proportional control loops.
The first thing the
loop function does is call the irDistance function for current distance
measurements and copies the results to the
irLeft and irRight variables.
void loop() // Main loop auto-repeats
{
int irLeft = irDistance(9, 10); // Measure left distance
int irRight = irDistance(2, 3); // Measure right distance
Remember the simple control loop calculation?
Output for maneuver = (Distance set point Measured distance) x Kp
The next two lines of code perform those calculations for the right and left control loops, and
store the output-for-maneuver results to variables named
driveLeft and driveRight.
// Left and right proportional control calculations
int driveLeft = (setpoint - irLeft) * kpl;
int driveRight = (setpoint - irRight) * kpr;
Now, driveLeft and driveRight are ready to be passed to the maneuver function to set
the servo speeds.
maneuver(driveLeft, driveRight, 20); // Drive levels set speeds
}
Since each call to maneuver lasts for 20 ms, it delays the loop function from repeating for 20
ms. The IR distance detection takes another 20 ms, so the
loop repetition time is about 40
ms. In terms of sampling rate, that translates to 25 samples per second.
Sampling Rate vs. Sample Interval: The sample interval is the time between one sample and the
next. The sampling rate is the frequency at which the samples are taken. If you know one term,
you can always figure out the other: sampling rate = 1 ÷ sample interval.