0
0
Raspberry Piprogramming~30 mins

DistanceSensor (ultrasonic) in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
DistanceSensor (ultrasonic) with Raspberry Pi
📖 Scenario: You have a Raspberry Pi connected to an ultrasonic distance sensor. This sensor can measure how far an object is by sending sound waves and timing how long they take to bounce back.We want to write a simple program that reads the distance from the sensor and shows it on the screen.
🎯 Goal: Build a Python program that reads distance values from an ultrasonic sensor connected to the Raspberry Pi and prints the distance in centimeters.
📋 What You'll Learn
Create variables for the sensor pins
Set up the GPIO pins for input and output
Write code to send a pulse and measure the echo time
Calculate the distance from the echo time
Print the distance in centimeters
💡 Why This Matters
🌍 Real World
Ultrasonic sensors are used in robots, parking sensors, and obstacle detection to measure how far objects are.
💼 Career
Understanding how to read sensors and control hardware with code is important for jobs in robotics, embedded systems, and IoT development.
Progress0 / 4 steps
1
Set up GPIO pins for the ultrasonic sensor
Import the RPi.GPIO module as GPIO and the time module. Then create two variables called TRIG and ECHO and set them to 23 and 24 respectively. Finally, set the GPIO mode to GPIO.BCM.
Raspberry Pi
Need a hint?

Use import to bring in modules. Assign numbers 23 and 24 to TRIG and ECHO. Use GPIO.setmode(GPIO.BCM) to set pin numbering.

2
Configure GPIO pins for output and input
Use GPIO.setup to set the TRIG pin as an output and the ECHO pin as an input.
Raspberry Pi
Need a hint?

Use GPIO.setup(pin, GPIO.OUT) for output pins and GPIO.setup(pin, GPIO.IN) for input pins.

3
Send pulse and measure echo time
Write code to send a 10 microsecond pulse on the TRIG pin. Then use a while loop to wait until the ECHO pin goes high and record the start time. Use another while loop to wait until the ECHO pin goes low and record the end time. Calculate the pulse duration as end - start.
Raspberry Pi
Need a hint?

Set TRIG low, wait, then high for 10 microseconds, then low again. Use loops to detect when ECHO changes state and record times.

4
Calculate and print the distance
Calculate the distance in centimeters by multiplying pulse_duration by 17150. Then print the distance rounded to 2 decimal places using print(f"Distance: {distance:.2f} cm"). Finally, clean up the GPIO pins with GPIO.cleanup().
Raspberry Pi
Need a hint?

Multiply the pulse duration by 17150 to get centimeters. Use an f-string to print with 2 decimals. Always clean up GPIO pins at the end.