#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// --- Configuración de Red y MQTT ---
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "io.adafruit.com";
const int mqtt_port = 1883;
const char* mqtt_user = "mati_xd14";
const char* mqtt_key = "aio_yJdQ27Wrt80ZfHi0JJR5WYsOpFyC";
// --- Pines de Hardware ---
#define POT_PIN 34 // Entrada Analógica (Sensor de Presión 0-10V simulado)
#define BTN_PIN 26 // Entrada Digital (Pulsador con pull-down externo)
#define LED_PIN 2 // Actuador: LED de estado
#define RELAY_PIN 4 // Actuador: Relé para carga industrial
// --- Instancias ---
WiFiClient espClient;
PubSubClient client(espClient);
LiquidCrystal_I2C lcd(0x27, 16, 2);
// --- Variables y Umbrales ---
const float UMBRAL_CRITICO = 80.0; // 80 Bar
void setup_wifi() {
delay(10);
lcd.setCursor(0, 0);
lcd.print("Conectando WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
lcd.clear();
lcd.print("WiFi Online");
}
void callback(char* topic, byte* payload, unsigned int length) {
// Control Remoto del LED desde MQTT
String message;
for (int i = 0; i < length; i++) message += (char)payload[i];
if (message == "ON") digitalWrite(LED_PIN, HIGH);
else if (message == "OFF") digitalWrite(LED_PIN, LOW);
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32_Industria", mqtt_user, mqtt_key)) {
// Suscripción al tópico de control del LED
client.subscribe("mati_xd14/feeds/led-control");
} else {
delay(5000);
}
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BTN_PIN, INPUT); //
lcd.init();
lcd.backlight();
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
// 1. Lectura y Procesamiento
int rawADC = analogRead(POT_PIN);
// Escalado: 0 a 0-100 Bar
float presion = (rawADC * 100.0) / 4095.0;
// 2. Lógica Local (Independiente de Internet)
if (presion > UMBRAL_CRITICO) {
digitalWrite(RELAY_PIN, HIGH); // Activa carga industrial
} else {
digitalWrite(RELAY_PIN, LOW);
}
// 3. Visualización Local LCD
lcd.setCursor(0, 0);
lcd.print("Presion: ");
lcd.print(presion, 1);
lcd.print(" Bar ");
lcd.setCursor(0, 1);
lcd.print(digitalRead(BTN_PIN) ? "STP: ACTIVADO " : "STP: NORMAL ");
// 4. Envío de datos a la Nube (MQTT) cada 2 segundos
static unsigned long lastMsg = 0;
if (millis() - lastMsg > 2000) {
lastMsg = millis();
client.publish("mati_xd14/feeds/presion", String(presion).c_str());
}
}