import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
from time import sleep
from servo import Servo
motor=Servo(pin=12)
# MQTT Server Parameters
MQTT_CLIENT_ID = "2023pj16001"
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_DISTANCE = "/IOT/SmartCarParking" # Original topic for distance status
MQTT_TOPIC_STATUS = "/IOT/parkingStatus" # New topic for textual status
# Initialize the HC-SR04 Sensor
sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
# Connecting to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Change the Wi-Fi credentials if needed
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Connecting to MQTT Server
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Main loop to read and publish sensor data
prev_message = ""
prev_status = ""
while True:
# Read the distance from the sensor
distance = sensor1.distance_cm()
# Determine if the distance is less than 40 cm and set the corresponding messages
if distance < 40:
message = ujson.dumps(0) # Numeric value for Car Slot Occupied
status_message = "Car slot occupied" # Text status for GUI display
print("Car slot occupied") # Print to serial monitor
motor.move(90)
else:
message = ujson.dumps(1) # Numeric value for Car Slot Empty
status_message = "Car slot empty" # Text status for GUI display
print("Car slot empty") # Print to serial monitor
motor.move(0)
# Publish distance status to the original topic
if message != prev_message:
print("Reporting distance status to MQTT topic {}: {}".format(MQTT_TOPIC_DISTANCE, message))
client.publish(MQTT_TOPIC_DISTANCE, message)
prev_message = message
# Publish the textual status to the new topic
if status_message != prev_status:
print("Reporting status to MQTT topic {}: {}".format(MQTT_TOPIC_STATUS, status_message))
client.publish(MQTT_TOPIC_STATUS, status_message)
prev_status = status_message
# Delay before the next reading
time.sleep(1)