0

Line Robot - Basic lessons - Do it once

Again, we learned that loop() function runs forever. Sometimes, this behaviour is desirable, sometimes not. If we want to do something once, we already learned how:
void RobotLine::loop() {
	print("Only once");
	end();
}
We showed You a very similar example already. The program will print "Only once!", find "end()", therefore breaking execution and no more text will be displayed. That was easy. Now consider a task that must be repeated great many times, but that has to do something only in the first run. This paradigm is extremely common. Before doing some job, You need to reset some counters, set initial values, etc. The "end" solution is no good anymore. We cannot stop the program. To help You with this problem, a command exists, and is called setup(). Its job is to execute the command next only once, during the first run. Therefore, this program will solve the problem:
void RobotLine::loop() {
	if (setup())
		print("First\n\r");
	print("Other\n\r");
}
Next command will be only the next line here, "print...".

The result will be:
First
Other
Other
Other
...
In other words, "setup()" will evaluate "true" only during the first run of the function it resides within (here: loop()). Already in the second pass, it will evaluate "false", so the next command will no more execute.

Task: start motors once

Write a program that starts the motors only once, instead in each pass of the program. Base Your code on previous example:

void RobotLine::loop() {
	go(50, 50);
}

Note for advanced beginners

If You ever programmed Arduino, You probably noticed that 2 functions exist there:
// Global variables
...
void setup(){
}

void loop(){
}
Functionally, this is quite similar to our concept. Arduino setup() is like out setup(), loop() is analog to loop(). In a later lesson You will see that there is a solution for global variables.