from machine import Pin, ADC, PWM, I2C
import dht
import time
import ssd1306
dht_sensor = dht.DHT22(Pin(4))
soil_sensor = ADC(Pin(34))
soil_sensor.atten(ADC.ATTN_11DB)
green_led = Pin(18, Pin.OUT)
red_led = Pin(19, Pin.OUT)
pump = Pin(26, Pin.OUT)
buzzer = PWM(Pin(23))
buzzer.duty(0)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
MAX_TEMP = 35
MIN_HUMIDITY = 40
DRY_THRESHOLD = 40
def buzzer_on():
buzzer.freq(1000)
buzzer.duty(512)
def buzzer_off():
buzzer.duty(0)
def soil_percentage(value):
percentage = 100 - int((value / 4095) * 100)
if percentage < 0:
percentage = 0
if percentage > 100:
percentage = 100
return percentage
def show_oled(temperature, humidity, soil_percent,
soil_status, pump_status, emergency):
oled.fill(0)
oled.text("SMART PLANT", 18, 0)
oled.text("T:" + str(temperature) + "C", 0, 12)
oled.text("H:" + str(humidity) + "%", 70, 12)
oled.text("Soil:" + str(soil_percent) + "%", 0, 24)
oled.text("Condition:" + soil_status, 0, 36)
oled.text("Pump:" + pump_status, 0, 48)
oled.show()
while True:
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
soil_value = soil_sensor.read()
soil_percent = soil_percentage(soil_value)
if soil_percent < DRY_THRESHOLD:
soil_status = "DRY"
else:
soil_status = "WET"
if temperature > MAX_TEMP or humidity < MIN_HUMIDITY:
emergency = True
else:
emergency = False
if soil_status == "DRY":
pump.on()
pump_status = "ON"
else:
pump.off()
pump_status = "OFF"
if emergency:
red_led.on()
green_led.off()
buzzer_on()
else:
red_led.off()
green_led.on()
buzzer_off()
print("----------------------------")
print("Temperature:", temperature, "C")
print("Humidity:", humidity, "%")
print("Soil Moisture:", soil_percent, "%")
print("Soil Condition:", soil_status)
print("Pump:", pump_status)
if emergency:
print("EMERGENCY: CHECK PLANT CONDITIONS")
else:
print("Plant Status: HEALTHY")
show_oled(
temperature,
humidity,
soil_percent,
soil_status,
pump_status,
emergency
)
time.sleep(2)
except Exception as e:
print("ERROR:", e)
pump.off()
green_led.off()
red_led.off()
buzzer_off()
oled.fill(0)
oled.text("SYSTEM ERROR", 15, 20)
oled.text("CHECK SENSORS", 10, 35)
oled.show()
time.sleep(2)Loading
ssd1306
ssd1306