Line Robot - Basic lessons - Curly brackets
Curly brackets, "{" and "}", enclose a block of instructions. For example, "if (expression)" command will execute the next instruction, if expression evaluates true. What if we want 2 or more instructions to execute instead of one? We will put a block right after "if". For example, let's assume that the robot was already moving, before entering function loop(). When the first transistor of MRMS reflectance sensors 9x, CAN, analog, I2C detects black surface, we may want to stop the motors
and end the function. This is the way to accomplish the task:
void RobotLine::loop() {
if (line(0)){
stop();
end();
}
}
Task: determine scope
The same assumption as above: the robot is already going ahead, right now transistor 0 doesn't detect black, and we want to stop it when the transistor 0 detects black. How long will it travel if loop() looks like this?
void RobotLine::loop() {
if (line(0))
stop();
end();
}
Solution
It will continue running till the battery runs out of power. Tabs don't mean anything to C++ (if You do not like this, switch to Python language). You can put as many of them as You like, if one is already present. Therefore, the program above is equivalent to this one (one tab deleted):
void RobotLine::loop() {
if (line(0))
stop();
end();
}
Interpretation: in the first run transistor 0 doesn't detect black (assumption), so if will not evaluate "true" and motors will not stop. However, this was their very last chance to do so as the next command is not a part of the block that is next to "if" and will always execute. loop() will exit, never to run again, and the motors will have no second chance to stop.