#include "DHT.h"
#include <WiFi.h>
#include "ThingSpeak.h"
// ---------- ThingSpeak Config ----------
const char* ssid = "Wokwi-GUEST"; // WiFi SSID
const char* password = ""; // WiFi password (Wokwi guest has none)
WiFiClient client;
unsigned long myChannelNumber = 3104647; // 👉 Replace with your ThingSpeak Channel ID
const char * myWriteAPIKey = "YLELU7N4ROOM3UCV"; // 👉 Replace with your ThingSpeak Write API Key
// ---------- Sensor + Actuators ----------
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
int ldrPin = 34; // ESP32 analog pin (use 34 instead of A0)
int bulbPin = 2; // Bulb LED on GPIO2
int fanPin = 5; // Fan LED/Motor on GPIO5
int lightThreshold = 2000; // Adjust for ESP32 ADC (0–4095 range)
float tempThreshold = 30.0; // Fan ON if temp > 30°C
void setup() {
Serial.begin(115200);
dht.begin();
pinMode(bulbPin, OUTPUT);
pinMode(fanPin, OUTPUT);
// ---------- WiFi Setup ----------
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
// ---------- Read Sensors ----------
int ldrValue = analogRead(ldrPin);
float temp = dht.readTemperature();
Serial.print("LDR Value: ");
Serial.print(ldrValue);
Serial.print(" | Temperature: ");
Serial.println(temp);
// ---------- Control Bulb ----------
if (ldrValue < lightThreshold) {
digitalWrite(bulbPin, HIGH); // Dark → Bulb ON
} else {
digitalWrite(bulbPin, LOW); // Bright → Bulb OFF
}
// ---------- Control Fan ----------
if (temp > tempThreshold) {
digitalWrite(fanPin, HIGH); // Fan ON
} else {
digitalWrite(fanPin, LOW); // Fan OFF
}
// ---------- Send Data to ThingSpeak ----------
ThingSpeak.setField(1, ldrValue); // Field1 → Light
ThingSpeak.setField(2, temp); // Field2 → Temperature
int status = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (status == 200) {
Serial.println("✅ Data sent to ThingSpeak");
} else {
Serial.println("❌ Problem sending data, HTTP error code " + String(status));
}
delay(20000); // ThingSpeak requires 15+ sec delay between updates
}