✅ Práctica 32
▷ #TSCLab #TCLab #ESP32 #Arduino #Control #MACI
En el siguiente blog se presenta la vigésima novena práctica del laboratorio de control de temperatura y velocidad de un motor.
Objetivo general:
- Enviar los valores sensados y estados de los transistores al servidor del TSC-Lab y visualizarlo en MyData-Lab.
Materiales:
- MQTTLens
- MyData-Lab
- TSC-Lab
Introducción:
En la práctica anterior se realizó la conexión MQTT entre el TSC-Lab y el servidor. Sin embargo, un caso práctico no consiste únicamente en enviar una cadena de caracteres, sino una serie de información útil para que pueda ser trabajada o procesada, siendo así el caso del envío de los valores de temperatura y estado de los transistores para a futuro poder realizar un control PID u otra clase de proyectos.
Procedimiento:
Nota: Se asume que la placa del ESP-32 y las libreías de las práticas anteriores han sido previamente instaladas en el IDE de Arduino. Sin embargo, se requiere la instalación de dos librerías adicionales, la primera de ellas es ArduinoJson, la cual se puede descargar aquí y la instalación se la realiza de manera normal. La segunda librería es NTP Client, la cual requiere una pequeña modificación para que funcione sin ningún problema, para ello se deben seguir los siquientes pasos:
- Cerrar los IDE de Arduino que se tengan abierto.
- Descargar NTP Client aquí y guárdelo en la carpeta de descargas.
- Descomprimir el archivo .zip y debe quedar la carpeta NTPClient-master.
- Renombrar la carpeta NTPClient-master a NTPClient
- Mover la carpeta al directorio de librerías, por lo general está en Documentos/Arduino/libraries
- Re-abrir el IDE de Arduino
Para que los datos puedan ser procesados y posteriormente visualizados en MyData-Lab, se los debe enviar con un formato específico el cual es el siguiente:
DireccionMAC#Fecha#Hora#{ "modelo":"TSC-Lab", "sensores":[ { "nombre": "temperatura1", "valor":"25.1", "unidadMedicion":"C" }, { "nombre": "temperatura2", "valor":"26.1", "unidadMedicion":"C" } , { "nombre": "transistor1", "valor":"1", "unidadMedicion":"" },{ "nombre": "transistor2", "valor":"0", "unidadMedicion":"" }] }
Y por esa razón la práctica será dividida en dos partes.
Parte A:
Como se pudo ver en el formato anterior, es necesario saber la dirección MAC del ESP-32 de cada TSC-Lab y para ello se debe implementar el código que se muestra a continuación
- Copiar el código en el IDE de Arduino y cargar el programa a la placa:
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 29_A ***************************** | |
This practice is about to know MAC Address of ESP32 | |
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> | |
void setup(){ | |
Serial.begin(115200); | |
Serial.print("Dirección Mac del ESP32: "); | |
Serial.println(WiFi.macAddress()); | |
} | |
void loop(){ | |
} |
Repositories: https://github.com/vasanza/TSC-Lab/tree/main/Practice17
- Anotar la dirección MAC. El monitor serial mostrará un mensaje así:
Parte B:
Ahora se implementará el código para subir al servidor y que este pueda ser visualizado.
- Copiar el código en el IDE de Arduino, cambiar la dirección MAC y cargar el programa a la placa:
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 29_B ***************************** | |
This practice is about MQTT Server (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 <OneWire.h> | |
#include <DallasTemperature.h> | |
//GPIO pin 4 is set as OneWire bus | |
OneWire ourWire1(4); | |
//GPIO pin 0 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); | |
//pins of transistor | |
int trans1 = 17; | |
int trans2 = 16; | |
int dutyCycle1 = 0; | |
int dutyCycle2 = 0; | |
// Setting PWM properties | |
const int freq = 30000; | |
const int pwmChannell = 0; | |
const int pwmChannel2 = 1; | |
const int resolution = 8; | |
//include librarys for date and time | |
#include <NTPClient.h> | |
#include <WiFiUdp.h> | |
// Define NTP Client to get time | |
WiFiUDP ntpUDP; | |
NTPClient timeClient(ntpUDP); | |
// Variables to save date and time | |
String formattedDate = ""; | |
String dayStamp = ""; | |
String timeStamp = ""; | |
#include <WiFi.h> | |
#include <PubSubClient.h> | |
#define MQTT_MAX_PACKET_SIZE 256; | |
// WiFi | |
const char *ssid = "Chica Orellana"; // Enter your WiFi name | |
const char *password = "ManchasyBombon1998"; // 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; | |
// variables | |
String mac = "24:62:AB:FC:A3:E8"; | |
String temperatura1 = ""; | |
String temperatura2 = ""; | |
String transistor1 = ""; | |
String transistor2 = ""; | |
float temp1; | |
float temp2; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
#include <ArduinoJson.h> | |
char buffer[400] = ""; | |
StaticJsonDocument<400> doc; | |
void setup() { | |
delay(1000); | |
Serial.begin(115200); | |
sensors1.begin(); //Sensor 1 starts | |
sensors2.begin(); //Sensor 2 starts | |
//transistor 1 | |
pinMode(trans1, OUTPUT); | |
//transitor 2 | |
pinMode(trans2, OUTPUT); | |
// configure LED PWM functionalitites | |
ledcSetup(pwmChannell, freq, resolution); | |
ledcSetup(pwmChannel2, freq, resolution); | |
// attach the channel to the GPIO to be controlled | |
ledcAttachPin(trans1, pwmChannell); | |
ledcAttachPin(trans2, pwmChannel2); | |
//wifi | |
WiFi.mode(WIFI_STA); | |
// Initialize a NTPClient to get time | |
timeClient.begin(); | |
// Set offset time in seconds to adjust for your timezone | |
timeClient.setTimeOffset(-18000); | |
connect_wifi(); | |
connect_mqtt(); | |
} | |
void loop() { | |
connect_wifi(); | |
connect_mqtt(); | |
readData(); | |
date_time(); | |
SerializeObject(); | |
publicSubscribe(400); | |
client.loop(); | |
delay(5000); | |
} | |
void readData() { | |
ledcWrite(pwmChannell, dutyCycle1); | |
ledcWrite(pwmChannel2, dutyCycle2); | |
transistor1 = String(dutyCycle1); | |
transistor2 = String(dutyCycle2); | |
//The command is sent to read the temperature | |
sensors1.requestTemperatures(); | |
//Obtain the temperature in ºC of sensor 1 | |
float 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 | |
float temp2 = sensors2.getTempCByIndex(0); | |
temperatura2 = String(temp2); | |
//print to display the temperature change | |
/*Serial.print(temp1); | |
Serial.print(","); | |
Serial.print(temp2); | |
Serial.print(","); | |
Serial.print(t1); | |
Serial.print(","); | |
Serial.println(t2);*/ | |
//delay(15000); | |
} | |
void SerializeObject() | |
{ | |
doc["modelo"] = "TSC-Lab"; | |
//temperature 1 | |
doc["sensores"][0]["nombre"] = "temperatura1" ; | |
doc["sensores"][0]["valor"] = temperatura1 ; | |
doc["sensores"][0]["unidadMedicion"] = "C" ; | |
//temperature 2 | |
doc["sensores"][1]["nombre"] = "temperatura2" ; | |
doc["sensores"][1]["valor"] = temperatura2 ; | |
doc["sensores"][1]["unidadMedicion"] = "C" ; | |
//transistor 1 | |
doc["sensores"][2]["nombre"] = "transistor1" ; | |
doc["sensores"][2]["valor"] = transistor1 ; | |
doc["sensores"][2]["unidadMedicion"] = "" ; | |
//transistor 2 | |
doc["sensores"][3]["nombre"] = "transistor2" ; | |
doc["sensores"][3]["valor"] = transistor2 ; | |
doc["sensores"][3]["unidadMedicion"] = "" ; | |
doc["sensores"][4]["nombre"] = "motor" ; | |
doc["sensores"][4]["valor"] = "0" ; | |
doc["sensores"][4]["unidadMedicion"] = "rpm" ; | |
//doc.clear(); | |
doc.garbageCollect(); | |
serializeJson(doc, buffer); | |
} | |
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 | |
Serial.println("Publicando..."); | |
char kevin[n]; | |
String todo = mac + "#" + dayStamp + "#" + timeStamp + "#" + buffer; | |
//char prueba[n]=mac + "#" + dayStamp + "#" + timeStamp + "#" + buffer; | |
todo.toCharArray(kevin, n); | |
Serial.println(sizeof(kevin)); | |
client.publish(topic, kevin); | |
client.subscribe(topic); | |
} | |
void date_time() { | |
while (!timeClient.update()) { | |
timeClient.forceUpdate(); | |
} | |
// The formattedDate comes with the following format: | |
// 2018-05-28T16:00:13Z | |
// We need to extract date and time | |
formattedDate = timeClient.getFormattedDate(); | |
// Extract date | |
int splitT = formattedDate.indexOf("T"); | |
dayStamp = formattedDate.substring(0, splitT); | |
// Extract time | |
timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() - 1); | |
} | |
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); | |
client.setBufferSize(512); | |
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/Practice17
- Ingresar al siguiente enlace para viualizar los resultados: http://mydata-lab.com/#/home
Comments
Post a Comment