Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
2.13 Ultrasonic Sensor Module
Introduction
The ultrasonic sensor module uses ultrasonic waves to measure distances with remarkable accuracy. It emits ultrasonic waves and listens for their echo, calculating the distance based on the time taken for the echo to return. This versatile technology is commonly used in robotics, obstacle detection, and range-finding applications.
What You’ll Need
Here are the components required for this project:
COMPONENT INTRODUCTION |
PURCHASE LINK |
|---|---|
- |
|
Raspberry Pi |
- |
Circuit Diagram
Below is the schematic diagram for the ultrasonic sensor module:
Wiring Diagram
Assemble the circuit as shown in the diagram below:
Ensure the connections are secure, with the Echo pin connected to GPIO 22 and the Trigger pin to GPIO 27 of the Raspberry Pi.
Running the Example
All example code used in this tutorial is available in the ai-lab-kit directory.
Follow these steps to run the example:
cd ~/ai-lab-kit/python/
sudo python3 2.13_Ultrasonic.py
This Python script uses an ultrasonic distance sensor to measure the distance to an object and displays the result on the console. When executed:
The sensor, connected to GPIO pins 27 (trigger) and 22 (echo), continuously measures the distance to the nearest object.
The distance is calculated in meters and converted to centimeters, then displayed in the format:
Distance: <value> cmwith two decimal places of precision.The distance is updated every 0.3 seconds, allowing for near real-time monitoring.
The program runs indefinitely until interrupted with
Ctrl+C, at which point it exits gracefully.
Code
Below is the Python code for this project:
# Import Ultrasonic and Pin class
from fusion_hat.modules import Ultrasonic
from fusion_hat.pin import Pin
from time import sleep
# Create Ultrasonic object
sensor = Ultrasonic(Pin(27), Pin(22))
try:
# Main loop to continuously measure and report distance
while True:
dis = sensor.read() # Measure distance in centimeters
print('Distance: {:.2f} cm'.format(dis)) # Print the distance with two decimal precision
sleep(0.3) # Wait for 0.3 seconds before the next measurement
except KeyboardInterrupt:
# Handle KeyboardInterrupt (Ctrl+C) to gracefully exit the loop
pass
Understanding the Code
Imports:
from fusion_hat.modules import Ultrasonic from fusion_hat.pin import Pin from time import sleep
The script imports the
Ultrasonicclass from thefusion_hatlibrary to interact with the ultrasonic sensor and thesleepfunction from thetimemodule to introduce delays.Initialization:
sensor = Ultrasonic(Pin(27), Pin(22))
The ultrasonic sensor is initialized with the Echo pin connected to GPIO 22 and the Trigger pin to GPIO 27. This setup enables the Raspberry Pi to send and receive ultrasonic signals.
Main Loop:
while True: dis = sensor.read() # Measure distance in centimeters print('Distance: {:.2f} cm'.format(dis)) # Print the distance with two decimal precision sleep(0.3) # Wait for 0.3 seconds before the next measurement
Continuously measures the distance to the nearest object.
Converts the distance from meters to centimeters.
Prints the distance with two decimal places of precision.
Includes a 0.3-second delay to allow the sensor to stabilize between measurements.
Graceful Exit:
The
try-exceptblock ensures the program exits cleanly when interrupted withCtrl+C.except KeyboardInterrupt: pass
Troubleshooting
No Distance Output:
Cause: The sensor is not properly connected or powered.
Solution:
Ensure the trigger pin is connected to GPIO 27 and the echo pin to GPIO 22.
Verify that the sensor has a stable power supply.
Constant or Incorrect Distance Values:
Cause: Obstacles are too close or too far from the sensor, or there is interference.
Solution:
Ensure the object is within the sensor’s effective range (typically 2 cm to 400 cm).
Check for interference from other ultrasonic devices or reflective surfaces.
Distance Always Zero:
Cause: Faulty sensor or incorrect wiring.
Solution: Test the sensor on another GPIO setup or replace it if faulty. Double-check the wiring configuration.
Extendable Ideas
Threshold-Based Alerts: Trigger an alert when the measured distance is below a specific threshold:
if dis < 10: print("Warning: Object too close!")
Auditory Feedback: Add a buzzer that sounds when the distance is below a threshold:
from fusion_hat import Buzzer buzzer = Buzzer(Pin(4)) if dis < 10: buzzer.on() else: buzzer.off()
Conclusion
This project demonstrates how to use an ultrasonic sensor module to measure distances with a Raspberry Pi. By understanding the principles of ultrasonic wave detection and GPIO programming, you can integrate such sensors into a variety of applications, from robotics to home automation. With this foundation, you can explore more advanced projects involving sensors and real-world interaction.