Bird
Raised Fist0
Raspberry Piprogramming~10 mins

DistanceSensor (ultrasonic) in Raspberry Pi - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - DistanceSensor (ultrasonic)
Start
↓
Send Trigger Pulse
↓
Wait for Echo Start
↓
Wait for Echo End
↓
Calculate Duration
↓
Calculate Distance
↓
Output Distance
↓
End
The sensor sends a pulse, waits for the echo, measures the time, then calculates and outputs the distance.
Execution Sample
Raspberry Pi
from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=17, trigger=4)
print(sensor.distance * 100)
This code measures distance using an ultrasonic sensor and prints it in centimeters.
Execution Table
StepActionSignal StateTime Measured (s)Distance Calculated (cm)Output
1Send trigger pulse (10µs HIGH)Trigger HIGH
2Wait for echo to go HIGHEcho LOW to HIGH
3Start timing echo pulseEcho HIGH
4Wait for echo to go LOWEcho HIGH to LOW0.015
5Calculate duration0.015
6Calculate distance (duration * 34300 / 2)257.25
7Output distance257.25257.25 cm
8End measurement cycleMeasurement complete
💡 Measurement ends after echo pulse duration is measured and distance is calculated.
Variable Tracker
VariableStartAfter Step 4After Step 6Final
triggerLOWHIGH (10µs pulse)LOWLOW
echoLOWHIGH (echo start)LOW (echo end)LOW
duration00.0150.0150.015
distance00257.25257.25
Key Moments - 3 Insights
Why do we wait for the echo signal to go HIGH and then LOW?
Because the time between echo HIGH and LOW is the pulse duration that tells us how long the sound took to return, as shown in steps 3 and 4 in the execution_table.
Why do we multiply duration by 34300 and then divide by 2 to get distance?
34300 cm/s is the speed of sound. We multiply by duration to get total travel distance and divide by 2 because the sound travels to the object and back, explained in step 6.
What happens if the echo signal never goes LOW?
The measurement would hang waiting for echo end, so the program must handle timeouts to avoid infinite wait, which is not shown here but important in real use.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'duration' after step 4?
A0 seconds
B0.015 seconds
C10 microseconds
D257.25 centimeters
💡 Hint
Check the 'Time Measured (s)' column at step 4 in the execution_table.
At which step is the distance actually calculated?
AStep 6
BStep 5
CStep 3
DStep 7
💡 Hint
Look at the 'Distance Calculated (cm)' column in the execution_table.
If the echo pulse duration doubles, how does the distance change?
ADistance stays the same
BDistance halves
CDistance doubles
DDistance quadruples
💡 Hint
Refer to the formula in step 6: distance is proportional to duration.
Concept Snapshot
DistanceSensor (ultrasonic) measures distance by:
- Sending a short trigger pulse
- Measuring echo pulse duration
- Calculating distance = (duration * speed_of_sound) / 2
- Outputting distance in cm
Use gpiozero library on Raspberry Pi for easy access.
Full Transcript
This visual trace shows how an ultrasonic DistanceSensor works on Raspberry Pi. First, the sensor sends a short trigger pulse. Then it waits for the echo signal to go HIGH, marking the start of the echo pulse. It times how long the echo stays HIGH until it goes LOW again. This duration is the time sound took to travel to the object and back. Using the speed of sound (34300 cm/s), the program calculates distance by multiplying duration by speed and dividing by two. Finally, it outputs the distance in centimeters. Variables like trigger and echo signals change state during the process. Key moments include understanding why we wait for echo HIGH and LOW, the distance formula, and handling echo timeouts. The quizzes test understanding of timing, calculation steps, and proportionality of distance to duration.

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

  1. Step 1: Understand the sensor's purpose

    The DistanceSensor uses sound waves to detect how far an object is without physical contact.
  2. Step 2: Identify the correct measurement type

    It measures distance, not temperature, speed, or brightness.
  3. Final Answer:

    The distance to an object without touching it -> Option C
  4. 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

  1. Step 1: Recall parameter names for DistanceSensor

    The DistanceSensor constructor expects named parameters: echo and trigger pins.
  2. Step 2: Match correct pin assignments

    sensor = DistanceSensor(echo=17, trigger=4) correctly assigns echo=17 and trigger=4 as named arguments.
  3. Final Answer:

    sensor = DistanceSensor(echo=17, trigger=4) -> Option B
  4. 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?
from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=17, trigger=4)
distance_cm = sensor.distance * 100
print(round(distance_cm))
medium
A. 25
B. 0.25
C. 250
D. 2.5

Solution

  1. Step 1: Understand sensor.distance value

    The sensor.distance returns distance in meters as a float, here 0.25 meters.
  2. Step 2: Convert meters to centimeters and round

    Multiplying 0.25 by 100 gives 25 centimeters, then rounding keeps it 25.
  3. Final Answer:

    25 -> Option A
  4. Quick Check:

    0.25 m * 100 = 25 cm [OK]
Hint: Multiply meters by 100 to get centimeters [OK]
Common Mistakes:
  • Printing meters instead of centimeters
  • Multiplying by 1000 instead of 100
  • Not rounding the result
4. Identify the error in this code snippet using DistanceSensor:
from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=4, trigger=17)
print(sensor.distance * 100)
medium
A. Echo and trigger pins are swapped
B. Missing import statement
C. sensor.distance returns centimeters directly
D. Print statement syntax error

Solution

  1. Step 1: Check pin assignments

    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.
  2. Step 2: Verify other code parts

    Import is correct, sensor.distance returns meters (not centimeters), and print syntax is valid.
  3. Final Answer:

    Echo and trigger pins are swapped -> Option A
  4. 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

  1. 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.
  2. 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).
  3. 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.
  4. 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
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard