#include <WiFi.h>
#include <HTTPClient.h>
// ================= = PINES =================
const int PIN_TRIG = 12;
const int PIN_ECHO = 14;
const int PIN_GAS = 34;
// ================= = WIFI =================
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ================= = SERVIDOR LOCAL =================
// Se conecta directamente a la IP configurada en tu panel local (ej: XAMPP / Servidor en PC)
const char* servidorURL = "https://datosparalaplantadegas.infinityfreeapp.com/index.php";
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("--- Robot Omnidireccional - Servidor Local ---");
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(PIN_GAS, INPUT);
Serial.print("Conectando al WiFi: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n¡Conectado exitosamente al WiFi!");
Serial.print("IP del ESP32: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
// 1. Lectura Distancia (HC-SR04)
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
long duracion = pulseIn(PIN_ECHO, HIGH);
float distancia = duracion * 0.034 / 2;
// 2. Lectura Gas Analógico
int gas = analogRead(PIN_GAS);
// 3. Envío POST al Servidor Local PHP
HTTPClient http;
http.begin(servidorURL);
http.addHeader("Content-Type", "application/json");
String jsonData = "{\"gas\":" + String(gas) + ", \"distancia\":" + String(distancia) + "}";
Serial.println("Enviando JSON: " + jsonData);
int httpResponseCode = http.POST(jsonData);
if (httpResponseCode > 0) {
Serial.print("Servidor respondió con código: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println("Respuesta: " + payload);
} else {
Serial.print("Error de conexión HTTP: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("⚠️ Desconectado. Reconectando...");
WiFi.reconnect();
}
delay(3000);
}