// Define Relay Control Pin
const int relayPin = 8;
// Time configurations (Adjust these variables as needed)
const unsigned long TIME_ON = 5000; // How long the appliance stays ON (5 seconds)
const unsigned long TIME_OFF = 7000; // How long the appliance stays OFF (7 seconds)
// Tracking variables
unsigned long previousMillis = 0;
bool isRelayActive = false;
void setup() {
// Configure the relay control pin as an output
pinMode(relayPin, OUTPUT);
// Set initial state to OFF
digitalWrite(relayPin, LOW);
// Initialize the Serial Monitor
Serial.begin(9600);
Serial.println("--- Time-Controlled Relay System Online ---");
Serial.print("Cycle Configured: OFF for ");
Serial.print(TIME_OFF / 1000);
Serial.print("s, then ON for ");
Serial.print(TIME_ON / 1000);
Serial.println("s.");
}
void loop() {
// Get the current running runtime of the microcontroller
unsigned long currentMillis = millis();
// Check the current state of our timer track
if (isRelayActive) {
// If the relay is currently ON, check if it's time to turn it OFF
if (currentMillis - previousMillis >= TIME_ON) {
digitalWrite(relayPin, LOW); // Turn off physical relay
isRelayActive = false; // Update software state tracker
previousMillis = currentMillis; // Reset time marker
Serial.println("[TIMER EVENT] Relay turned OFF. Safe cycle resting...");
}
}
else {
// If the relay is currently OFF, check if it's time to turn it ON
if (currentMillis - previousMillis >= TIME_OFF) {
digitalWrite(relayPin, HIGH); // Turn on physical relay
isRelayActive = true; // Update software state tracker
previousMillis = currentMillis; // Reset time marker
Serial.println("[TIMER EVENT] Relay activated! Load is powered ON.");
}
}
}