jueves, 17 de septiembre de 2026

DATA LOGGER

 #include <WiFi.h>

#include <HTTPClient.h>
#include <Wire.h>
#include "Adafruit_SHT31.h"

// ---------- Wi-Fi ----------
const char* ssid = "LEOMASTER";
const char* password = "123456789";

// ---------- Google Apps Script ----------
const char* scriptURL = "https://script.google.com/macros/s/AKfycbxqx832rkd68MmhMnbllSZFzFE7h5NBoRL1gofs88IVuYAPS3IsWSnvUgpg8VWy8Hgs/exec";

// ---------- SHT30 ----------
Adafruit_SHT31 sht30 = Adafruit_SHT31();

void setup() {

  Serial.begin(115200);
  Wire.begin(21, 22);

 
  if (!sht30.begin(0x44)) {
    Serial.println("SHT30 not found!");
    while (1);
  }

  Serial.println("SHT30 connected!");

  WiFi.begin(ssid, password);

  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("Wi-Fi connected!");
  Serial.print("ESP32 IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Read temperature and humidity
  float temperature = sht30.readTemperature();
  float humidity = sht30.readHumidity();
  // Definimos el valor de AQI (Calidad del aire).
  int aqi = 45;
  // Check sensor data
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Error reading SHT30");
    delay(5000);
    return;
  }
  // Show data in Serial Monitor
  Serial.println("----------------------------");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" °C");

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  Serial.print("AQI: ");
  Serial.println(aqi);

  // Send data to Google Sheets using POST and JSON
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    // Iniciamos la conexión con la URL del script
    http.begin(scriptURL);
    // Indicamos que los datos se envían en formato JSON
    http.addHeader("Content-Type", "application/json");
    // Construimos el paquete JSON con las variables
    String httpRequestData = "{\"temperature\":" + String(temperature, 2) +
                             ",\"humidity\":" + String(humidity, 2) +
                             ",\"aqi\":" + String(aqi) + "}";

    Serial.println("Sending JSON data to Google Sheets...");
    // Enviamos la petición POST con los datos empaquetados
    int httpResponseCode = http.POST(httpRequestData);
    if (httpResponseCode > 0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);

      String response = http.getString();
      Serial.print("Server response: ");
      Serial.println(response);
    } else {
      Serial.print("Error sending data: ");
      Serial.println(httpResponseCode);
    }
    http.end();

  } else {
    Serial.println("Wi-Fi disconnected!");
  }
  delay(10000);
}

No hay comentarios:

Publicar un comentario