Soccer Robot C - Basic lessons - Exercises - Bounce off the lines
Another exercise for Robocup Junior Soccer.
Task: bounce the robot off any white line.
Start the robot in heading -15°. When it detects a white stripe, it has to change the direction by 180°. The purpose is not to allow it to cross playfield boundaries. Base Your program on previous exercise:
void RobotSoccer::loop() {
static int initialDirection;
if (setup())
initialDirection = heading();
int error = heading() - initialDirection;
go(50, 137, error);
bool any = false;
for (int sensor = 0; sensor < 4 && !any; sensor++)
for (int transistor = 0; transistor < 8 && !any; transistor++)
if (line(transistor, sensor) && (sensor != 0 || transistor < 6))
any = true;
if (any)
end();
}
Solution
void RobotSoccer::loop() {
static int initialDirection;
static int currentHeading = -15;
if (setup())
initialDirection = heading();
int error = heading() - initialDirection;
go(50, currentHeading, error);
int heading = 999;
for (int sensor = 0; sensor < 4 && heading == 999; sensor++)
for (int transistor = 0; transistor < 8 && heading == 999; transistor++)
if (line(transistor, sensor) && (sensor != 0 || transistor < 4))
currentHeading = (heading() < 180 ? heading() + 180 : heading() -180);
}
- A new static variable is introduced, "currentHeading", because it is no more constant.
- Nested loops and the inner "if" are the same.
- The only difference is that the instruction following "if" changes robot's direction and it will return in the direction it came from.
- Shorthand "if" in the previous statement will keep the angle within 0-360° limits.
Note that it will not exactly bounce of the line, but only change the direction by 180°. You can also implement either proper bouncing or, even better, returning orthogonal to the boundary. This will still not be the best strategy keeping the robot out of out-area, but it will be enough for now.