Soccer Robot C - Basic lessons - Exercises - Go straight
This is an exercise that will help You to make a program for RCJ Soccer competition.
Task: go straight ahead.
Program the robot to go straight ahead. A hint: the following program is not a solution:
void RobotSoccer::loop() {
go(50, 0);
}
You may ask why, as all the motors spin at the same speed. The problem is they don't. They are not the same. Some of them will rotate faster and the robot will veer off course.
Solution
void RobotSoccer::loop() {
static int direction;
if (setup())
direction = (int)heading();
if (direction - heading() < 0)
go(50, -5);
else
go(50, 5);
}
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.