import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient
from machine import Pin, time_pulse_us
from time import sleep_us, sleep
SSID = "Wokwi-GUEST"
PASSWORD = ""
# MQTT Server Parameters
MQTT_CLIENT_ID = "Mqtt"
#MQTT_BROKER = "broker.mqttdashboard.com";#"broker.emqx.io"
MQTT_BROKER = "mqtt-dashboard.com";#"broker.emqx.io"
#MQTT_PASSWORD = ".30x%h9HS@?A6PnsJzpR"
#MQTT_USER = "hivemq.webclient.1749310363166"
MQTT_USER = "surapongpim"
MQTT_PASSWORD = "jjjjjjjJ0!"
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)
motorStatus = "OFF"
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 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;
return distance
def on_message(topic, message):
#print("received message: " ,str(message.payload.decode("utf-8")))
global motorStatus
print("received message: " ,topic, message)
if (topic == b'status/in') & (message == b'ON'):
motor(1)
motorStatus = "ON"
print("ON")
elif (topic == b'status/in') & (message == b'OFF'):
motor(0)
motorStatus = "OFF"
print("OFF")
def main():
global motorStatus
level = "LOW"
motorStatus = "OFF"
initWifi()
#connectMqtt()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER,port=1883, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
client.set_callback(on_message)
client.subscribe("status/in")
#
while True:
# Measure the distance and print the value in centimeters
client.check_msg()
distance = measure_distance()
print("Distance: cm",int(distance))
if (distance < 150):
lowLed(0)
level = "LOW"
motorStatus = "ON"
midLed(1)
highLed(1)
motor(1)
elif ((distance > 160) & (distance < 400)):
level = "MIDDLE"
#motorStatus = "ON"
lowLed(1)
midLed(0)
highLed(1)
#motor(1)
elif (distance >= 400 ):
level = "HIGH"
lowLed(1)
midLed(1)
highLed(0)
motor(0)
motorStatus = "OFF"
message = ujson.dumps({
"WaterLevel": level,
"MotorStatus": motorStatus,
})
client.publish(MQTT_TOPIC, message,True)
print("WaterLevel",level)
print("MotorStatus",motorStatus)
# Wait for 1 second before taking the next measurement
sleep(2)
if __name__ == "__main__":
main()