#include <WiFi.h>
#include <HTTPClient.h>
// -------- WiFi --------
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// -------- ThingSpeak --------
String apiKey = "YOUR_API_KEY"; // Paste your Write API Key
const char* server = "http://api.thingspeak.com/update";
// -------- Pin Definitions --------
#define TRIG_PIN 5
#define ECHO_PIN 18
#define LED_PIN 2
#define GAS_PIN 34
#define PIR_PIN 27
#define LDR_PIN 35
// -------- Settings --------
const int binHeight = 30; // cm
int gasThreshold = 2000;
int ldrThreshold = 1500; // adjust in Wokwi
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(GAS_PIN, INPUT);
pinMode(PIR_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
// WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected");
}
void loop() {
// -------- Ultrasonic --------
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2;
float wasteLevel = ((binHeight - distance) / binHeight) * 100;
wasteLevel = constrain(wasteLevel, 0, 100);
// -------- LDR --------
int lightValue = analogRead(LDR_PIN);
bool isDark = lightValue < ldrThreshold;
// -------- Serial --------
Serial.println("---- SENSOR DATA ----");
Serial.print("Waste Level: "); Serial.print(wasteLevel); Serial.println(" %");
Serial.print("Gas Value: "); Serial.println(gasValue);
Serial.print("Motion: "); Serial.println(motionDetected ? "Detected" : "No");
Serial.print("Light Value: "); Serial.println(lightValue);
Serial.println(isDark ? "Night / Low Light" : "Day / Bright");
// -------- Alert Logic --------
if (wasteLevel >= 80 || gasValue > gasThreshold || motionDetected == HIGH || isDark) {
digitalWrite(LED_PIN, HIGH);
Serial.println("⚠ ALERT CONDITION!");
} else {
digitalWrite(LED_PIN, LOW);
}
// -------- ThingSpeak --------
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = server + String("?api_key=") + apiKey +
"&field1=" + String(wasteLevel) +
"&field2=" + String(gasValue) +
"&field3=" + String(motionDetected) +
"&field4=" + String(lightValue);
http.begin(url);
http.GET();
http.end();
}
delay(15000);
}