// Sketch to toggle a relay and an LED with a push button.
// - When the relay is active, an LED connected to it will blink.
// - An LED connected directly to Arduino will blink based on button presses, independent of the relay.
#define relayOn LOW
#define ledOn LOW
#define relayOff HIGH
#define ledOff HIGH
const int ledPin = 4; // LED directly connected to Arduino
const int ledRelayPin = 7; // LED connected through relay
const int buttonPin = 2;
int relayState = relayOff; // the current state of the relay
int ledState = ledOff; // the current state of the led
int previousButtonState = LOW; // the previous state of the button
unsigned long buttonTime = 0; // The last time the relay state was toggled
unsigned long debounceTime = 400; // debounce time (for noisy buttons)
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(ledRelayPin, OUTPUT);
// Explicitly set the LEDs to off
digitalWrite(ledPin, ledOff);
digitalWrite(ledRelayPin, relayOff);
}
void loop() {
int buttonState = digitalRead(buttonPin);
// Toggle relay state logic
if (buttonState == LOW && previousButtonState == HIGH && millis() - buttonTime > debounceTime) {
relayState = (relayState == relayOff) ? relayOn : relayOff;
ledState = (ledState == ledOff) ? ledOn : ledOff; // Toggle the LED's blinking state
buttonTime = millis();
}
// Blinking logic for LED connected to relay
if (relayState == relayOn) {
digitalWrite(ledRelayPin, (millis() % 900 < 300) ? relayOn : relayOff);
} else {
digitalWrite(ledRelayPin, relayOn);
}
// Blinking logic for LED connected directly to Arduino
if (ledState == ledOn) {
digitalWrite(ledPin, (millis() >> 9) & 3); //Blink
} else {
digitalWrite(ledPin, ledOn);
}
previousButtonState = buttonState;
}