#include <ESP32Servo.h>
#include <DHT.h>
// ===== DHT22 =====
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// ===== SERVO =====
Servo bomba;
const int pinServo = 18;
// ===== SENSOR HUMEDAD =====
const int pinSensor = 34;
int humedadSuelo = 0;
int humedadMinima = 30;
// ===== CONTROL =====
unsigned long tiempoInicioRiego = 0;
unsigned long tiempoMaxRiego = 600000;
bool bombaActiva = false;
void setup() {
Serial.begin(115200);
// Inicializar DHT22
dht.begin();
// 🔑 Configuración correcta para ESP32
ESP32PWM::allocateTimer(0);
bomba.setPeriodHertz(50);
bomba.attach(pinServo, 500, 2400);
bomba.write(0); // Bomba apagada
Serial.println("Sistema de riego inteligente con ESP32 + DHT22");
}
void loop() {
// ===== LECTURA HUMEDAD SUELO =====
int lectura = analogRead(pinSensor);
humedadSuelo = map(lectura, 0, 4095, 0, 100);
// ===== LECTURA DHT22 =====
float temperatura = dht.readTemperature();
float humedadAire = dht.readHumidity();
// Validación del sensor
if (isnan(temperatura) || isnan(humedadAire)) {
Serial.println("Error leyendo DHT22");
delay(2000);
return;
}
// ===== MONITOREO =====
Serial.println("------");
Serial.print("Humedad suelo: ");
Serial.print(humedadSuelo);
Serial.println("%");
Serial.print("Temperatura: ");
Serial.print(temperatura);
Serial.println(" °C");
Serial.print("Humedad aire: ");
Serial.print(humedadAire);
Serial.println(" %");
// ===== LÓGICA DE DECISIÓN =====
if (humedadSuelo < humedadMinima) {
int tiempoRiego = 10000; // base
// Ajuste por temperatura
if (temperatura > 30) {
tiempoRiego = 15000;
} else if (temperatura < 20) {
tiempoRiego = 7000;
}
if (!bombaActiva) {
Serial.println("Bomba ENCENDIDA");
bomba.write(90); // Activar servo
bombaActiva = true;
tiempoInicioRiego = millis();
tiempoMaxRiego = tiempoRiego;
}
// Seguridad
if (millis() - tiempoInicioRiego > tiempoMaxRiego) {
Serial.println("Riego detenido (seguridad)");
bomba.write(0);
bombaActiva = false;
}
} else {
if (bombaActiva) {
Serial.println("Bomba APAGADA (suelo húmedo)");
bomba.write(0);
bombaActiva = false;
}
}
delay(2000);
}