import time
import machine
import dht
from machine import I2C, Pin
# Define GPIO pins
TRIG_PIN = machine.Pin(2, machine.Pin.OUT)
ECHO_PIN = machine.Pin(3, machine.Pin.IN)
BUZZER_PIN = machine.Pin(4, machine.Pin.OUT)
DHT_PIN = machine.Pin(5)
LED_PIN = machine.Pin(6, machine.Pin.OUT)
# I2C configuration for LCD
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
LCD_ADDR = 0x27 # Adjust if necessary for Wokwi
# LCD Constants
LCD_CMD = 0x00
LCD_CHR = 0x01
LCD_LINE_1 = 0x80
LCD_LINE_2 = 0xC0
LCD_BACKLIGHT = 0x08
ENABLE = 0b00000100
# Initialize DHT sensor
dht_sensor = dht.DHT22(DHT_PIN)
def lcd_toggle_enable(data):
time.sleep_us(500)
i2c.writeto(LCD_ADDR, bytearray([data | ENABLE | LCD_BACKLIGHT]))
time.sleep_us(500)
i2c.writeto(LCD_ADDR, bytearray([(data & ~ENABLE) | LCD_BACKLIGHT]))
time.sleep_us(500)
def lcd_byte(bits, mode):
# Send byte to data pins
high_bits = mode | (bits & 0xF0) | LCD_BACKLIGHT
low_bits = mode | ((bits << 4) & 0xF0) | LCD_BACKLIGHT
i2c.writeto(LCD_ADDR, bytearray([high_bits]))
lcd_toggle_enable(high_bits)
i2c.writeto(LCD_ADDR, bytearray([low_bits]))
lcd_toggle_enable(low_bits)
def lcd_init():
# Initialize display
lcd_byte(0x33, LCD_CMD) # Initialize
lcd_byte(0x32, LCD_CMD) # Set to 4-bit mode
lcd_byte(0x06, LCD_CMD) # Cursor move direction
lcd_byte(0x0C, LCD_CMD) # Turn on display
lcd_byte(0x28, LCD_CMD) # 2 line display
lcd_byte(0x01, LCD_CMD) # Clear display
time.sleep_ms(2)
def lcd_string(message, line):
# Send string to display
lcd_byte(line, LCD_CMD)
for char in message:
lcd_byte(ord(char), LCD_CHR)
# Initialize LCD
lcd_init()
def distance_measurement():
# Trigger ultrasonic sensor
TRIG_PIN.on()
time.sleep_us(10)
TRIG_PIN.off()
# Wait for echo to be HIGH (start time)
while not ECHO_PIN.value():
pass
pulse_start = time.ticks_us()
# Wait for echo to be LOW (end time)
while ECHO_PIN.value():
pass
pulse_end = time.ticks_us()
# Calculate distance
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
distance = pulse_duration / 58 # Speed of sound (343 m/s) divided by 2
return distance
def read_dht_sensor():
dht_sensor.measure()
return dht_sensor.temperature(), dht_sensor.humidity()
while True:
dist = distance_measurement()
temp, humidity = read_dht_sensor()
# Check if the distance is less than a threshold (e.g., 50 cm)
if dist < 50:
# Turn on the buzzer and LED
BUZZER_PIN.off()
LED_PIN.off()
status = "Flooding Detected"
else:
# Turn off buzzer and LED if distance is above threshold
BUZZER_PIN.on()
LED_PIN.on()
status = "No Flooding Detected"
# Update LCD with measurements
lcd_string(f"Dist:{dist:.1f} cm", LCD_LINE_1)
lcd_string(f"Temp:{temp:.1f}C Hum:{humidity:.1f}%", LCD_LINE_2)
# Print to console for debugging
print(f"Distance: {dist:.2f} cm")
print(f"Temperature: {temp:.2f}°C, Humidity: {humidity:.2f}%")
print("Status:", status)
# Short delay before next loop
time.sleep(2)