#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define DHTTYPE DHT22 // Definimos el modelo del sensor DHT22
#define DHTPIN 4 // Se define el pin D4 del ESP32 para conectar el sensor DHT22
DHT dht(DHTPIN, DHTTYPE);
// Credenciales de red WiFi (Wokwi)
const char* ssid = "Wokwi-GUEST";
const char* password = ""; // Sin contraseña
// Token de Ubidots
const String ubidotsToken = "BBUS-HKTjYYHqFMWtalkqdFgfl6AVotUIxw";
// Nombres del dispositivo y las variables (puedes cambiarlos manualmente)
String deviceName = "devicename"; // Nombre del dispositivo en Ubidots
String temperatureVariable = "temperatura"; // Nombre de la variable de temperatura en Ubidots
String humidityVariable = "humedad"; // Nombre de la variable de humedad en Ubidots
void setup() {
Serial.begin(9600);
Serial.println("Iniciando lectura del sensor de temperatura y humedad...");
// Conectamos a la red WiFi (simulada en Wokwi)
Serial.print("Conectando a WiFi");
WiFi.begin(ssid, password, 6); // Canal 6 para Wokwi
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Conectado!");
// Inicializamos el sensor DHT
dht.begin();
}
void loop() {
// Leemos los valores de temperatura y humedad
float h = dht.readHumidity();
float t = dht.readTemperature();
// Mostramos los valores en el monitor serie
Serial.print("Humedad: ");
Serial.print(h);
Serial.println("%");
Serial.print("Temperatura: ");
Serial.print(t);
Serial.println("°C");
// Enviamos los datos a Ubidots
if (WiFi.status() == WL_CONNECTED) { // Verificamos la conexión WiFi
WiFiClient client;
HTTPClient http;
// URL de la API de Ubidots con el nombre del dispositivo
String url = "http://industrial.api.ubidots.com/api/v1.6/devices/" + deviceName;
http.begin(client, url); // Pasamos el cliente WiFi junto con la URL
// Configuramos el token en el encabezado HTTP
http.addHeader("X-Auth-Token", ubidotsToken);
http.addHeader("Content-Type", "application/json");
// Formato de los datos a enviar (JSON) con los nombres de las variables
String json = "{\"" + temperatureVariable + "\":" + String(t) + ", \"" + humidityVariable + "\":" + String(h) + "}";
// Enviamos la solicitud POST y obtenemos la respuesta
int httpResponseCode = http.POST(json);
if (httpResponseCode > 0) {
Serial.print("Datos enviados. Código de respuesta: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error enviando los datos. Código: ");
Serial.println(httpResponseCode);
}
// Cerramos la conexión
http.end();
} else {
Serial.println("Error: No hay conexión WiFi.");
}
// Esperamos 2 segundos antes de la siguiente lectura
delay(2000);
}