// ---------------------------- LIBRARIES: ESP32 ---------------------------- //
#include <WiFi.h>
#include <DHTesp.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
// CONFIGURACIÓN INICIAL: --------------------------------------------------- //
// DHT-22.
#define DHTPIN 15
#define DHTTYPE DHT22
DHTesp DHT;
// WI-FI.
const char* SSID = "Wokwi-GUEST"; // Nombre de la red.
const char* Password = ""; // Contraseña de la red.
WiFiClientSecure CodeWave;
// API.
const char* APIPath = "";
// POST: ID de los sensores.
const int TemperatureID = 91;
const int MoistureID = 93;
const int LightID = 95;
// VARIABLES: --------------------------------------------------------------- //
// Intervalo de tiempo entre lecturas.
const int Intervalo = 4000;
// Temperatura/Humedad (DHT).
float Temperature;
float Humidity;
// Humedad de suelo.
float Moisture = 0;
// SETUP: WIFI -------------------------------------------------------------- //
void InternetConnection() {
delay(10);
Serial.print("Conectando a: "); Serial.println(SSID);
Serial.println();
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, Password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(); Serial.println();
Serial.println("Conectado a Internet.");
Serial.print("Dirección IP: "); Serial.println(WiFi.localIP());
// Permite cualquier certificado SSL.
CodeWave.setInsecure();
}
// API: POST DATA ----------------------------------------------------------- //
void sendData(float value, int sensorId) {
HTTPClient http;
String JSON_BODY = "{\"value\":" + String(value) + ",\"sensorId\":" + String(sensorId) + "}";
http.begin(CodeWave, APIPath);
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(JSON_BODY);
if (httpCode > 0) {
Serial.printf("HTTP POST code: %d\n", httpCode);
} else {
Serial.printf("HTTP POST error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
// SETUP: MAIN -------------------------------------------------------------- //
void setup() {
Serial.begin(115200);
Serial.setTimeout(2000);
Serial.println();
Serial.println("- Iniciando conexión a Internet...");
InternetConnection();
Serial.println();
Serial.println("- Iniciando sensor DHT...");
DHT.setup (DHTPIN, DHTesp::DHTTYPE);
}
// LOOP: MAIN --------------------------------------------------------------- //
void loop() {
// Intervalo entre lecturas.
delay(Intervalo);
Serial.println();
Temperature = DHT.getTemperature();
Serial.print("Temperatura: "); Serial.println(Temperature);
Humidity = DHT.getHumidity();
Serial.print("Humedad: "); Serial.println(Humidity);
Serial.println();
Serial.println("----------------------");
// Envío de datos a la API.
sendData(Temperature, TemperatureID);
sendData(Moisture, MoistureID);
sendData(Humidity, LightID);
}
// -------------------------------------------------------------------------- //