// ==== Pin Definitions ====
// Relay Control (Outputs)
const int FAN1_RELAY = 5;
const int FAN2_RELAY = 4;
const int LIGHT1_RELAY = 2;
const int LIGHT2_RELAY = 15;
const int LIGHT3_RELAY = 13;
// Manual Toggles (Inputs)
const int FAN1_BTN = 18;
const int FAN2_BTN = 19;
const int LIGHT1_BTN = 21;
const int LIGHT2_BTN = 22;
const int LIGHT3_BTN = 23;
// Sensor & Status
const int CURRENT_SENSOR = 34; // ACS712 analog in
const int STATUS_LED = 27; // Heartbeat
// ==== State Tracking ====
bool f1_state = false;
bool f2_state = false;
bool l1_state = false;
bool l2_state = false;
bool l3_state = false;
// Button Last States (for debouncing/edge detection)
bool last_f1 = LOW, last_f2 = LOW, last_l1 = LOW, last_l2 = LOW, last_l3 = LOW;
unsigned long lastHeartbeat = 0;
unsigned long lastSerialPrint = 0;
void setup() {
Serial.begin(115200);
// Set Relay pins as outputs
pinMode(FAN1_RELAY, OUTPUT);
pinMode(FAN2_RELAY, OUTPUT);
pinMode(LIGHT1_RELAY, OUTPUT);
pinMode(LIGHT2_RELAY, OUTPUT);
pinMode(LIGHT3_RELAY, OUTPUT);
pinMode(STATUS_LED, OUTPUT);
// Set Button pins as inputs with internal pulldowns
pinMode(FAN1_BTN, INPUT_PULLDOWN);
pinMode(FAN2_BTN, INPUT_PULLDOWN);
pinMode(LIGHT1_BTN, INPUT_PULLDOWN);
pinMode(LIGHT2_BTN, INPUT_PULLDOWN);
pinMode(LIGHT3_BTN, INPUT_PULLDOWN);
// Analog input for ACS712
pinMode(CURRENT_SENSOR, INPUT);
}
// Function to handle toggling logic
void handleButton(int pin, bool &lastState, bool &relayState, int relayPin) {
bool currentState = digitalRead(pin);
// Detect low-to-high transition (button press)
if (currentState == HIGH && lastState == LOW) {
relayState = !relayState; // Toggle the state
digitalWrite(relayPin, relayState ? HIGH : LOW);
delay(50); // Simple debounce
}
lastState = currentState;
}
void loop() {
// 1. Scan Inputs and Update Relays
handleButton(FAN1_BTN, last_f1, f1_state, FAN1_RELAY);
handleButton(FAN2_BTN, last_f2, f2_state, FAN2_RELAY);
handleButton(LIGHT1_BTN, last_l1, l1_state, LIGHT1_RELAY);
handleButton(LIGHT2_BTN, last_l2, l2_state, LIGHT2_RELAY);
handleButton(LIGHT3_BTN, last_l3, l3_state, LIGHT3_RELAY);
// 2. Handle Heartbeat LED (blinks every 500ms)
if (millis() - lastHeartbeat >= 500) {
lastHeartbeat = millis();
digitalWrite(STATUS_LED, !digitalRead(STATUS_LED)); // Toggle LED status
}
// 3. Read Analog Sensor (simulating printing to serial every 2 seconds)
if (millis() - lastSerialPrint >= 2000) {
lastSerialPrint = millis();
int sensorValue = analogRead(CURRENT_SENSOR);
Serial.print("ACS712 Simulated Analog Value: ");
Serial.println(sensorValue);
}
delay(10); // Yield slightly to prevent Watchdog Timer crashes
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4