from machine import Pin, PWM
import network
from umqtt.simple import MQTTClient
import time
from hcsr04 import HCSR04
# MQTT Server Parameters
MQTT_CLIENT_ID = "stein"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC1 = "cmr.seg.entrada"
MQTT_TOPIC2 = "cmr.seg.saida"
led = Pin(25, Pin.OUT)
buzzer = PWM(Pin(27), freq= 1000, duty = 0)
pin_motion = Pin(33, Pin.IN)
sensor_distancia = HCSR04(trigger_pin = 5, echo_pin = 18)
unidade_de_medida = sensor_distancia.distance_cm()
# Função de callback para recebimento de mensagens MQTT
def callback(topic, msg):
#print("Mensagem recebida: ", msg.decode())
global status
if((str(msg.decode()) == "Entrou no Raio de Distancia") and (status == 0)):
client.publish(MQTT_TOPIC2, "Dentro do Raio de Distancia")
status = 1
if pin_motion.value() == 1:
if unidade_de_medida < 250:
led.on()
buzzer.duty(1023)
buzzer.duty(500)
print("ALGO DETECTADO")
elif(str((msg.decode()) == "Saiu do Raio de Distancia") and (status == 1)):
led.off()
buzzer.duty(0)
print("NADA DETECTADO")
status = 0
client.publish(MQTT_TOPIC2, "Nada detectado")
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!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
#Lembrem-se sempre é necessário ter um callback para receber informações.
client.set_callback(callback)
client.connect()
client.subscribe(MQTT_TOPIC1)
print("Connected!")
status = 0
while True:
client.check_msg()
time.sleep(1)