0

Soccer Robot C - 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 RobotSoccer::loop() {
	...
	if (mrm_lid_can_b2->reading(3) < 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_lida_can_b2" 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 RobotSoccer::loop() {
	...
	if (left() < 100)
	...
}
It looks much better, doesn't it? It is reasonably clear that we are comparing distance on the left to 100. left() is already an existing function:
uint16_t RobotSoccer::left() {
	return mrm_lid_can_b2->reading(3);
}
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:
  • left()
  • right()
  • rear()
  • front()
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.