import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
from machine import Pin, time_pulse_us
from time import sleep_us, sleep
SSID = "SSID of WIFI Network"
PASSWORD = "Password of WIFI Network"
# MQTT Server Parameters
MQTT_CLIENT_ID = "Mqtt"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "status/out"
# 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)
lowLed(1)
midLed(1)
highLed(1)
motor(0)
def initWifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
#sta_if.connect(SSID, PASSWORD)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def connectMqtt():
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
def measure_distance():
# Ensure trigger is low initially
trigger(0)
sleep_us(2)
# Send a 10 microsecond pulse to the trigger pin
trigger(1)
sleep_us(10)
trigger(0)
# Measure the duration of the echo pulse (in microseconds)
pulse_duration = time_pulse_us(echo, 1)
distance = pulse_duration / 58;
# Calculate the distance (in centimeters) using the speed of sound (343 m/s)
# distance = pulse_duration * 0.0343 / 2
return distance
def main():
level = "LOW"
motorStatus = "OFF"
initWifi()
#connectMqtt()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
while True:
# Measure the distance and print the value in centimeters
distance = measure_distance()
print("Distance: cm",int(distance))
if (distance < 100):
lowLed(0)
level = "LOW"
motorStatus = "ON"
midLed(1)
highLed(1)
motor(1)
elif ((distance > 200) & (distance < 400)):
level = "MIDDLE"
#motorStatus = "ON"
lowLed(1)
midLed(0)
highLed(1)
#motor(1)
elif (distance >= 400 ):
level = "HIGH"
motorStatus = "OFF"
lowLed(1)
midLed(1)
highLed(0)
motor(0)
message = ujson.dumps({
"Waterlevel": level,
"MotorStatus": motorStatus,
})
client.publish(MQTT_TOPIC, message,True,qos = 1)
print("WaterLevel",level)
print("MotorStatus",motorStatus)
# Wait for 1 second before taking the next measurement
sleep(2)
if __name__ == "__main__":
main()