"""
To view the message:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-movement-topic"(withouth the quotation marks!) then click "Subscribe"
Click on the PIR Sensor in the simulation and press the "Simulate motion" button, you should be able to see the message "Movimento Detectado".
If you can't see the message, try restarting the MQTT or/and the simulaiton.
"""
import network
from machine import Pin, PWM
import time
import ujson
from umqtt.simple import MQTTClient
## Parámetros MQTT
MQTT_CLIENT_ID = "micropython-movement-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-movement-topic"
## Print status de conexão
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)
client.connect()
print("Connected!")
buzzer = PWM(23,Pin.OUT)
pir = Pin(27,Pin.IN)
tempo = 3
tones = {
'c': 262,
'd': 294,
'e': 330,
'f': 349,
'g': 392,
'a': 440,
'b': 494,
'C': 523,
' ': 0,
}
lastPirValue = ""
while True:
if pir.value() >= 1:
lastPirValue = pir.value
melody = 'cdefgabC'
rhythm = [3, 3]
## Mensagem de teste no console
print("Teste")
## Mensagem no servidor mqtt
message = ujson.dumps({
"Mensagem": "teste"
})
for tone, length in zip(melody, rhythm):
buzzer.freq(tones[tone])
time.sleep(tempo/length)
time.sleep(1)
buzzer.freq(1)
buzzer.duty(40)
if pir.value() >=1:
client.publish(MQTT_TOPIC, "Movimento detectado")