#include <WiFi.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include <Keypad.h> // Asegúrate de tener instalada la librería Keypad
// Configuración de la red WiFi
const char* ssid = "TuSSID";
const char* password = "TuContraseña";
// Configuración de la pantalla LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // Dirección I2C y tamaño de la pantalla
// Configuración del sensor DHT22
#define DHTPIN 27
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// Configuración del sensor MQ135
#define MQ135PIN 34
// Configuración del sensor de humedad del suelo
#define SOIL_HUMIDITY_PIN 35
// Configuración de los actuadores
#define LIGHT_PIN 14
#define FAN_PIN 12
#define WATER_PUMP_PIN 13
#define ALARM_PIN 15
// Credenciales para acceder al sistema
const String credentials = "1245";
String input_credentials = "";
// Variables para almacenar los valores de los sensores
float temperature = 0.0;
float humidity = 0.0;
int co2 = 0;
int soil_humidity = 0;
// Umbrales para el control de los actuadores
const float TEMP_THRESHOLD = 25.0; // Umbral de temperatura para tomates
const int SOIL_HUMIDITY_THRESHOLD = 500; // Umbral de humedad del suelo
// Instancia del servidor web
AsyncWebServer server(80);
// Temporizador para la lectura de sensores y actualización de la interfaz web
unsigned long previousMillis = 0;
const long interval = 2000; // Intervalo de 2 segundos
// Configuración del teclado
const byte ROWS = 4; // Número de filas
const byte COLS = 4; // Número de columnas
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {32, 33, 18, 19}; // Pines de las filas
byte colPins[COLS] = {23, 25, 26, 2}; // Pines de las columnas
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
// Inicialización de la pantalla LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Bienvenido");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Digite credencial:");
// Configuración de pines de los actuadores
pinMode(LIGHT_PIN, OUTPUT);
pinMode(FAN_PIN, OUTPUT);
pinMode(WATER_PUMP_PIN, OUTPUT);
pinMode(ALARM_PIN, OUTPUT);
// Inicialización del sensor DHT22
dht.begin();
// Inicialización del servidor web
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
String html = "<html><head><style>";
html += "body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; text-align: center; }";
html += "h1 { color: #4CAF50; }";
html += "button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }";
html += "button:hover { background-color: #45a049; }";
html += "</style></head><body>";
html += "<h1>Invernadero 2.0</h1>";
html += "<p>Temperatura: " + String(temperature) + " C</p>";
html += "<p>Humedad: " + String(humidity) + " %</p>";
html += "<p>CO2: " + String(co2) + " ppm</p>";
html += "<p>Humedad del suelo: " + String(soil_humidity) + "</p>";
html += "<button onclick=\"controlActuator('light', 'on')\">Encender Bombillo</button>";
html += "<button onclick=\"controlActuator('light', 'off')\">Apagar Bombillo</button><br>";
html += "<button onclick=\"controlActuator('fan', 'on')\">Encender Ventilador</button>";
html += "<button onclick=\"controlActuator('fan', 'off')\">Apagar Ventilador</button><br>";
html += "<button onclick=\"controlActuator('water', 'on')\">Encender Bomba de Agua</button>";
html += "<button onclick=\"controlActuator('water', 'off')\">Apagar Bomba de Agua</button><br>";
html += "<button onclick=\"controlActuator('alarm', 'on')\">Encender Sirena</button>";
html += "<button onclick=\"controlActuator('alarm', 'off')\">Apagar Sirena</button><br>";
html += "<script>";
html += "function controlActuator(actuator, state) {";
html += "var xhr = new XMLHttpRequest();";
html += "xhr.open('GET', '/control?actuator=' + actuator + '&state=' + state, true);";
html += "xhr.send();";
html += "}";
html += "</script>";
html += "</body></html>";
request->send(200, "text/html", html);
});
server.on("/control", HTTP_GET, [](AsyncWebServerRequest *request){
String actuator = request->getParam("actuator")->value();
String state = request->getParam("state")->value();
controlActuator(actuator, state);
request->send(200, "text/plain", "OK");
});
server.begin();
}
void loop() {
unsigned long currentMillis = millis();
// Verificación de credenciales
if (input_credentials != credentials) {
char key = keypad.getKey();
if (key) {
input_credentials += key;
lcd.print(key);
if (input_credentials.length() == 4) {
if (input_credentials == credentials) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Acceso OK");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Conectando a Wifi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
lcd.print(".");
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Conexion exitosa");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("IP: " + WiFi.localIP().toString());
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("SESION INICIADA");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Invernadero 2.0");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Credencial invalida");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Digite credencial:");
input_credentials = "";
}
}
}
} else {
// Lectura de sensores y control autónomo de actuadores cada intervalo de tiempo
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Lectura de los sensores
readSensors();
// Control autónomo de los actuadores
controlActuators();
// Actualización de la interfaz web
updateWebInterface();
}
}
}
void readSensors() {
temperature = dht.readTemperature();
humidity = dht.readHumidity();
co2 = analogRead(MQ135PIN); // Leer el valor del potenciómetro
soil_humidity = analogRead(SOIL_HUMIDITY_PIN); // Leer el valor del potenciómetro
}
void controlActuators() {
if (temperature > TEMP_THRESHOLD) {
digitalWrite(FAN_PIN, HIGH);
} else {
digitalWrite(FAN_PIN, LOW);
}
if (soil_humidity < SOIL_HUMIDITY_THRESHOLD) {
digitalWrite(WATER_PUMP_PIN, HIGH);
} else {
digitalWrite(WATER_PUMP_PIN, LOW);
}
}
void controlActuator(String actuator, String state) {
if (actuator == "light") {
digitalWrite(LIGHT_PIN, state == "on" ? HIGH : LOW);
} else if (actuator == "fan") {
digitalWrite(FAN_PIN, state == "on" ? HIGH : LOW);
} else if (actuator == "water") {
digitalWrite(WATER_PUMP_PIN, state == "on" ? HIGH : LOW);
} else if (actuator == "alarm") {
digitalWrite(ALARM_PIN, state == "on" ? HIGH : LOW);
}
}
void updateWebInterface() {
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
String html = "<html><head><style>";
html += "body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; text-align: center; }";
html += "h1 { color: #4CAF50; }";
html += "button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }";
html += "button:hover { background-color: #45a049; }";
html += "</style></head><body>";
html += "<h1>Invernadero 2.0</h1>";
html += "<p>Temperatura: " + String(temperature) + " C</p>";
html += "<p>Humedad: " + String(humidity) + " %</p>";
html += "<p>CO2: " + String(co2) + " ppm</p>";
html += "<p>Humedad del suelo: " + String(soil_humidity) + "</p>";
html += "<button onclick=\"controlActuator('light', 'on')\">Encender Bombillo</button>";
html += "<button onclick=\"controlActuator('light', 'off')\">Apagar Bombillo</button><br>";
html += "<button onclick=\"controlActuator('fan', 'on')\">Encender Ventilador</button>";
html += "<button onclick=\"controlActuator('fan', 'off')\">Apagar Ventilador</button><br>";
html += "<button onclick=\"controlActuator('water', 'on')\">Encender Bomba de Agua</button>";
html += "<button onclick=\"controlActuator('water', 'off')\">Apagar Bomba de Agua</button><br>";
html += "<button onclick=\"controlActuator('alarm', 'on')\">Encender Sirena</button>";
html += "<button onclick=\"controlActuator('alarm', 'off')\">Apagar Sirena</button><br>";
html += "<script>";
html += "function controlActuator(actuator, state) {";
html += "var xhr = new XMLHttpRequest();";
html += "xhr.open('GET', '/control?actuator=' + actuator + '&state=' + state, true);";
html += "xhr.send();";
html += "}";
html += "</script>";
html += "</body></html>";
request->send(200, "text/html", html);
});
}