from machine import Pin, PWM, ADC
import time
import dht
import network
# Constants for additional sensors
DHT_PIN = 12
SERVO_PIN = 14
SWITCH_LEFT_PIN = 18
SWITCH_RIGHT_PIN = 19
LED_RED_PIN = 23
LED_GREEN_PIN = 22
LDR_PIN = 34 # Light sensor (LDR)
SOIL_MOISTURE_PIN = 35 # Soil moisture sensor
# Set up DHT sensor
sensor = dht.DHT22(Pin(DHT_PIN))
# Set up Servo motor
servo = PWM(Pin(SERVO_PIN), freq=50)
# Set up LEDs
led_red = Pin(LED_RED_PIN, Pin.OUT)
led_green = Pin(LED_GREEN_PIN, Pin.OUT)
# Set up switches (buttons)
switch_left = Pin(SWITCH_LEFT_PIN, Pin.IN, Pin.PULL_UP)
switch_right = Pin(SWITCH_RIGHT_PIN, Pin.IN, Pin.PULL_UP)
# Set up LDR (Light) and Soil Moisture Sensors
ldr = ADC(Pin(LDR_PIN)) # Light intensity sensor (LDR)
soil_moisture = ADC(Pin(SOIL_MOISTURE_PIN)) # Soil moisture sensor
# Wi-Fi Setup
ssid = "Wokwi-GUEST"
password = ""
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, password)
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
# Function to read DHT sensor
def read_dht_sensor():
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
return temp, hum
except OSError as e:
print("Failed to read sensor:", e)
return None, None
# Function to read light level (LDR)
def read_light_sensor():
light_level = ldr.read() # Read light level (0-1023)
return light_level
# Function to read soil moisture level
def read_soil_moisture():
moisture_level = soil_moisture.read() # Read soil moisture level (0-1023)
return moisture_level
# Main loop
def loop():
switch_state = switch_left.value() == 0 # If the left switch is pressed
temp, hum = read_dht_sensor()
if temp and hum:
print("Temperature: ", temp, "C")
print("Humidity: ", hum, "%")
# Read the additional sensors
light_level = read_light_sensor()
moisture_level = read_soil_moisture()
print("Light level: ", light_level)
print("Soil moisture level: ", moisture_level)
# Control logic for LDR: Turn on LED if it's too dark
if light_level < 500: # Arbitrary threshold for light
led_green.value(1) # Turn on green LED
else:
led_green.value(0) # Turn off green LED
# Control logic for Soil Moisture Sensor: Activate watering system if soil is dry
if moisture_level < 500: # Arbitrary threshold for soil moisture
print("Soil is dry, turning on watering system")
servo.duty(77) # Activate servo to turn on water pump
else:
print("Soil is moist, no need for watering")
servo.duty(38) # Deactivate servo (no watering)
# Servo and LED logic based on temperature and humidity
if switch_state:
if hum < 30.0:
if temp > 30.0:
servo.duty(77) # Adjust servo position
led_green.value(1)
led_red.value(0)
else:
servo.duty(38) # Adjust servo position
led_green.value(1)
led_red.value(0)
else:
servo.duty(0)
led_green.value(0)
led_red.value(1)
time.sleep(1)
# Run the loop continuously
while True:
loop()