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
class UltrasonicSensor:
def __init__(self, trig_pin, echo_pin):
self.trig_pin = trig_pin
self.echo_pin = echo_pin
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
def get_distance(self):
# Trigger pulse
GPIO.output(self.trig_pin, True)
time.sleep(0.00001)
GPIO.output(self.trig_pin, False)
# Wait for echo start
while GPIO.input(self.echo_pin) == 0:
pulse_start = time.time()
# Wait for echo end
while GPIO.input(self.echo_pin) == 1:
pulse_end = time.time()
# Calculate pulse duration
pulse_duration = pulse_end - pulse_start
# Speed of sound is approximately 343m/s
# Distance = time * speed
distance = pulse_duration * 34300 / 2
return distance
class MovingAverageFilter:
def __init__(self, window_size):
self.window_size = window_size
self.data = []
def add_data(self, value):
if len(self.data) < self.window_size:
self.data.append(value)
else:
self.data.pop(0)
self.data.append(value)
def get_filtered_value(self):
return sum(self.data) / len(self.data)
# GPIO Pins (example pins, adjust as per your connections)
TRIG_PIN = 23
ECHO_PIN = 24
# Initialize GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Initialize Ultrasonic Sensor and Moving Average Filter
ultrasonic_sensor = UltrasonicSensor(TRIG_PIN, ECHO_PIN)
moving_average_filter = MovingAverageFilter(window_size=5)
try:
while True:
# Measure distance
distance = ultrasonic_sensor.get_distance()
# Add distance data to the moving average filter
moving_average_filter.add_data(distance)
# Get filtered distance
filtered_distance = moving_average_filter.get_filtered_value()
print("Distance: {:.2f} cm | Filtered Distance: {:.2f} cm".format(distance, filtered_distance))
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()