Soccer Robot C - Basic lessons - While
"While" is one of 2 loops in C++. The other one, "for", we already know. It has even a simpler form. For example:
void RobotSoccer::loop() {
static uint32_t startMs = millis();
while(millis() - startMs < 10000)
print("%i\n\r", millis());
}
First line declares a variable that will be retained between successive executions of loop(), named "startMs", which immediately stores number of milliseconds since microcontroller power-up. Now, "while": in the brackets is a logical expression (evaluates either true or false). As long as it is true (for 10 sec.), the next instruction will execute, printing milliseconds.
Can You find a subtle error in the code? Hint: it will run only once. If You try to execute it the second time, nothing will be displayed. Here is the corrected version:
void RobotSoccer::loop() {
static uint32_t startMs;
if (setup())
startMs = millis();
while(millis() - startMs < 1000)
print("%i\n\r", millis());
}
The previous one initialized "startMs" only when loop() started the first time.
Note that this task could have been programmed without "while".
Task: go - stop - go.
Let the robot go straight ahead. When Your hand interrupts the barrier, the robot should stop. When you remove it, the robot should continue going ahead.
Solution
void RobotSoccer::loop() {
if (setup())
go(50, 0);
if (analogRead(35) < 500){
stop();
while(analogRead(35) < 500)
;
go(50, 0);
}
}
If the barrier is interrupted, the robot stops and enters "while" loop that does nothing (empty statement, ";", does nothing). However it pauses program execution and the robot stays put. When You remove the hand, "while" exits and the motors restart.
Note that in fact this is a bad programming example. As long as the program execution is captured in the "while" loop, all the other actions are prevented, including CAN Bus messages' exchange. It works only because we used a simple sensor that doesn't depend on the CAN Bus, but just returns analog values.