0

Line Robot - Basic lessons - Function example

Functions' most important use is for reducing repetitive parts of the program. Instead of writing 10 identical, or quite similar, lines of code in 5 different places, write them once, in a function, and call that function 5 times. Other usage is for making program clearer. Consider this code fragment:
void RobotLine::loop() {
	...
	if (mrm_lid_can_b->reading(0) < 100)
	...
}
"..." denotes some other instructions, but they are not important now. It is not obvious what we are trying to compare to 100 here. Even if we are familiar with "mrm_lid_can_b" and its function "reading()", there is still parameter "0" and we may not know which sensor it is. Now, another version of the same program:
void RobotLine::loop() {
	...
	if (leftFront() < 100)
	...
}
It looks much better, doesn't it? It is reasonably clear that we are comparing distance on the left, looking from front of the robot, to 100. frontLeft() is already an existing function:
uint16_t RobotLine::frontLeft() {
	return mrm_lid_can_b->reading(0);
}
The technical details of the implementation, like lidar's name and sensor's ordinal number are hidden inside the function. You can use any of the predefined functions for lidars:
  • frontLeft()
  • frontRight()
  • rearLeft()
  • rearRight()
However, You should first check if they use the sensors that correspond to sensors You built Your robot with. If not, change functions' definitions.

Task: stop when any wall found.

Write a function that will drive the robot ahead and stop it if any side wall detected.