import hcsr04
import ssd1306
from machine import Pin, I2C, PWM
from time import sleep
import dht
# Declare connections for water level sensing
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=500 * 2 * 30)
# Declare connections for DHT22 sensor
dht_sensor = dht.DHT22(Pin(14)) # Change pin number accordingly
# OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Buzzer
buzzer = PWM(Pin(17), Pin.OUT)
# LED setup
green_led = Pin(15, Pin.OUT)
red_led = Pin(2, Pin.OUT)
# Function to get water level
def get_water_level():
try:
distance_cm = ultrasonic_sensor.distance_cm()
return distance_cm
except Exception as e:
print("Error:", e)
return None
# Function to get temperature and humidity
def get_temperature_humidity():
try:
dht_sensor.measure()
return dht_sensor.temperature(), dht_sensor.humidity()
except Exception as e:
print("Error:", e)
return None
# Main loop
while True:
# Water level sensing
water_level = get_water_level()
if water_level is not None:
print("Water level:", water_level, "cm")
# Adjust the threshold based on your water level requirements
high_level_threshold = 30 # Adjust as needed
low_level_threshold = 10 # Adjust as needed
# Display on OLED
oled.fill(0) # Clear the display
oled.text("Water Level:", 0, 0, 1)
oled.text(str(water_level) + " cm", 0, 20, 1)
# Temperature and humidity sensing
temperature, humidity = get_temperature_humidity()
oled.text("Temp: {}C, Humidity: {}%".format(temperature, humidity), 0, 40, 1)
oled.show()
if water_level > high_level_threshold:
print("High water level! Red LED ON, Buzzer ON.")
red_led.on()
green_led.off()
# Sound the buzzer
for i in range(100):
buzzer.init(freq=1703, duty=400)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
elif water_level < low_level_threshold:
print("Low water level! Green LED ON, Buzzer ON.")
green_led.on()
red_led.off()
# Sound the buzzer
for i in range(100):
buzzer.init(freq=1703, duty=400)
sleep(0.5)
# Turn off the buzzer after the loop
buzzer.init(freq=1, duty=0)
sleep(0.5)
# Check the distance/range for the LED loop
distance_cm = ultrasonic_sensor.distance_cm()
# LED loop
if distance_cm < 50:
# Sound the buzzer
for i in range(100):
buzzer.init(freq=1703, duty=400)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
elif 50 <= distance_cm < 150:
# Sound the buzzer
for i in range(100):
buzzer.init(freq=1703, duty=400)
sleep(1)
buzzer.init(freq=1, duty=0)
sleep(1)
else:
buzzer.init(freq=1, duty=0)
sleep(5)