import machine
import ssd1306 # For the OLED display
import time
# Pin definitions
TRIG_PIN = machine.Pin(13, machine.Pin.OUT)
ECHO_PIN = machine.Pin(12, machine.Pin.IN)
RELAY_PIN = machine.Pin(27, machine.Pin.OUT)
# OLED display setup
i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21)) # Adjust pins as needed
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Function to measure distance
def measure_distance():
TRIG_PIN.off()
time.sleep_us(2) # Short delay
TRIG_PIN.on()
time.sleep_us(10) # Trigger pulse
TRIG_PIN.off()
# Wait for echo pin to go high (start of the pulse)
while ECHO_PIN.value() == 0:
pass
pulse_start = time.ticks_us() # Capture the start time
# Wait for echo pin to go low (end of the pulse)
while ECHO_PIN.value() == 1:
pass
pulse_end = time.ticks_us() # Capture the end time
# Calculate duration of the pulse
duration = time.ticks_diff(pulse_end, pulse_start) # Time in microseconds
# Calculate distance (speed of sound in air is approximately 34300 cm/s)
distance = (duration * 0.0343) / 2 # Convert duration to cm
return distance
# Main loop
THRESHOLD_DISTANCE = 5 # Threshold in cm, the pump should stop when the water level reaches this distance
distance = 50 # Start with an initial distance (in cm)
while True:
# Simulate the decreasing water level by reducing distance by 10 cm
if distance > THRESHOLD_DISTANCE:
distance -= 5
# Decrease the distance by 10 cm every cycle
else:
distance = THRESHOLD_DISTANCE # Stop the decrease once it reaches the threshold
# Debug print to check measured distance
print("Measured Distance:", distance)
# Display distance on OLED
oled.fill(0) # Clear the display
oled.text("Water Level:", 0, 0)
oled.text(f"{distance:.2f} cm", 0, 10)
# Control the relay based on distance
if distance > THRESHOLD_DISTANCE:
RELAY_PIN.on() # Turn on the pump if the distance is greater than the threshold (water level is low)
oled.text("Pump: ON", 0, 30)
else:
RELAY_PIN.off() # Turn off the pump if the distance is less than or equal to the threshold (water level is high)
oled.text("Pump: OFF", 0, 30)
distance += 50
# Show changes on OLED
oled.show()
time.sleep(1) # Wait before the next reading