#include <WiFi.h>
#include <ThingSpeak.h>
const char* ssid = "Wokwi-GUES"; // Replace with your WiFi SSID
const char* password = " "; // Replace with your WiFi password
const char* thingSpeakApiKey = "6OOO18J9FKBKAU8A"; // Replace with your ThingSpeak API Key
const long myChannelNumber = 2326409; // Replace with your ThingSpeak Channel Number
WiFiClient client;
// Pin assignments
const int pirSensorPin = 23; // Pin connected to PIR motion sensor
const int ultrasonicTriggerPin = 33; // Pin connected to Ultrasonic sensor trigger
const int ultrasonicEchoPin = 12; // Pin connected to Ultrasonic sensor echo
const int switchRelayPin = 26;
int pirState = LOW;
int val = 0; // Pin connected to the switch relay
// Variables
bool isMotionDetected = false; // Flag to track motion detection
void setup() {
// Initialize pins
pinMode(pirSensorPin, INPUT);
pinMode(ultrasonicTriggerPin, OUTPUT);
pinMode(ultrasonicEchoPin, INPUT);
pinMode(switchRelayPin, OUTPUT);
digitalWrite(switchRelayPin, LOW); // Turn off the switch initially
// Initialize Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
// Check PIR motion sensor
val = digitalRead(pirSensorPin); // read input value
if (val == HIGH) {
// ... Your existing code for motion detection
}
// Check Ultrasonic sensor
int distance = measureDistance();
// Update ThingSpeak with the sensor data
ThingSpeak.writeField(myChannelNumber, 1, distance, thingSpeakApiKey);
ThingSpeak.writeField(myChannelNumber, 2, isMotionDetected, thingSpeakApiKey);
// Control switch based on motion and distance
if (isMotionDetected || distance <= 100) {
digitalWrite(switchRelayPin, LOW); // Turn on the switch
} else {
digitalWrite(switchRelayPin, HIGH); // Turn off the switch
}
}
int measureDistance() {
// Send a pulse to the Ultrasonic sensor
digitalWrite(ultrasonicTriggerPin, LOW);
delayMicroseconds(2);
digitalWrite(ultrasonicTriggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(ultrasonicTriggerPin, LOW);
// Measure the duration of the pulse
long duration = pulseIn(ultrasonicEchoPin, HIGH);
// Calculate the distance based on the speed of sound (343 m/s or 0.0343 cm/µs)
int distance = duration * 0.0343 / 2;
return distance;
}