#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// Replace these with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// ThingSpeak settings
const char* server = "api.thingspeak.com";
const String channelID = "3088505";
const String writeAPIKey = "CJW344I3IBISDG68";
// Pins
#define LDR_PIN 34 // Analog pin for LDR
#define DHTPIN 4 // Digital pin for DHT sensor
#define DHTTYPE DHT22 // DHT22 sensor, change to DHT11 if needed
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
delay(100);
// Initialize DHT sensor
dht.begin();
// Connect to WiFi
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Read sensors
int ldrValue = analogRead(LDR_PIN);
float temperature = dht.readTemperature(); // Celsius
if (isnan(temperature)) {
Serial.println("Failed to read temperature from DHT sensor!");
temperature = 0.0; // Handle error by sending zero or last known value
}
Serial.print("LDR Value: ");
Serial.print(ldrValue);
Serial.print(" | Temperature: ");
Serial.println(temperature);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String("http://") + server + "/update?api_key=" + writeAPIKey
+ "&field1=" + String(ldrValue)
+ "&field2=" + String(temperature);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.print("Response code: ");
Serial.println(httpCode);
Serial.print("Response: ");
Serial.println(payload);
} else {
Serial.print("Error on sending request: ");
Serial.println(httpCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
// ThingSpeak allows updates every 15 seconds
delay(15000);
}