#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define DHTPIN 4 // GPIO for DHT22
#define DHTTYPE DHT22
#define LDR_PIN 34 // Analog pin for LDR
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverURL ="https://ec78-2409-40f4-201d-957b-c471-b708-b377-ccce.ngrok-free.app/data";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(1000);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nConnected!");
} else {
Serial.println("\nFailed to connect. Restarting...");
ESP.restart();
}
dht.begin();
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
int lightIntensity = analogRead(LDR_PIN);
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Construct JSON payload
String payload = "{\"temperature\":" + String(temperature) +
", \"humidity\":" + String(humidity) +
", \"light\":" + String(lightIntensity) + "}";
http.begin(serverURL); // Initialize HTTP connection
http.addHeader("Content-Type", "application/json"); // Ensure correct format
int httpResponseCode = http.POST(payload); // Send data
Serial.println("Data Sent: " + payload);
Serial.println("Response: " + String(httpResponseCode));
http.end(); // Close connection
}
delay(5000); // Wait before the next request to prevent overload
}