#include <DHT.h>
// 1. Pin Definitions (Kept exactly the same as your original code)
#define relay1 14
#define relay2 27
#define relay3 26
#define relay4 25
#define switch1 23
#define switch2 22
#define switch3 32
#define switch4 33
#define DHTTYPE DHT11
#define DHT11Pin 2
// 2. State Variables
unsigned char relay1_state = 1; // 1 = OFF, 0 = ON (Active Low)
unsigned char relay2_state = 1;
unsigned char relay3_state = 1;
unsigned char relay4_state = 1;
DHT dht(DHT11Pin, DHTTYPE);
unsigned long previousMillis = 0;
void setup() {
Serial.begin(115200);
dht.begin();
// Set Relay Pins
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(relay3, OUTPUT);
pinMode(relay4, OUTPUT);
// Initial State: All OFF (High)
digitalWrite(relay1, HIGH);
digitalWrite(relay2, HIGH);
digitalWrite(relay3, HIGH);
digitalWrite(relay4, HIGH);
// Set Switch Pins with Internal Pullup
pinMode(switch1, INPUT_PULLUP);
pinMode(switch2, INPUT_PULLUP);
pinMode(switch3, INPUT_PULLUP);
pinMode(switch4, INPUT_PULLUP);
Serial.println("System Started: Offline Mode");
Serial.println("Manual Switch Control + Auto Heat Safety Enabled");
}
void loop() {
// --- PART 1: MANUAL SWITCH CONTROL ---
checkSwitch(switch1, relay1, relay1_state, "Relay 1");
checkSwitch(switch2, relay2, relay2_state, "Relay 2");
checkSwitch(switch3, relay3, relay3_state, "Relay 3");
checkSwitch(switch4, relay4, relay4_state, "Relay 4");
// --- PART 2: AUTOMATIC SENSOR LOGIC ---
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 2000) { // Check every 2 seconds
previousMillis = currentMillis;
float temp = dht.readTemperature();
if (!isnan(temp)) {
Serial.print("Current Temp: ");
Serial.print(temp);
Serial.println("C");
// AUTO LOGIC: If temp > 32C, force Relay 1 ON (Fan)
if (temp > 32.0) {
Serial.println("!!! OVERHEAT: Auto-starting Relay 1 !!!");
digitalWrite(relay1, LOW);
relay1_state = 0;
}
}
}
}
// Helper function to handle button presses without "freezing" the code
void checkSwitch(int switchPin, int relayPin, unsigned char &state, String name) {
if (digitalRead(switchPin) == LOW) {
delay(50); // Small debounce
if (digitalRead(switchPin) == LOW) {
state = !state; // Toggle state
digitalWrite(relayPin, state);
Serial.print(name);
Serial.println(state == 0 ? " turned ON" : " turned OFF");
// Wait for button release so it doesn't flicker
while (digitalRead(switchPin) == LOW) {
delay(10);
}
}
}
}