from machine import Pin, ADC
import dht
import time
import network
import urequests
# Initialize the DHT22 sensor
dht_pin = Pin(14)
dht_sensor = dht.DHT22(dht_pin)
# Initialize the soil moisture sensor
soil_moisture_pin = ADC(Pin(34))
soil_moisture_pin.atten(ADC.ATTN_11DB) # Configure to read the full range (0-3.3V)
# Initialize the relay
relay_pin = Pin(27, Pin.OUT)
relay_pin.value(0) # Initially turn off the relay
# WiFi Configuration (replace with your WiFi credentials)
ssid = 'your_SSID'
password = 'your_PASSWORD'
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi")
print(wlan.ifconfig())
connect_to_wifi()
# Function to read temperature and humidity
def read_dht_sensor():
dht_sensor.measure()
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temp, humidity
# Function to read soil moisture
def read_soil_moisture():
moisture_value = soil_moisture_pin.read()
moisture_percentage = (moisture_value / 4095.0) * 100 # Convert to percentage
return moisture_percentage
# Main loop
while True:
temp, humidity = read_dht_sensor()
soil_moisture = read_soil_moisture()
print("Temperature: {:.2f} C".format(temp))
print("Humidity: {:.2f} %".format(humidity))
print("Soil Moisture: {:.2f} %".format(soil_moisture))
# Simple control logic
if temp > 30: # If temperature is above 30 degrees Celsius
relay_pin.value(1) # Turn on the fan
print("Fan turned ON")
else:
relay_pin.value(0) # Turn off the fan
print("Fan turned OFF")
if soil_moisture < 30: # If soil moisture is below 30%
relay_pin.value(1) # Turn on the pump
print("Pump turned ON")
else:
relay_pin.value(0) # Turn off the pump
print("Pump turned OFF")
# Send data to a server (optional)
try:
url = "http://your_server_address/update" # Replace with your server address
data = {
"temperature": temp,
"humidity": humidity,
"soil_moisture": soil_moisture
}
response = urequests.post(url, json=data)
print("Data sent to server:", response.text)
except Exception as e:
print("Failed to send data to server:", e)
time.sleep(10) # Wait for 10 seconds before the next reading