✅ Práctica 33
▷ #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, inclusive utilizar el protocolo HTTP ha generado conflictos. Ante ello, la mejor alternativa es trabajar con un servidor y enviar la data por medio de protocolo MQTT.
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 25 ***************************** | |
This practice is aboutNode-Red (with wi-fi) | |
By: Kevin E. Chica O | |
More information: https://tsc-lab.blogspot.com/ | |
*/ | |
#include <OneWire.h> | |
#include <DallasTemperature.h> | |
//GPIO pin 0 is set as OneWire bus | |
OneWire ourWire1(4); | |
//GPIO pin 4 is set as OneWire bus | |
OneWire ourWire2(0); | |
//A variable or object is declared for our sensor 1 | |
DallasTemperature sensors1(&ourWire1); | |
//A variable or object is declared for our sensor 2 | |
DallasTemperature sensors2(&ourWire2); | |
#include <WiFi.h> | |
#include <PubSubClient.h> | |
// WiFi | |
const char* ssid = "your_ssid"; | |
const char* password = "your_password"; | |
//Your Domain name with URL path or IP address with path | |
const char* mqtt_server = "test.mosquitto.org"; | |
const char *topic = "tsclab/your_name"; //cambiar "your_name" por su nombre o usuario | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
String msg; | |
String temperatura1 = ""; | |
String temperatura2 = ""; | |
float temp1; | |
float temp2; | |
void setup() { | |
//sensors | |
sensors1.begin(); //Sensor 1 starts | |
sensors2.begin(); //Sensor 2 starts | |
// Set software serial baud to 115200; | |
Serial.begin(115200); | |
// connecting to a WiFi network | |
//wifi | |
WiFi.mode(WIFI_STA); | |
connect_wifi(); | |
client.setServer(mqtt_server, 1883); | |
client.setCallback(callback); | |
} | |
void loop() { | |
connect_wifi(); | |
readData(); | |
publicMQTT(); | |
delay(1000); | |
} | |
void readData() { | |
//The command is sent to read the temperature | |
sensors1.requestTemperatures(); | |
//Obtain the temperature in ºC of sensor 1 | |
temp1 = sensors1.getTempCByIndex(0); | |
temperatura1 = String(temp1); | |
//The command is sent to read the temperature | |
sensors2.requestTemperatures(); | |
//Obtain the temperature in ºC of sensor 2 | |
temp2 = sensors2.getTempCByIndex(0); | |
temperatura2 = String(temp2); | |
//print to display the temperature change | |
} | |
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 callback(char* topic, byte* payload, unsigned int length) { | |
Serial.print("Message arrived ["); | |
Serial.print(topic); | |
Serial.print("] "); | |
for (int i = 0; i < length; i++) { | |
Serial.print((char)payload[i]); | |
} | |
Serial.println(); | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
if (client.connect("TSCLABClient")) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} | |
void publicMQTT() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
msg = temperatura1+","+temperatura2; | |
client.publish(topic, msg.c_str()); | |
} |
Repositories: https://github.com/vasanza/TSC-Lab/tree/main/Practice10
- Listo, ya se está enviando información por MQTT.
Comments
Post a Comment