import time
import machine
from time import sleep_us,sleep
from machine import I2C, Pin, ADC
from i2c_lcd import I2cLcd
from umqtt.simple import MQTTClient
import ujson
import network
# MQTT Server Parameters
MQTT_CLIENT_ID = "Wokwi-GUEST"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = "Wokwi-GUEST"
MQTT_PASSWORD = ""
MQTT_TOPIC = "exams/Asoukidis/distance/"
# WiFi connection
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# MQTT server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Settings of display
AddressOfLcd = 0x27
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, AddressOfLcd, 2, 16)
print("display is ready")
print("PROGRAM START")
last_distance = ""
echo=Pin(33,Pin.IN)
trig=Pin(25,Pin.OUT)
while True:
trig.value(0)
sleep_us(2)
trig.value(1)
sleep_us(10)
trig.value(0)
x=machine.time_pulse_us(echo,1)
distance=(0.034*x)/2
print("Distance:", distance, "cm")
lcd.move_to(0,0)
lcd.putstr("Distance:")
lcd.move_to(5,1)
lcd.putstr(str(distance)+ "cm")
message = ujson.dumps({
"Asoukidis/distance": distance,
})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
last_distance = distance
sleep(5)