#define BLYNK_TEMPLATE_ID "TMPL3jc0Be67m"
#define BLYNK_TEMPLATE_NAME "POWER TRACK"
#define BLYNK_AUTH_TOKEN "Q4Ob8jskdLuZbUSUb6BpvhCMxFIKiH8U"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
char auth[] = "Q4Ob8jskdLuZbUSUb6BpvhCMxFIKiH8U";
double units = 0;
double price = 0;
const int ledPin = 27; // Pin connected to the LED on ESP32
const int ldrPin = 2; // Pin connected to the LDR
const int ldrThreshold = 1500; // LDR value threshold for detecting dark to bright transition
const int ldrHighThreshold = 2000; // LDR value threshold for considering it as HIGH state
const int blinkDelay = 500; // Adjust the delay based on your requirements for the loop
const int debounceDelay = 50; // Debounce delay to prevent false triggers
int ledState = LOW; // Variable to store the current state of the LED
int lastLdrState = LOW; // Variable to store the previous state of the LDR
int lastDebounceTime = 0; // Variable to store the last time the input was debounced
int blinkCount = 0; // Variable to store the count of LED blinks
BlynkTimer timer;
// This function sends LED blink count to Blynk app
void sendUnits()
{
Blynk.virtualWrite(V2, units);
}
void sendPrice()
{
Blynk.virtualWrite(V3, price);
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);
// Setup a function to be called every second
timer.setInterval(1000L, sendUnits);
timer.setInterval(1000L, sendPrice);
}
void loop() {
Blynk.run();
timer.run();
int ldrValue = analogRead(ldrPin);
// Check if LDR state has changed (detects a transition from dark to bright)
if (ldrValue > ldrThreshold && lastLdrState == LOW) {
// Record the time when the state change occurred
lastDebounceTime = millis();
}
// Check if enough time has passed since the last state change to debounce
if ((millis() - lastDebounceTime) > debounceDelay) {
// Toggle the LED state
ledState = !ledState;
digitalWrite(ledPin, ledState);
if (ledState == HIGH) {
blinkCount++;
Serial.print("LED Blink Count: ");
Serial.println(blinkCount);
}
}
// Update the LDR state
lastLdrState = (ldrValue > ldrHighThreshold) ? HIGH : LOW;
delay(blinkDelay);
units = blinkCount/10;
// price of electricity
if (units<=100)
price = units * 3.4;
else if (units>100 and units <= 200)
price = units * 4.8;
else if (units>200 and units <= 300)
price = units * 7.7;
else if (units>300 and units <= 400)
price = units * 9;
else if (units>400 and units <= 800)
price = units * 9.5;
else
price = units * 10;
}