"""
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 the topic then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient
fotoresistor_pin = Pin(35)
infravermelho_passivo_pin = Pin(34)
led_pinVerde = Pin(25)
led_pinBranco = Pin(14)
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
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!")
val = 0;
prev_ldr_val = 0 # Variável para armazenar o estado anterior do LDR
pirState = 0 # Estado do sensor PIR (infravermelho passivo)
prev_val = 0 # Variável para armazenar o estado anterior do fotoresistor
#val = ""
while True:
val = fotoresistor_pin.value()
if val == 1:
led_pinVerde.on() # Acende o LED
if infravermelho_passivo_pin.value() == LOW and pirState == LOW:
print("Movimento detectado! Luz acessa!")
led_pinBranco.on()
pirState = 1
time.sleep(3)
else: # Se não
led_pinVerde.off() # Desliga o LED
if pirState == 1:
print("Nenhum movimento detectado! Luz apagada!")
led_pinBranco.off()
pirState = 0
time.sleep(3)
# Verifica se o valor do fotoresistor mudou e reporta para MQTT
if val != prev_val:
print("Updated!")
message = ujson.dumps({"Sensor LDR": val, "Sensor PIR": pirState})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_val = val
#else:
# print("No change")
time.sleep(1)