from machine import Pin, I2C
from time import sleep, sleep_us, ticks_us, ticks_diff
import ssd1306
# OLED Display settings
i2c = I2C(0, scl=Pin(22), sda=Pin(21)) # Connect OLED to SDA and SCL pins
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Ultrasonic sensor pins
trig = Pin(27, Pin.OUT)
echo = Pin(26, Pin.IN)
def measure_distance():
# Send a 10us pulse to trigger the sensor
trig.off()
sleep_us(2)
trig.on()
sleep_us(10)
trig.off()
# Initialize start time
start_time = ticks_us()
# Measure the duration of the echo pulse
while echo.value() == 0:
signal_off = ticks_us()
# Timeout if echo signal takes too long
if ticks_diff(signal_off, start_time) > 100000: # 100ms timeout
return -1 # Return -1 to indicate timeout
while echo.value() == 1:
signal_on = ticks_us()
if ticks_diff(signal_on, start_time) > 100000: # 100ms timeout
return -1 # Return -1 to indicate timeout
# Calculate distance in cm (speed of sound is ~34300 cm/s)
time_passed = signal_on - signal_off
distance = (time_passed * 0.0343) / 2 # Divide by 2 for round-trip
return distance
def display_distance(distance):
oled.fill(0) # Clear display
oled.text("Water Level Monitor", 0, 0)
oled.text("Distance:", 0, 20)
if distance == -1:
oled.text("Out of range", 0, 40) # Display if there's a timeout
else:
oled.text(f"{distance:.2f} cm", 0, 40)
oled.show()
def main():
while True:
# Measure distance
distance = measure_distance()
# Display distance on OLED
display_distance(distance)
# Print to console (for debugging)
if distance == -1:
print("Distance: Out of range")
else:
print(f"Distance: {distance:.2f} cm")
# Delay before next measurement
sleep(1)
# Run the main function
main()