Exercise: HC-SR04

5.15. Exercise: HC-SR04#

Instructions

  1. Read the case study on Case Study: HC-SR04 Ultrasonic Sensor.

Question 1

Answer the following:

  • Draw the pin states over time when a measurement is triggered.

You may wish to draw over the blank plots provided below.

../../_images/exercise_hcsr04_q1_blank-7c855608b0e80938.png
Solution
../../_images/exercise_hcsr04_q1-bc4ac8e38254d362.png
Question 2

Answer the following:

  • Create a wiring diagram of the sensor connected to your microcontroller using Wokwi.

Solution

Solution is locked

Question 3

Answer the following:

  • Annotate the provided MicroPython code to match the steps outlined on the case study.

Note

The code provided is for the micro:Maqueen robot. You may need to adjust the pins used for your particular robot.

import utime

def ultrasound_measure():
    pin1.write_digital(1)
    utime.sleep_us(10)
    pin1.write_digital(0)

    timeout = utime.ticks_us()
    while True:
        pulseBegin = utime.ticks_us()
        if 1 == pin2.read_digital():
            break
        if (pulseBegin - timeout) > 5000:
            return -1  # error: no echo start detected

    while True:
        pulseEnd = utime.ticks_us()
        if 0 == pin2.read_digital():
            break
        if (pulseEnd - pulseBegin) > 5000:
            return -2  # error: echo too long (timeout)

    x = pulseEnd - pulseBegin   # time in µs
    d = x * 0.01715             # distance in cm
    return int(d)

while True:
    dist = ultrasound_measure()
    if dist >= 0: # only process valid readings
        print(dist)
        sleep(100)
Solution

Solution is locked

Question 4

The measurements from the HC-SR04 can be noisy.

Extend the code so that:

  • the distance is smoothed using a moving average

  • small changes are suppressed with deadband

Solution

Solution is locked