In this lesson, we will learn how to program the car to avoid objects in front of it automatically.
After creating the project, create 3 variables named disVal, reference and speed.
Click the Simulation icon on the left to enter the Simulation page.
In module category, drag Ultrasonic module to the right area.
Connect Trig pin of Ultrasonic module to D0 port, Echo pin to D1 port, and connect VCC and GND to 3.3V and GND of Robot HAT respectively.
Return to Programming page, then assign the speed value to 35 in the Start block, and the reference value to 10.
Put set disVal to block in Forever block, followed by Ultrasonic module block in Modules category. Assign the read value of the ultrasonic sensor to the variable, disVal.
Place an if do block under set disVal to block and add the else if block in the setting icon.
A condition is set up in if block to judge whether disVal ≥ reference(10 cm).
If disVal ≥ reference, set the speed of Motor1 and Motor2 as speed in do, that is, the car continues to move forward.
Continue to set conditions in else if to judge if disVal < reference.
If disVal < reference is met, or if obstacles are encountered in front, the car will move backward.
Place a delay block below, and change the value to 500 to let the car move back for 500 ms.
Then let the car turn left to avoid obstacles for 200 ms.
Save and flash the project into Raspberry Pi. An obstacle is placed in front of the car. The car moves forward, when the obstacle is less than 10cm, the car will successively first move backward then turn left to avoid the obstacle, otherwise continue to advance.