from machine import Pin, time_pulse_us
import utime
# Define GPIO pins for Bin 1 (First sensor)
TRIG1 = Pin(15, Pin.OUT) # Trigger pin for Bin 1 (Pin 21)
ECHO1 = Pin(14, Pin.IN) # Echo pin for Bin 1 (Pin 19)
# Define GPIO pins for Bin 2 (Second sensor)
TRIG2 = Pin(16, Pin.OUT) # Trigger pin for Bin 2 (Pin 22)
ECHO2 = Pin(17, Pin.IN) # Echo pin for Bin 2 (Pin 22)
# Define GPIO pins for Bin 3 (Third sensor)
TRIG3 = Pin(18, Pin.OUT) # Trigger pin for Bin 3 (Pin 24)
ECHO3 = Pin(19, Pin.IN) # Echo pin for Bin 3 (Pin 25)
# Setup GPIO pins
TRIG1.low()
TRIG2.low()
TRIG3.low()
utime.sleep(2) # Allow sensors to stabilize
# Function to measure distance for a given sensor
def measure_distance(TRIG, ECHO):
# Send trigger pulse to start the ultrasonic sensor
TRIG.high()
utime.sleep_us(10) # Pulse duration of 10 microseconds
TRIG.low()
# Measure the duration of the echo pulse
try:
pulse_time = time_pulse_us(ECHO, 1) # Time the echo pulse (high state)
except OSError:
return None # If no echo received
# Calculate distance (speed of sound = 343 m/s)
distance = (pulse_time * 0.0343) / 2 # Distance in centimeters
return distance
# Function to categorize bin level based on distance
def categorize_bin_level(distance):
if distance is None:
return "No reading - Check sensor connections"
elif distance > 30:
return "🟢 Bin is Empty!"
elif 20 <= distance <= 30:
return "🟡 Bin is Filling!"
elif 10 <= distance < 20:
return "🟠 Bin is Almost Full!"
else:
return "🚨 Bin is Full!"
# Main program loop
try:
print("You have 3 waste bins to monitor!") # Message indicating three bins
while True:
# Measure distance for all three bins
distance1 = measure_distance(TRIG1, ECHO1)
distance2 = measure_distance(TRIG2, ECHO2)
distance3 = measure_distance(TRIG3, ECHO3)
# Get the status for all three bins
bin1_status = categorize_bin_level(distance1)
bin2_status = categorize_bin_level(distance2)
bin3_status = categorize_bin_level(distance3)
# Print the waste level for all three bins separately
print("\nWaste Level for Bin 1:")
print(bin1_status)
print("\nWaste Level for Bin 2:")
print(bin2_status)
print("\nWaste Level for Bin 3:")
print(bin3_status)
utime.sleep(1) # Wait for 1 second before taking the next reading
except KeyboardInterrupt:
print("Measurement stopped")