✅ Práctica 31
▷ #TSCLab #TCLab #ESP32 #Arduino #Control #MACI
En el siguiente blog se presenta la vigésima octava práctica del laboratorio de control de temperatura y velocidad de un motor.
Objetivo general:
- Realizar una conexión MQTT utilizando el TSC-Lab.
Objetivos específicos:
- Enviar un mensaje al servidor y verificarlo en MQTTLens.
Materiales:
- MQTTLens
- TSC-Lab
Introducción:
En las prácticas anteriores se realizararon conexiones a .diferentes plataformas donde se envió la información e inclusive se pudo visualizar los datos. Sin embargo, poseen muchas limitaciones como por ejemplo ThingSpeak que únicamente permite crear cuatro canales y el envío de información lo hace con un delay mínimo de 14 segundos. Ante ello, la mejor alternativa es trabajar con el servidor del TSC-Lab debido a que no tiene limitaciones en cuanto a la creación de proyectos, ni envío de información. Por esta razón, en la presente prácticase darán los primeros pasos para poder conectarse a dicho servidor y enviar información.
Procedimiento:
Nota: revisar la práctica 1 donde se le recuerda a como instalar librerías e instalar la librería PubSubClient.
Se asume que la placa del ESP-32 ha sido previamente instalada en el IDE de Arduino.
- Copiar el código en el IDE de Arduino:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
****************************** TSC-Lab ******************************* | |
***************************** PRACTICE 28 **************************** | |
This practice is about MQTT connection (mydata-lab) | |
By: Kevin E. Chica O | |
Reviewed: Víctor Asanza | |
More information: https://tsc-lab.blogspot.com/ | |
More examples: https://github.com/vasanza/TSC-Lab | |
Dataset: http://ieee-dataport.org/4138 | |
*/ | |
#include <WiFi.h> | |
#include <PubSubClient.h> | |
// WiFi | |
const char *ssid = "your_ssid"; // Enter your WiFi name | |
const char *password = "your_password"; // Enter WiFi password | |
// MQTT Broker | |
const char *mqtt_broker = "147.182.236.61"; | |
const char *topic = "topicPrincipal"; | |
const char *mqtt_username = "ideTSer"; | |
const char *mqtt_password = "secReTex4@m#"; | |
const int mqtt_port = 1883; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
void setup() { | |
// Set software serial baud to 115200; | |
Serial.begin(115200); | |
//wifi | |
WiFi.mode(WIFI_STA); | |
} | |
void loop() { | |
connect_wifi(); | |
connect_mqtt(); | |
publicSubscribe(200); | |
client.loop(); | |
delay(5000); | |
} | |
void callback(char *topic, byte *payload, unsigned int length) { | |
Serial.print("Message arrived in topic: "); | |
Serial.println(topic); | |
Serial.print("Message:"); | |
for (int i = 0; i < length; i++) { | |
Serial.print((char) payload[i]); | |
} | |
Serial.println(); | |
Serial.println("-----------------------"); | |
} | |
void publicSubscribe(int n) { | |
// publish and subscribe | |
client.publish(topic, "Mensaje enviado al servidor del TSC-Lab"); | |
client.subscribe(topic); | |
} | |
void connect_wifi(){ | |
// Connect or reconnect to WiFi | |
if(WiFi.status() != WL_CONNECTED){ | |
Serial.print("Attempting to connect to SSID: "); | |
Serial.println(ssid); | |
while(WiFi.status() != WL_CONNECTED){ | |
WiFi.begin(ssid, password); // Connect to WPA/WPA2 network. Change this line if using open or WEP network | |
Serial.print("."); | |
delay(5000); | |
} | |
Serial.println("\nConnected."); | |
} | |
} | |
void connect_mqtt(){ | |
//connecting to a mqtt broker | |
client.setServer(mqtt_broker, mqtt_port); | |
client.setCallback(callback); | |
while (!client.connected()) { | |
String client_id = "esp32-client-"; | |
client_id += String(WiFi.macAddress()); | |
Serial.printf("The client %s connects to the mqtt broker\n", client_id.c_str()); | |
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) { | |
Serial.println("Mqtt broker connected"); | |
} else { | |
Serial.print("failed with state "); | |
Serial.print(client.state()); | |
delay(2000); | |
} | |
} | |
} |
Repositories: https://github.com/vasanza/TSC-Lab/tree/main/Practice10
- Instalar la extensión de Google Chrome llamada MQTTLens
- Al abrir el programa dar clic en el "+", tal y como se muestra en la siguiente imagen:
- Complete los campos, Hostname: 147.182.236.61; Username: ideTSer; Password: secReTex4@m#. Y presione "Create Conecction".
- Escribir el topic y subscribirse
- Cargar el código a la placa.
- Verificar en el monitor serial la conexión WiFi y la conexión al servidor. En MQTTLens revisar los mensajes publicados.
fig1. Vista del monitor serial fig2. Vista de MQTTLENS
Comments
Post a Comment