#include <WiFi.h>
#include <ThingSpeak.h>
const char* ssid = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char* password = ""; // Replace with your WiFi password
WiFiClient client;
unsigned long myChannelNumber = 2644089; // Replace with your ThingSpeak channel number
const char* myWriteAPIKey = "GEYWVYP8TDDCGMK9"; // Replace with your ThingSpeak Write API Key
const int ldrPin = 34; // LDR connected to GPIO34 (Analog pin)
const int trigPin = 13; // Ultrasonic sensor Trig pin connected to GPIO13
const int echoPin = 12; // Ultrasonic sensor Echo pin connected to GPIO12
const int ledPin = 14; // LED connected to GPIO14
const int thresholdDistance = 200; // Distance threshold in cm
const int lightThreshold = 50; // Light level threshold in LUX
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
ThingSpeak.begin(client);
}
void loop() {
int distance = getDistance();
int lightLevel = analogRead(ldrPin);
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, Light Level: ");
Serial.println(lightLevel);
// Check if the distance is less than the threshold and the light level is low
if (distance < thresholdDistance && lightLevel < lightThreshold) {
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
// Send data to ThingSpeak
ThingSpeak.setField(1, distance);
ThingSpeak.setField(2, lightLevel);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Channel update successful.");
} else {
Serial.print("Problem updating channel. HTTP error code: ");
Serial.println(x);
}
delay(15000); // Delay to avoid too frequent readings
}
int getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2;
return distance;
}