Soccer Robot C - Basic lessons - Exercises - Stop on any line
Another exercise inspired by RCJ Soccer.
Task: if any transistor detects line, stop the robot.
Start the robot in direction of 137°. Do not allow it rotate about vertical axis. As soon as any transistor detects a white line, stop the robot. The code to maintain rotational position is here.
void RobotSoccer::loop() {
static int initialDirection;
if (setup())
initialDirection = heading();
int error = heading() - initialDirection;
go(0, 0, error);
}
Solution
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();
}
- The part before "any" declaration we know already.
- Variable "any" is declared and will later be set to "true" as soon as a white line is detected.
- 2 nested loops follow. So, for every value of "sensor" variable (sensor's ordinal number, 0 to 3), we will try every transistors (6 of them for front sensor and 8 for the rest).
- End condition is not the one we used by now. Instead of just comparing the counter variable to a number, we have a more complex expression, with "&& !any" part. But, that's OK. Here we can put any logical expression. It just means: end the loop when the counter exceeds the limit value or when a white stripe has been detected already. The purpose is not to continue searching for a white line if we've already detected one.
- Next, "if". Because it is in a nested loop, every combination of "transistor" - "sensor" will be tested. The anomaly here is that sensor 0 (front one) doesn't feature 8 transistors, but just 6. Therefore, we mustn't test the 2 missing transistors and that is what "&& (sensor != 0 || transistor < 6)" assures. If "sensor" is not 0, the expression will be "true", so all 8 transistors will be tested. However, for sensor 0, "sensor!=0" will be "false", so "transistor < 6" must be true and that is just what we wanted.
- The last "if" ends the program if "any" is "true", thus any white stripe detected.