0

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.