📖 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
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
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
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
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.
Practice
(1/5)
1. What does the DistanceSensor measure using ultrasonic waves?
easy
A. The speed of sound in water
B. The temperature of the air
C. The distance to an object without touching it
D. The brightness of a light source
Solution
Step 1: Understand the sensor's purpose
The DistanceSensor uses sound waves to detect how far an object is without physical contact.
Step 2: Identify the correct measurement type
It measures distance, not temperature, speed, or brightness.
Final Answer:
The distance to an object without touching it -> Option C
Quick Check:
DistanceSensor measures distance = C [OK]
Hint: Remember: ultrasonic means measuring distance by sound [OK]
Common Mistakes:
Confusing distance with temperature
Thinking it measures speed or light
Assuming physical contact is needed
2. Which of the following is the correct way to create a DistanceSensor object in Python on Raspberry Pi?
easy
A. sensor = DistanceSensor(trigger=17, echo=4)
B. sensor = DistanceSensor(echo=17, trigger=4)
C. sensor = DistanceSensor(4, 17)
D. sensor = DistanceSensor(echo=4, trigger=17)
Solution
Step 1: Recall parameter names for DistanceSensor
The DistanceSensor constructor expects named parameters: echo and trigger pins.
Step 2: Match correct pin assignments
sensor = DistanceSensor(echo=17, trigger=4) correctly assigns echo=17 and trigger=4 as named arguments.
Final Answer:
sensor = DistanceSensor(echo=17, trigger=4) -> Option B
Quick Check:
Use named pins echo=17, trigger=4 = A [OK]
Hint: Use named arguments echo and trigger in correct order [OK]
Common Mistakes:
Swapping echo and trigger pins
Passing pins without names
Using wrong pin numbers
3. What will the following code print if the sensor measures 0.25 meters?
The echo pin should be connected to the sensor's echo pin, trigger to trigger pin. Usually, echo=17 and trigger=4 is standard, so swapping is likely wrong.
Step 2: Verify other code parts
Import is correct, sensor.distance returns meters (not centimeters), and print syntax is valid.
Final Answer:
Echo and trigger pins are swapped -> Option A
Quick Check:
Pin swap error = D [OK]
Hint: Echo pin usually higher number than trigger [OK]
Common Mistakes:
Confusing echo and trigger pins
Assuming distance returns centimeters
Forgetting to import gpiozero
5. You want to measure distance in centimeters and print only integer values every second. Which code snippet correctly does this using DistanceSensor?
hard
A. from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=17, trigger=4)
while True:
print(sensor.distance)
time.sleep(1)
B. from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=17, trigger=4)
print(round(sensor.distance))
C. from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=4, trigger=17)
while True:
print(sensor.distance * 100)
time.sleep(1)
D. from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=17, trigger=4)
while True:
print(int(sensor.distance * 100))
time.sleep(1)
Solution
Step 1: Check pin assignments and imports
from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=17, trigger=4)
while True:
print(int(sensor.distance * 100))
time.sleep(1) correctly imports time, sets echo=17 and trigger=4, which is standard.
Step 2: Verify distance calculation and printing
It multiplies sensor.distance (meters) by 100 to get centimeters, converts to int for integer output, and prints every second with time.sleep(1).
Step 3: Compare with other options
from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=17, trigger=4)
print(round(sensor.distance)) prints once and rounds meters, not centimeters. from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=4, trigger=17)
while True:
print(sensor.distance * 100)
time.sleep(1) swaps pins and prints float centimeters. from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=17, trigger=4)
while True:
print(sensor.distance)
time.sleep(1) prints meters, not centimeters.
Final Answer:
from gpiozero import DistanceSensor
import time
sensor = DistanceSensor(echo=17, trigger=4)
while True:
print(int(sensor.distance * 100))
time.sleep(1) -> Option D
Quick Check:
Correct pins, int centimeters, 1-second delay = A [OK]
Hint: Multiply by 100, convert to int, use sleep(1) for timing [OK]
Common Mistakes:
Swapping echo and trigger pins
Not converting meters to centimeters
Printing only once instead of every second
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.