import machine
import time
# Pins for sensor, relay, and buttons
TRIG_PIN = 15
ECHO_PIN = 13
RELAY_PIN = 12
ON_BUTTON_PIN = 14 # Pin for manual ON button
OFF_BUTTON_PIN = 27 # Pin for manual OFF button
# Setup the pins
trig = machine.Pin(TRIG_PIN, machine.Pin.OUT)
echo = machine.Pin(ECHO_PIN, machine.Pin.IN)
relay = machine.Pin(RELAY_PIN, machine.Pin.OUT)
on_button = machine.Pin(ON_BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_UP) # Manual ON button
off_button = machine.Pin(OFF_BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_UP) # Manual OFF button
# Initialize motor state
motor_on = False # Assume motor starts on
# Function to measure distance
def get_distance():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
# Initialize start_time and end_time properly
start_time = 0
end_time = 0
# Wait for echo signal to go HIGH
while echo.value() == 0:
start_time = time.ticks_us()
# Wait for echo signal to go LOW
while echo.value() == 1:
end_time = time.ticks_us()
# Calculate distance based on the time difference
elapsed_time = end_time - start_time
distance = (elapsed_time * 0.0343) / 2 # Speed of sound is 343 m/s
return distance
# Debouncing function to check if a button is pressed
def button_pressed(button):
if button.value() == 0: # Button is pressed (LOW)
time.sleep(0.05) # Wait 50ms for debounce
if button.value() == 0: # If still pressed after debounce
return True
return False
# Main loop to monitor water level and handle manual buttons
while True:
distance = get_distance()
print(f"Water level: {distance} cm")
# Check if the water tank is full
if distance < 10: # Assuming 10 cm is the threshold for full tank
if motor_on: # Turn off motor only if it is currently on
relay.off() # Turn off the motor
motor_on = False # Update motor state
print("Motor turned off. Tank is full.")
# Manual ON button logic
if not motor_on and button_pressed(on_button): # If motor is off and ON button is pressed
relay.on() # Turn on the motor
motor_on = True # Update motor state
print("Manual ON button pressed. Motor turned on.")
# Manual OFF button logic
if motor_on and button_pressed(off_button): # If motor is on and OFF button is pressed
relay.off() # Turn off the motor
motor_on = False # Update motor state
print("Manual OFF button pressed. Motor turned off.")
time.sleep(0)