#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak settings
const String apiKey = "4TVNWN2ISUY73SPB";
const String channelID = "3088039";
const String server = "http://api.thingspeak.com/update";
// DHT settings
#define DHTPIN 15 // GPIO pin for DHT
#define DHTTYPE DHT22 // Change to DHT11 if using DHT11
DHT dht(DHTPIN, DHTTYPE);
// LDR settings
#define LDRPIN 34 // Analog pin for LDR (GPIO 34)
void setup() {
Serial.begin(115200);
delay(100);
dht.begin();
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi!");
}
void loop() {
// Read temperature from DHT
float temperature = dht.readTemperature();
// Read light level from LDR
int ldrValue = analogRead(LDRPIN);
// Check if readings are valid
if (isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Light Level: ");
Serial.println(ldrValue);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = server + "?api_key=" + apiKey +
"&field1=" + String(temperature) +
"&field2=" + String(ldrValue);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.print("Data sent. Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error sending data. Code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi not connected!");
}
delay(15000); // ThingSpeak requires at least 15 seconds between updates
}