#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <ESP32Servo.h>
#define DHTPIN 15
#define DHTTYPE DHT11
#define PIRPIN 14
#define LDRPIN 13
#define TRIGPIN 12
#define ECHOPIN 27
#define SERVOPIN 26
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* apiKey = "5NSOEEHW6WZHY042";
const char* channelID = "3023129";
DHT dht(DHTPIN, DHTTYPE);
Servo myServo;
void setup() {
Serial.begin(115200);
dht.begin();
pinMode(PIRPIN, INPUT);
pinMode(LDRPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(ECHOPIN, INPUT);
myServo.setPeriodHertz(50);
myServo.attach(SERVOPIN, 500, 2400);
myServo.write(0);
// Connect to WiFi
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 sensor values
float temp = dht.readTemperature();
float hum = dht.readHumidity();
int motionDetected = digitalRead(PIRPIN);
int light = digitalRead(LDRPIN);
// Ultrasonic distance
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
long duration = pulseIn(ECHOPIN, HIGH);
float distance_cm = duration * 0.034 / 2;
// Control Servo
if (distance_cm > 100) {
myServo.write(90);
} else {
myServo.write(0);
}
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "http://api.thingspeak.com/update?api_key=";
url += apiKey;
url += "&field1=" + String(temp);
url += "&field2=" + String(hum);
url += "&field3=" + String(distance_cm);
url += "&field4=" + String(light);
url += "&field5=" + String(motionDetected);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("Data sent to ThingSpeak.");
} else {
Serial.print("Error sending data: ");
Serial.println(http.errorToString(httpCode));
}
http.end();
}
// Print data locally
Serial.println("----- Sensor Readings -----");
Serial.print("Temp: "); Serial.println(temp);
Serial.print("Humidity: "); Serial.println(hum);
Serial.print("Distance: "); Serial.println(distance_cm);
Serial.print("Light: "); Serial.println(light ? "Bright" : "Dark");
Serial.print("Motion: "); Serial.println(motionDetected ? "YES" : "NO");
Serial.println("---------------------------\n");
delay(20000); // ThingSpeak allows updates every 15s (minimum)
}