The below steps explain the process to get to a millis() based approach. Demonstrated for Function_2(), I'll leave the other function to you.
In a first step, replace the for-loop
void Function_2()
{
// counter replacing i of the for-loop
static byte counter = 0;
digitalWrite(led2, HIGH);
delay(500);
digitalWrite(led2, LOW);
delay(500);
// increment the counter
counter++;
// if the required number of iterations is completed
if(counter == 5)
{
// reset the counter
counter = 0;
}
}
This uses a static local variable; static local variables are like global variables (so they will be remembered), but only known to the function.
If you simply call this function from loop(), the result will behave the same as the original. E.g.
void loop()
{
Function_2();
}
Next you need to implement a millis() based approach
void Function_2()
{
// counter replacing i of the for-loop
static byte counter = 0;
// variable to keep track of the start time of a delay
static unsigned long delayStartTime;
// variable to keep track of the ledState
static byte ledState = HIGH;
// check if it's time to change the led
if(millis() - delayStartTime >= 500)
{
// change the led
digitalWrite(led2, ledState);
// set a new start time for the delay
delayStartTime = millis();
// change the ledState for the next time that we need to change it
ledState = !ledState;
}
// increment the counter
counter++;
// if the required number of iterations is completed
if(counter == 10)
{
// reset the counter
counter = 0;
}
}
Note that the couter now goes to 10 (5x on, 5x off).
Sometimes you might want to know if a complete 'for-loop' is completed. The function can return a bool variable to indicate this.
/*
blink led2 every 500ms
Returns:
true if blink cycle completed, else false
*/
bool Function_2()
{
// counter replacing i of the for-loop
static byte counter = 0;
// variable to keep track of the start time of a delay
static unsigned long delayStartTime;
// variable to keep track of the ledState
static byte ledState = HIGH;
// check if it's time to change the led
if(millis() - delayStartTime >= 500)
{
// change the led
digitalWrite(led2, ledState);
// set a new start time for the delay
delayStartTime = millis();
// change the ledState for the next time that we need to change it
ledState = !ledState;
}
// increment the counter
counter++;
// if the required number of iterations is completed
if(counter == 10)
{
// reset the counter
counter = 0;
// indicate to caller that a full cycle was completed
return true;
}
else
{
return false;
}
}
In loop(), you can now read buttons without having to wait for a cycle to be completed.
The below demonstrates how the return value can be used. It will do one cycle of 5 flashes and after that hang forever.
void loop()
{
bool rc = Function_2();
if (rc == true)
{
for (;;);
}
}
All this migt need some polishing depending on your exact needs.