It often happens that you want to react to different inputs with the same output. In the following example we react to the detection of an obstacle by the left obstacle sensor as well as by the right obstacle sensor, with repeated switching on and off of the headlights every second.
However, this can quickly become confusing. If we need certain processes more than once, we can outsource them to so-called functions.
In principle, functions consist of two parts. The function head and the function body. The function name is first defined in the header. The function body then contains all instruction blocks to be executed with this function.
The function can then be called in the main program flow. Each time the function is called, all instructions that we have previously added to the function body are executed.
In the following example we have outsourced the light change to the function "light_sequence". This way we can reuse the sequence both when the left obstacle sensor detects the light and when the right obstacle sensor detects the light. This not only guarantees that the same blocks are executed in both cases, but also makes our "forever" block much clearer!
Optionally, functions can also provide so-called return values. In this case the function returns an answer every time it is called. This return value, i.e. the answer, can be determined within the function. For example, calculations can be done here and the result can be returned to the main function.
In the next example we create the function "sonar_sensor". This function checks the ultrasonic sensor as soon as it is called and returns either a 0, a 1, or a 2 back to the main function, depending on the distance value the sensor returns. Depending on the delivered value we switch the headlights and the hazard lights of the joy car into different states.