from machine import Pin, PWM
from time import sleep, sleep_us
import utime as time
# Pin Definitions
PIN_TRIG = 26
PIN_ECHO = 25
LOWLED = 18
MIDLED = 19
HIGHLED = 21
MOTOR = 27
BUZZER_PIN = 15
# Initialize Pins
trig = Pin(PIN_TRIG, Pin.OUT)
echo = Pin(PIN_ECHO, Pin.IN)
low_led = Pin(LOWLED, Pin.OUT)
mid_led = Pin(MIDLED, Pin.OUT)
high_led = Pin(HIGHLED, Pin.OUT)
motor = Pin(MOTOR, Pin.OUT)
buzzerPin = Pin(BUZZER_PIN, Pin.OUT)
# Buzzer setup
buzzer = PWM(buzzerPin)
toneA = 440 # Frequency for tone A (440 Hz)
# Initial States
low_led.value(1)
mid_led.value(1)
high_led.value(1)
motor.value(0)
buzzer.duty(0)
def measure_distance():
"""Measure distance using the ultrasonic sensor."""
trig.value(1)
sleep_us(10)
trig.value(0)
while echo.value() == 0:
pass
start_time = time.ticks_us()
while echo.value() == 1:
pass
end_time = time.ticks_us()
duration = time.ticks_diff(end_time, start_time)
distance = duration / 58
return distance
def ring_buzzer(freq, duration_ms):
"""Ring the buzzer at a specific frequency for a duration."""
buzzer.freq(freq)
buzzer.duty(512) # Set duty cycle (volume)
sleep(duration_ms / 1000) # Convert milliseconds to seconds for sleep
buzzer.duty(0) # Stop the buzzer after the duration
while True:
level = measure_distance()
print(f"Distance in CM: {level:.1f}")
# Determine water level status and control LEDs and motor
if level <= 200:
low_led.value(0)
mid_led.value(1)
high_led.value(1)
motor.value(1)
status = "Low"
elif 200 < level < 400:
low_led.value(1)
mid_led.value(0)
high_led.value(1)
motor.value(1)
status = "Medium"
elif level >= 400:
low_led.value(1)
mid_led.value(1)
high_led.value(0)
motor.value(0)
status = "High"
# Activate buzzer when water level is High
ring_buzzer(toneA, 500) # Play the tone for 500 ms
else:
status = "Unknown"
print(f"Water Level: {status}")
sleep(1)