// https://wokwi.com/projects/396896548104172545
// https://forum.arduino.cc/t/run-the-function-once-button-is-press/1255473
const int BUTTON_PIN = 7; // Connect the Button to pin 7 or change here
const int LED_PIN = 13;
// variables will change:
int ledState = LOW; // tracks the current state of LED
int lastButtonState; // the previous state of button
int currentButtonState; // the current state of button
int time = 0;
int counter = 0;
int current_time=0;
// relay variable
int Relay[4] = {A0, A1, A2, A3};
void Show();
void Show_off();
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
currentButtonState = digitalRead(BUTTON_PIN);
for (int i = 0; i < 4; i++)
pinMode(Relay[i], OUTPUT);
pinMode(LED_PIN,OUTPUT);
}
void loop() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
// if you need to here: Serial.println(currentButtonState);
if (lastButtonState == HIGH && currentButtonState == LOW) {
Serial.print("The button is pressed: ");
// Show();
// toggle state of LED
if(ledState == LOW) {
ledState = HIGH;
// Show();
Serial.println("Turning LED on");
}
else {
ledState = LOW;
// Show_off();
Serial.println("Turning LED off");
}
}
// control LED arccoding to the toggled state
digitalWrite(LED_PIN, ledState); //turns the LED on or off based on the variable
// run one of the two machines
if (ledState) Show();
else Show_Off();
delay(20); // poor man's debouncing
}
void Show() {
current_time=millis();
if((current_time-time) >= 100) { // was 1000. life too short
time=current_time;
counter++;
// if you must here: Serial.println(counter);
switch (counter) {
case 5 :
digitalWrite(Relay[0], HIGH);
break;
case 10 :
digitalWrite(Relay[1], HIGH);
break;
case 15 :
digitalWrite(Relay[2], HIGH);
break;
case 20 :
digitalWrite(Relay[03], HIGH);
break;
default:
// turn all the LEDs off:
for (int i = 0; i < 4; i++)
digitalWrite(Relay[i], LOW);
if(counter >= 25)
counter = 0;
break;
}
}
}
void Show_Off(){
for (int i = 0; i < 4; i++)
digitalWrite(Relay[i], LOW);
counter = 0;
}