Introduction
In this lesson, we will learn how to program the car to avoid objects in front of it automatically.
Programming Steps
Step 1
After creating the project, create 3 variables named disVal, reference and speed.
Step 2
Click the Simulation icon on the left to enter the Simulation page.
Step 3
In module category, drag Ultrasonic module to the right area.
Step 4
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.
Step 5
Return to Programming page, then assign the speed value to 35 in the Start block, and the reference value to 10.
Step 6
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.
Step 7
Place an if do block under set disVal to block and add the else if block in the setting icon.
Step 8
A condition is set up in if block to judge whether disVal ≥ reference(10 cm).
Step 9
If disVal ≥ reference, set the speed of Motor1 and Motor2 as speed in do, that is, the car continues to move forward.
Step 10
Continue to set conditions in else if to judge if disVal < reference.
Step 11
If disVal < reference is met, or if obstacles are encountered in front, the car will move backward.
Step 12
Place a delay block below, and change the value to 500 to let the car move back for 500 ms.
Step 13
Then let the car turn left to avoid obstacles for 200 ms.
Step 14
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.