Line Robot - Basic lessons - Exercises - Smooth wall following
One of many exercises useful for RCJ Rescue Line and Maze.
Task: smoothly follow a wall.
We learned how to follow a wall, but the motion was rather erratic. The robot was constantly changing direction, either going too much toward or away from the wall. The old code is below. Can You write a code that will make movement smoother?
void RobotLine::loop() {
if (rightFront() > 100)
go(80, 20);
else
go(20, 80);
}
Solution
void RobotLine::loop() {
int error = (rightFront() - 100) * 0.5;
error = constrain(error, -50, 50);
go(50 + error, 50 - error);
}
- After starting devices, integer variable "error" is declared.
- Let's say we want to follow the wall at 100 mm. Therefore, the error in distance is
rightFront() - 100
This is the value we can use for direction correction. If the robot is too far from the right wall, for example 120 mm, the difference will be 20. If we add the difference (20) to the left motor, and subtract it from the left, the new speeds will be (70, 30). So, we will force the robot to go toward the wall, reducing the error.
- On the other hand, if the robot is too close to the wall, let's say at 50 mm, the error will be -50 (note - negative). If we do exactly the same math, i.e. add the error the the left motor, and subtract from the right, as the error is negative, the left motor's speed will be reduced, and right will be increased. The result will be (0, 100). This time the robot will go away from the wall - exactly what we needed.
- There is a factor 0.5 we multiply the result with, before storing it in "error". Do you see why? Well, the error may be 300 mm or more. Adding 300 mm would violate upper bound for speed. Therefore, we reduce the error before using it to correct speed.
- Next line uses "constrain" Arduino function, meaning: "If error is bigger than 50, it will be 50. It it is less than -50, it will be -50. Otherwise leave it as it is."
- In the last line we finally correct speeds the way we described.
Do You see what this algorithm is better? Because the error is corrected proportionally. A small error will cause a small correction and a big one a big correction. The former solution had one-size-for-all solution. Even when the error was quite small, for example 1 mm, the robot was still trying to change the direction quite vigorously - causing overshoot.