import time
import network
from machine import Pin, time_pulse_us
from umqtt.simple import MQTTClient
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
MQTT_Broker = "mqtt3.thingspeak.com"
MQTT_Client = "FgY0DwInJzQqKzchGiEtKjM"
MQTT_Username = "FgY0DwInJzQqKzchGiEtKjM"
MQTT_Password = "AI/s/7747+Y4PbAnL9XLKx+g"
MQTT_Topic = "channels/2491429/publish"
Write_Key = "4XJ64X5FBTY3NP0G"
trigger_pin = Pin(14, Pin.OUT)
echo_pin = Pin(5, Pin.IN)
pir_sensor = Pin(16, Pin.IN, Pin.PULL_UP)
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print('Network config:', wlan.ifconfig())
connect_to_wifi()
client = MQTTClient(MQTT_Client, MQTT_Broker, port=1883, user=MQTT_Username, password=MQTT_Password)
client.connect()
def send_thingspeak_mqtt(client, distance):
payload = 'field1={}&api_key={}'.format(distance, Write_Key)
client.publish(MQTT_Topic, payload)
def measure_distance():
trigger_pin.off()
time.sleep_us(2)
trigger_pin.on()
time.sleep_us(10)
trigger_pin.off()
duration = time_pulse_us(echo_pin,1,1000000)
if duration < 0:
duration = 1000000
distance = (duration / 2) / 29.1
return distance
def check_motion():
motion = pir_sensor.value()
return motion
while True:
distance = measure_distance()
motion = check_motion()
if distance < 200:
print('Parking spot is occupied')
else:
print('Parking spot is vaccant')
if motion:
print('Motion Detected')
send_thingspeak_mqtt(client, distance)
time.sleep(15)