#include <WiFi.h>
#include <DHTesp.h>
#include <HTTPClient.h>
// Replace with your WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// DHT sensor pin and type
const int DHT_PIN = 4;
const DHTesp dhtSensor(DHT_PIN, DHTTYPE DHT22); // DHT 22 sensor
// Google Apps Script function URL (replace with yours)
const char* googleSheetUrl = "https://script.google.com/macros/s/AKfycbzHJ2NzKfCXPy6A3WkgNVMa4zu3gbN_3munFP49vtvqzZaeo6O1BpSR1Vx3eKx8xhJD/exec";
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi!");
// Start DHT sensor
dhtSensor.begin();
}
void loop() {
// Read temperature and humidity
delay(2000); // Adjust reading interval as needed
float temp = dhtSensor.readTemperature();
float humidity = dhtSensor.readHumidity();
// Check if any reads failed and exit early (to avoid NaN values)
if (isnan(temp) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Create HTTP client and request
HTTPClient http;
http.begin(googleSheetUrl);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Prepare data to send (replace with your column names)
String data = "temperature=" + String(temp) + "&humidity=" + String(humidity);
// Send POST request
int httpCode = http.POST(data);
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Server response: " + payload);
} else {
Serial.print("HTTP POST request failed with error code: ");
Serial.println(httpCode);
}
http.end();
}