I wrote a function to blink an led using millis and want to blink multiple leds with the same function but with different delay intervals. When I call this function thrice to blink 3 different leds, all the leds blink with the shortest delay. As far my understanding is, functions can be reused if you want to perform same task but why doesn't it work in this case? It works incase I rename the function before calling it again.
Is it wrong to call single function more than once to perform same task but on different pins? How would you call a function without renaming it?
const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;
void setup() {
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}
void loop() {
blinkLed(redLed, 1000);
blinkLed(yellowLed, 4000);
blinkLed(greenLed, 8000);
}
void blinkLed(int led, unsigned long timePeriod) {
static unsigned long oldTime = 0;
unsigned long newTime = millis();
static boolean ledState = LOW;
if (newTime - oldTime >= timePeriod) {
oldTime = newTime;
ledState = !ledState;
}
digitalWrite(led, ledState);
}
Edit: I have modified the function to not have shared variables but it just blinks redLed. why doesn't it work now? Here is the code:
const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;
void setup() {
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}
void loop() {
blinkLed(redLed, 1000);
blinkLed(yellowLed, 4000);
blinkLed(greenLed, 8000);
}
void blinkLed(int led, unsigned long timePeriod) {
switch (led) {
case 10:
static unsigned long oldTime1 = 0;
unsigned long newTime1 = millis();
static boolean redState = LOW;
if (newTime1 - oldTime1 >= timePeriod) {
oldTime1 = newTime1;
redState = !redState;
}
digitalWrite(led, redState);
break;
case 11:
static unsigned long oldTime2 = 0;
unsigned long newTime2 = millis();
static boolean yellowState = LOW;
if (newTime2 - oldTime2 >= timePeriod) {
oldTime2 = newTime2;
yellowState = !yellowState;
}
digitalWrite(led, yellowState);
break;
case 12:
static unsigned long oldTime3 = 0;
unsigned long newTime3 = millis();
static boolean greenState = LOW;
if (newTime3 - oldTime3 >= timePeriod) {
oldTime3 = newTime3;
greenState = !greenState;
}
digitalWrite(led, greenState);
break;
}
}