#define BLYNK_TEMPLATE_ID "TMPL6LgMiSOvj"
#define BLYNK_TEMPLATE_NAME "lighting cc"
#define BLYNK_AUTH_TOKEN "Nckr2VMma41casAyz5d7H53k9wVWoKB8"
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
char auth[] = BLYNK_AUTH_TOKEN; // Auth Token
char ssid[] = "Wokwi-GUEST"; // WiFi SSID
char pass[] = ""; // WiFi Password
#define PIR_PIN 2
#define LED_PIN 14
#define LDR_PIN 13
BlynkTimer timer;
bool manualControl = false; // To keep track of manual LED control
// Function to read the LDR value and map it to LED brightness
int getLEDBrightness() {
int ldrValue = analogRead(LDR_PIN);
int ledBrightness;
// Define ranges and map LDR values to brightness
if (ldrValue >= 0 && ldrValue < 1365) {
// Low light
ledBrightness = map(ldrValue, 0, 1364, 255, 170); // Map to a bright range
} else if (ldrValue >= 1365 && ldrValue < 2730) {
// Medium light
ledBrightness = map(ldrValue, 1365, 2729, 169, 85); // Map to a medium range
} else {
// High light
ledBrightness = map(ldrValue, 2730, 4095, 84, 0); // Map to a dim range
}
Serial.print("LDR Value: ");
Serial.println(ldrValue);
return ledBrightness;
}
// Switch control via Blynk
BLYNK_WRITE(V0) {
int buttonState = param.asInt();
if (buttonState == 1) {
manualControl = true;
digitalWrite(LED_PIN, HIGH);
} else {
manualControl = false;
digitalWrite(LED_PIN, LOW);
}
}
// Timer callback function to check brightness
void checkBrightness() {
if (!manualControl) { // Only adjust brightness if manual control is off
int pirState = digitalRead(PIR_PIN);
if (pirState == HIGH) {
// Motion detected
int brightness = getLEDBrightness();
analogWrite(LED_PIN, brightness); // Set LED brightness based on LDR value
Serial.print("Motion detected! LED brightness: ");
Serial.println(brightness);
} else {
// No motion detected
analogWrite(LED_PIN, 0); // Turn off LED
Serial.println("No motion detected. LED off.");
}
}
}
void setup() {
pinMode(PIR_PIN, INPUT); // Set PIR pin as input
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);
timer.setInterval(2000L, checkBrightness); // Check brightness every 2 seconds
}
void loop() {
Blynk.run();
timer.run();
}