from machine import Pin, ADC
from umqtt.simple import MQTTClient
import time
import json
import network
import dht
# **#
# Objects:
led1 = Pin(19 , Pin.OUT)
led2 = Pin(4, Pin.OUT) # GPIO 04: D4 led interno NodeMCU
d = dht.DHT22(Pin(2))
trig = Pin(27, Pin.OUT)
echo = Pin(26, Pin.IN)
# **#
# Configure the ESP32 wifi as STAtion.
sta = network.WLAN(network.STA_IF)
if not sta.isconnected():
print('connecting to network...')
sta.active(True)
sta.connect('Wokwi-GUEST', '')
# sta.connect(wifi_credentials.ssid, wifi_credentials.password)
while not sta.isconnected():
pass
print('network config:', sta.ifconfig())
# **#
print("pasando a THINGSBOARD")
# Global variables and constants:
username = "izfxgxjfc2oua2xiuo65"
broker = "thingsboard.cloud"
topic = "v1/devices/me/telemetry"
Mqtt_CLIENT_ID = "b3ve1ii1qslk5tbhet3p" # Max. Number is 23 due to MQTT specs
PASSWORD = "sfsg3ncn018ngu4x70jk"
client = MQTTClient(client_id=Mqtt_CLIENT_ID, server=broker, port=1883,
user=username, password=PASSWORD, keepalive=10000) # Configuración del Cliente MQTT
client.connect()
UPDATE_TIME_INTERVAL = 1000 # in ms unit
last_update = time.ticks_ms()
# **#
data = dict()
# ***#
led1 = True
led2 = True
print("Conectado a thingsboard")
time.sleep(4)
def read_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
pulse_start = 0
pulse_end = 0
while echo.value() == 0:
pulse_start = time.ticks_us()
while echo.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
distance = (pulse_duration * 0.0343) / 2
return distance
# Main loop:
while True:
if time.ticks_diff(time.ticks_ms(), last_update) >= UPDATE_TIME_INTERVAL:
last_update = time.ticks_ms()
d.measure()
distance = read_distance()
print(distance)
time.sleep_ms(100)
t = d.temperature()
h = d.humidity()
print(t, h)
data["temperature"] = t
data["humidity"] = h
data["led"] = led2
data["distance"] = distance
data2 = json.dumps(data) # Convert it to JSON
print('connection finished')
client.publish(topic, data2)
print("Data_Published")
if t > 25:
led2.value(1)
print('PELIGRO DE TEMPERATURA')
else:
led2.value(0)
if distance < 20: # Assuming 20 cm is the threshold for distance
led1.value(1)
print('OBSTÁCULO DETECTADO')
else:
led1.value(0)