Hi, I'm implementing an anti-consumption home automation system, with an LED (analogy of a chandelier), and two buttons, one to turn on/off the LED, the other to: restart the whole system with an interrupt to avoid power surges. The code seems to work, i would however try to bring the model of this code into reality, also because if a chandelier exceeds a certain power in terms of watts, the light goes out, i would also like to pin it on the EEPROM and print it to serial monitor. i would like to bring this problem into the real world, make it 100% true. I would like ideas of implementations in the code that would turn this simulation into reality.
Code with interrupt
#include <EEPROM.h>
int ledPin = 9;
int buttonPin = 3;
int ledState = LOW;
int buttonState = LOW;
int debounceDelay = 50;
unsigned long lastDebounceTime = 0;
int lastButtonReading = LOW;
unsigned long ledOnTime = 0;
const float ledPower = 60; //in watt to simulate chandelier
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(ledPin, ledState);
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(2), resetSystem, FALLING);
}
void loop() {
int buttonReading = digitalRead(buttonPin);
if (buttonReading != lastButtonReading) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (buttonReading != buttonState && buttonReading == HIGH) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
if (ledState == HIGH) {
ledOnTime = millis();
} else {
unsigned long elapsedTime = (millis() - ledOnTime) / 1000;
Serial.print("LED on time: ");
Serial.print(elapsedTime);
Serial.println(" seconds");
float energyConsumption = (ledPower * elapsedTime) / 1000.0;
Serial.print("Energy consumption: ");
Serial.print(energyConsumption, 3);
Serial.println(" kWh");
EEPROM.put(0, energyConsumption);
Serial.println("Energy consumption saved in EEPROM.");
}
}
buttonState = buttonReading;
}
lastButtonReading = buttonReading;
delay(10);
}
void resetSystem() {
ledState = LOW;
buttonState = LOW;
lastDebounceTime = 0;
asm volatile (" jmp 0");
}