Line Robot - Basic lessons - Exercises - Go straight
This is another exercise that will help You to make a program for RCJ Rescue Maze or Line. For example, when a gap in line detected, You may want the robot to go straight ahead precisely.
Task: go straight ahead.
Program the robot to go straight ahead. A hint: the following program is not a solution:
void RobotLine::loop() {
go(50, 50);
}
You may ask why, as both motors spin at the same speed. The problem is they don't. They are not the same. One side will rotate faster and the robot will veer off course.
Solution
void RobotLine::loop() {
static int direction;
if (setup())
direction = (int)heading();
if (direction - heading() < 0)
go(40, 60);
else
go(60, 40);
}
This is much better. First, an integer variable "direction" is declared. In the first run, it immediately stores the value of the current course. In every pass the second "if" determines if the robot goes too much left or right and corrects the direction. Do we have a subtle logic flaw here? We do. Consider the case where initial course is very small, let's say 0 or 1° and note that the compass shows values between 0 and 360° - no negatives.
In the solution we avoided decimal numbers to postpone learning them.