const int buttonPin = 2; // Define the button pin
const int ledPin = 3; // Define the relay control pin
const int relayPin = 4; // Define the relay control pin
bool relayState = LOW; // Initialize the relay state to OFF
bool lastButtonState = LOW; // Initialize the button's previous state
unsigned long lastDebounceTime = 0; // Initialize the debounce time
unsigned long debounceDelay = 50; // Delay in milliseconds
int blinkCount = 0; // Initialize the blink counter
int blinkTarget = 6; // Number of times to blink the relay
int delayBlink = 700; // ms between ticks
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as an input with a pull-up resistor
pinMode(relayPin, OUTPUT); // Set the relay pin as an output
digitalWrite(relayPin, relayState); // Initialize the relay state
}
void loop() {
int buttonState = digitalRead(buttonPin); // Read the current button state
unsigned long currentTime = millis(); // Get the current time
// Check if the button state has changed and debounce it
if (buttonState != lastButtonState) {
lastDebounceTime = currentTime;
}
// Check if the button state has been stable for the debounce delay
if ((currentTime - lastDebounceTime) > debounceDelay) {
// If the button has been pressed, start blinking the relay
if (buttonState == LOW) {
for (int i = 0; i <= blinkTarget; i++) {
digitalWrite(ledPin, HIGH);
digitalWrite(relayPin, HIGH); // Turn off the relay after reaching the target blinks
delay(delayBlink);
digitalWrite(ledPin, LOW);
digitalWrite(relayPin, LOW); // Turn off the relay after reaching the target blinks
delay(delayBlink);
}
// blinkCount = 0; // Reset the blink counter
// // digitalWrite(relayPin, HIGH); // Turn on the relay
// digitalWrite(ledPin, LOW);
// delay(500);
// digitalWrite(ledPin, HIGH);
// delay(500);
}
}
// If the relay is blinking, count the blinks
// if (blinkCount < 6) {
// unsigned long blinkInterval = 1000; // Blink interval in milliseconds (0.5 seconds)
// if (currentTime - lastDebounceTime >= blinkInterval) {
// lastDebounceTime = currentTime;
// }
// }
// Update the last button state
lastButtonState = buttonState;
}