Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

import RPi.GPIO as GPIO import time from collections import deque # GPIO Pins TRIG_PIN = 23 # GPIO pin connected to the Trigger pin of the sensor ECHO_PIN = 24 # GPIO pin connected to the Echo pin of the sensor # Moving Average Filter Parameters WINDOW_SIZE = 5 # Number of readings for the moving average filter def setup_gpio(): GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) GPIO.output(TRIG_PIN, GPIO.LOW) time.sleep(2) def measure_distance(): """Measure distance using the ultrasonic sensor.""" # Send a 10µs pulse to trigger the sensor GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) # Measure the time for echo signal while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() # Calculate distance in centimeters pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 # Speed of sound (34300 cm/s) / 2 return round(distance, 2) def moving_average_filter(data_queue, new_value): """Apply a moving average filter to the sensor data.""" if len(data_queue) >= WINDOW_SIZE: data_queue.popleft() data_queue.append(new_value) return sum(data_queue) / len(data_queue) def main(): setup_gpio() data_queue = deque(maxlen=WINDOW_SIZE) # Queue to hold sensor readings for the filter try: while True: raw_distance = measure_distance() smoothed_distance = moving_average_filter(data_queue, raw_distance) print(f"Raw Distance: {raw_distance} cm, Smoothed Distance: {smoothed_distance:.2f} cm") time.sleep(0.1) # Delay between readings except KeyboardInterrupt: print("Measurement stopped by user.") finally: GPIO.cleanup() if __name__ == "__main__": main()

Explanation:

  1. Setup GPIO:

    • Configure the GPIO pins for the trigger and echo of the ultrasonic sensor.
    • Initialize the pins to the appropriate state.
  2. Measure Distance:

    • Send a short pulse (10 µs) to the trigger pin.
    • Measure the duration of the echo signal and calculate the distance using the formula Distance = (Pulse Duration * Speed of Sound) / 2.
  3. Moving Average Filter:

    • Use a deque with a fixed length (WINDOW_SIZE) to store the last few readings.
    • Compute the average of the values in the deque to smooth the sensor data.
  4. Main Loop:

    • Continuously measure the distance, apply the moving average filter, and print the results.
    • Use a try-except block to handle user interruptions gracefully.
  5. Cleanup:

    • Ensure the GPIO pins are reset to avoid warnings or errors during subsequent runs.

Notes:

  • Dependencies: Install the RPi.GPIO library for Raspberry Pi GPIO control. You can do this via pip install RPi.GPIO.
  • Accuracy: Ensure there is no obstruction around the sensor and the target object is within the sensor's range (2 cm to ~300 cm).
  • Power Supply: Use a reliable power source for the sensor and microcontroller
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.