In this lesson, we will study how to use the ultrasonic module on the car. The ultrasonic module transmits the ultrasonic wave and reflects it back after encountering the object. The module receives the reflected wave and judges the distance of the object in front by calculating the time difference between sending and receiving.
After create a new project and click Create variable in the Variables category to create two variables named reference and disVal.
Click on the Simulation icon on the left side of the page to go to the Simulation page.
Drag the Ultrasonic module to the right area as shown.
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.
Place a set disVal to block in Start block, then click the drop-down box and change the disVal to reference. Add a number 0 block from Math category, and change the value to 10.
Drag a set disVal to block under the Variables category into the Forever block.
Add the Ultrasonic module block to the end of set disVal to block to assign the read value of ultrasonic to the variable, disVal. Print the value of disVal with a print block.
Click on Logic category, then drag an if do block to below the set disVal to block; besides, add a Comparison Operator ( = ) block and change the equal sign to less than sign.
Place the disVal block in the Variables category to the left of the < block and the reference block to the right so as to judge if obstacles are found in the front 10cm.
Place a print block after do and input “Alarm!”. When the read value of the sensor is less than the reference, the debug monitor will print “Alarm!”.
Save the project and flash it into the Raspberry Pi (refer to lesson 0 for details). Place an obstacle in front of the PiMobile and move the obstacle in the direction of the car. When the distance is less than 10cm, you can see the print information on Debug Monitor.