from machine import SoftI2C, Pin, time_pulse_us, ADC
from time import sleep_ms, sleep_us
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import dht
from servo import Servo
SOUND_SPEED=340
TRIG_PULSE_DURATION_US=10
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
servoSystem = 0
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) # initializing the I2C method for ESP32
trig_pin = Pin(14, Pin.OUT)
echo_pin = Pin(27, Pin.IN)
dhtSensor = dht.DHT22(Pin(16))
servoLeft = Servo(Pin(13))
servoRight = Servo(Pin(12))
# adc = ADC(Pin(34))
# adc.atten(ADC.ATTN_11DB)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.move_to(0,0)
lcd.putstr("Welcome to Flood")
lcd.move_to(0,1)
lcd.putstr("Detection System")
sleep_ms(1000)
lcd.move_to(3,1)
lcd.clear()
lcd.putstr(" And Prevenstion System")
sleep_ms(1000)
lcd.clear()
lcd.move_to(0,0)
lcd.putstr("....")
sleep_ms(4000)
lcd.clear()
# display welcome message on LCD
# def read_rain_sensor():
# adc_value = adc.read()
# voltage = adc_value * 5 / 4095
# return voltage
def move_servo_slowly(servoPin, current_angle, end_angle, delay):
if current_angle < end_angle:
step = 3 # If the current angle is less than the end angle, move the servo in increments of 3 degrees.
else:
step = -3 # If the current angle is greater than the end angle, move the servo in decrements of 3 degrees.
for angle in range(current_angle, end_angle + step, step):
servoPin.move(angle)
sleep_ms(delay)
while True:
trig_pin.value(0)
sleep_us(5)
trig_pin.value(1)
sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
ultrason_duration = time_pulse_us(echo_pin, 1, 30000)
distance_cm = SOUND_SPEED * ultrason_duration / 20000
print(f"Distance : {distance_cm} cm")
sleep_ms(500)
lcd.move_to(0,0)
lcd.putstr(f"Dist:{distance_cm}")
dhtSensor.measure()
temp = dhtSensor.temperature()
hum = dhtSensor.humidity()
print('Temperature in C: ', temp, 'C')
print('Humidity in %', hum, '%')
tempF = (temp * 9/5) + 32
print('Temperature in F: ', tempF, 'F')
lcd.move_to(0,1)
lcd.putstr(" ")
lcd.move_to(0,1)
lcd.putstr(f"Temp:{temp}C")
sleep_ms(1000)
lcd.move_to(0,1)
lcd.putstr(" ")
lcd.move_to(0,1)
lcd.putstr(f"Humidity:{hum}%")
# rain_sensor_voltage = read_rain_sensor()
# print("rain value",rain_sensor_voltage)
if distance_cm < 7 and servoSystem == 0:
#move_servo_slowly(servoRight, 0, 60, 0.05)
servoRight.move(60)
servoLeft.move(60)
servoSystem = 1
# print("rain value")
elif distance_cm >= 7 and servoSystem == 1:
#move_servo_slowly(servoRight, 60, 0, 0.05)
servoRight.move(0)
servoLeft.move(0)
servoSystem = 0
else:
print("rain value2")