So what I'm trying to achieved in this project is that once the button is pushed("push once, not hold press") the function will start looping.
example that LED_PIN, one i push the button the led will light up and once push again it will switch off. So just think of it that the LED_PIN is like the function i want to switch on.
i tried so many way that i can think of but none of them are working.
i don't know what's the proper approached to achieved this.
so am seeking help with you guys hope u can hep me thank you in advance.
const int BUTTON_PIN = 11; // 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] = {4,5,8,9};
void Show();
void Show_off();
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT); // set arduino pin to input mode
for (int i = 0; i < 4; i++) {
pinMode(Relay[i], OUTPUT);
// set arduino pin to output mode
pinMode(LED_PIN,OUTPUT);
currentButtonState = digitalRead(BUTTON_PIN);
}
}
void loop() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN);
Serial.println(currentButtonState);
// read new state
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
}
}
void Show() {
current_time=millis();
if((current_time-time)>=1000){
counter++;
time=current_time;
Serial.println(counter);
switch (counter) {
case 5 :
digitalWrite(4, HIGH);
break;
case 10 :
digitalWrite(5, HIGH);
break;
case 15 :
digitalWrite(8, HIGH);
break;
case 20 :
digitalWrite(9, HIGH);
break;
default:
// turn all the LEDs off:
for (int i = 0; i < 4; i++) {
digitalWrite(Relay[i], LOW);
if(counter>=25){
counter = 0;
}
}
}
}
}
void Show_off(){
}