"""
MicroPython MQTT Logger (ESP32)
MicroPython code for MPU6050 and temperature sensor data reporting through MQTT
Master Cyberseguridad UNIR
Sensores, Dispositivos, Redes y Protocolos de Comunicaciones
Alumnos:
Jon Ander Aguirrechu Zea
Guillermo Anoro Corz
Jesus Gonzalez Villagomez
Date: May 18th 2024
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
from machine import Pin, I2C, sleep
import mpu6050
import time
# MQTT Server Parameters
MQTT_CLIENT_ID = "sensoresMQTT"
MQTT_BROKER = "io.adafruit.com"
MQTT_USER = "Guillermoac22"
MQTT_PASSWORD = "aio_MeJh493rlO0EwZTtjJ2Qe9t9FMiH"
tempSensor = dht.DHT22(Pin(15))
i2c = I2C (scl =Pin(22), sda = Pin(21))
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()
client.ping()
print("Connected!")
mpu =mpu6050.accel(i2c)
prev_val_tem = []
prev_val_acc = []
prev_val_gir = []
while True:
temps = (mpu.get_values())
tempSensor.measure()
#Temp
messageTem = ujson.dumps({
"temMPU": tempSensor.temperature(),
"temp": temps["Tmp"]
})
MQTT_TOPIC="Guillermoac22/feeds/temperature"
if messageTem!=prev_val_tem:
prev_val_tem=messageTem
print("{}:{}".format(MQTT_TOPIC, messageTem))
client.publish(MQTT_TOPIC, messageTem)
#Gyro
messageGyro = ujson.dumps({
"GyroXMPU": round(temps["GyX"]*250/32762,2),
"GyroYMPU": round(temps["GyY"]*250/32762,2),
"GyroZMPU": round(temps["GyZ"]*250/32762,2)
})
MQTT_TOPIC="Guillermoac22/feeds/giroscope"
if messageGyro!=prev_val_gir:
prev_val_gir=messageGyro
print("{}:{}".format(MQTT_TOPIC, messageGyro))
client.publish(MQTT_TOPIC, messageGyro)
#Accel
messageAccel = ujson.dumps({
"AccXMPU": round(temps["AcX"]*2 / 32767,2),
"AccYMPU": round(temps["AcY"]*2 / 32767,2),
"AccZMPU": round(temps["AcZ"]*2 / 32767,2)
})
MQTT_TOPIC="Guillermoac22/feeds/accelerometer"
if messageAccel!=prev_val_acc:
prev_val_acc=messageAccel
print("{}:{}".format(MQTT_TOPIC, messageAccel))
client.publish(MQTT_TOPIC, messageAccel)
time.sleep(1)