Hello, I'm new to Arduino and trying to figure out how to make multiple LED's blink at specified times for a specific amount of time after a button is pressed. Once the LED's go through their designated routine the program should end, until the button is pressed again and everything repeats.
I'm having difficulty grasping how to use a 4 pin push button to run the program when pressed in conjunction with millis. I will post the code I have so far, and I understand why it's not working (as soon as the button is released the loop ends and "myFunction" stops running. I'm just not sure how to fix it so that the function loops properly. Should I be using for or WHILE loops in the function or something? Thanks for any help.
int ledPin = 8; // choose the pin for the LED
int buttonPin = 7; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
// On and Off Times (as int, max=32secs)
const unsigned int onTime = 1000;
const unsigned int offTime = 200;
// Interval is how long we wait
int interval = onTime;
// Used to track if LED should be on or off
boolean LEDstate = true;
long previousMillis = 0; // will store last time LED was updated
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(buttonPin, INPUT); // declare pushbutton as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(buttonPin); // READ INPUT VALUE FOR BUTTON
if (val == HIGH) { // IF BUTTON IS DOWN
myFunction();
}
}
void myFunction(){
digitalWrite(8, LEDstate);
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (LEDstate) {
interval = offTime;
} else {
interval = onTime;
}
LEDstate = !(LEDstate);
previousMillis = currentMillis;
}
}