import network
import time
from machine import Pin, I2C
from machine import time_pulse_us
from time import sleep_us, sleep
# LCD I2C constants
LCD_ADDR = 0x27 # I2C address for the LCD (typically 0x27 or 0x3F)
LCD_BACKLIGHT = 0x08
LCD_NOBACKLIGHT = 0x00
LCD_CLEAR_DISPLAY = 0x01
LCD_RETURN_HOME = 0x02
LCD_ENTRY_MODE_SET = 0x04
LCD_DISPLAY_CONTROL = 0x08
LCD_FUNCTION_SET = 0x20
LCD_2LINE = 0x08
LCD_5x8DOTS = 0x00
LCD_DISPLAY_ON = 0x04
LCD_DISPLAY_OFF = 0x00
LCD_SET_DDRAM_ADDR = 0x80
# Define the GPIO pin numbers for the trigger and echo pins
ECHO_PIN = 25
TRIGGER_PIN = 26
LOWLED = 18
MIDLED = 19
HIGHLED = 21
MOTOR = 27
# Initialize trigger and echo pins
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
lowLed = Pin(LOWLED, Pin.OUT)
midLed = Pin(MIDLED, Pin.OUT)
highLed = Pin(HIGHLED, Pin.OUT)
motor = Pin(MOTOR, Pin.OUT)
motorStatus = "OFF"
lowLed(1)
midLed(1)
highLed(1)
motor(0)
# I2C and LCD configuration (SCL=22, SDA=23)
i2c = I2C(0, scl=Pin(22), sda=Pin(23), freq=400000)
# LCD Functions for sending commands
def lcd_byte(cmd, mode):
high_bits = mode | (cmd & 0xF0) | LCD_BACKLIGHT
low_bits = mode | ((cmd << 4) & 0xF0) | LCD_BACKLIGHT
i2c.writeto(LCD_ADDR, bytes([high_bits, high_bits | 0x04, high_bits]))
i2c.writeto(LCD_ADDR, bytes([low_bits, low_bits | 0x04, low_bits]))
def lcd_init():
lcd_byte(0x03, 0)
lcd_byte(0x03, 0)
lcd_byte(0x03, 0)
lcd_byte(0x02, 0)
lcd_byte(LCD_FUNCTION_SET | LCD_2LINE | LCD_5x8DOTS, 0)
lcd_byte(LCD_DISPLAY_CONTROL | LCD_DISPLAY_ON, 0)
lcd_byte(LCD_CLEAR_DISPLAY, 0)
time.sleep(0.002)
def lcd_clear():
lcd_byte(LCD_CLEAR_DISPLAY, 0)
time.sleep(0.002)
def lcd_putstr(s):
for char in s:
lcd_byte(ord(char), 1)
def lcd_move_to(row, col):
addr = col + (0x40 if row else 0x00)
lcd_byte(LCD_SET_DDRAM_ADDR | addr, 0)
# Initialize LCD with messages
def init_lcd():
lcd_init()
lcd_clear()
lcd_putstr("Bonjour LISI3")
sleep(2)
lcd_clear()
lcd_putstr("Controle niveau")
lcd_move_to(1, 0)
lcd_putstr("d'eau")
sleep(5)
lcd_clear()
def measure_distance():
trigger(0)
sleep_us(2)
trigger(1)
sleep_us(10)
trigger(0)
pulse_duration = time_pulse_us(echo, 1)
distance = pulse_duration / 58
return distance
def main():
global motorStatus
level = "LOW"
motorStatus = "OFF"
init_lcd() # Initialize LCD with startup messages
#initWifi()
print("Connecting to MQTT server... ", end="")
while True:
distance = measure_distance()
print("Distance: cm", int(distance))
if distance < 150:
lowLed(0)
level = "LOW"
motorStatus = "ON"
midLed(1)
highLed(1)
motor(1)
elif 160 < distance < 400:
level = "MIDDLE"
lowLed(1)
midLed(0)
highLed(1)
motor(1)
motorStatus = "ON"
elif distance >= 400:
level = "HIGH"
lowLed(1)
midLed(1)
highLed(0)
motor(0)
motorStatus = "OFF"
# Display current status on LCD
lcd_clear()
lcd_putstr("Level: {}".format(level))
lcd_move_to(1, 0)
lcd_putstr("Motor: {}".format(motorStatus))
sleep(2)
if __name__ == "__main__":
main()