from machine import Pin, ADC, I2C
import BlynkLib
import network
import time
from ssd1306 import SSD1306_I2C
import dht
# Blynk Authentication Token
BLYNK_AUTH = "xTV7YDdynjI7D7pt2BSXeGeKxIipXzZC" # Replace with your actual Blynk token
# Wi-Fi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# Initialize Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
while not wifi.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi:", wifi.ifconfig())
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Initialize the Soil Moisture Sensor
soil_sensor = ADC(Pin(34)) # ADC Pin for soil moisture sensor
soil_sensor.atten(ADC.ATTN_11DB) # Set ADC range (0-3.3V)
# Initialize LED Pins
led_dry = Pin(15, Pin.OUT) # Red LED for dry soil
led_wet = Pin(2, Pin.OUT) # Green LED for moist soil
# Initialize OLED Display
i2c = I2C(0, scl=Pin(22), sda=Pin(21)) # Default pins for ESP32 in Wokwi
oled = SSD1306_I2C(128, 64, i2c)
# Initialize DHT Sensor (Temperature and Humidity)
dht_sensor = dht.DHT22(Pin(4)) # Connect DHT22 to GPIO4
# Function to display data on the OLED
def display_oled(moisture_value, moisture_status, temp, hum):
oled.fill(0) # Clear the display
oled.text("Soil Monitoring", 0, 0)
oled.text(f"Moisture: {moisture_value}", 0, 15)
oled.text(f"Status: {moisture_status}", 0, 30)
oled.text(f"Temp: {temp}C", 0, 45)
oled.text(f"Humidity: {hum}%", 0, 60)
oled.show()
# Function to read soil moisture and control LEDs
def read_soil_moisture():
moisture_value = soil_sensor.read() # Read soil moisture value (0-4095)
print("Soil Moisture:", moisture_value)
# Determine soil status
if moisture_value > 800: # Adjust threshold as needed
moisture_status = "Dry"
led_dry.on() # Turn ON Red LED
led_wet.off() # Turn OFF Green LED
else:
moisture_status = "Moist"
led_dry.off() # Turn OFF Red LED
led_wet.on() # Turn ON Green LED
return moisture_value, moisture_status
# Function to read temperature and humidity from DHT sensor
def read_temperature_humidity():
try:
dht_sensor.measure()
temp = dht_sensor.temperature() # Read temperature
hum = dht_sensor.humidity() # Read humidity
print(f"Temperature: {temp}C, Humidity: {hum}%")
return temp, hum
except Exception as e:
print("Error reading DHT sensor:", e)
return None, None
# Main loop
while True:
blynk.run() # Handle Blynk connection
# Read sensors
moisture_value, moisture_status = read_soil_moisture()
temp, hum = read_temperature_humidity()
# Update OLED display
if temp is not None and hum is not None:
display_oled(moisture_value, moisture_status, temp, hum)
else:
print("Skipping OLED update due to sensor error.")
# Send data to Blynk
blynk.virtual_write(1, moisture_value) # Soil moisture to V1
blynk.virtual_write(2, temp) # Temperature to V2
blynk.virtual_write(3, hum) # Humidity to V3
time.sleep(2) # Delay to avoid spamming