Hi everyone, I'm trying to make LED blink sequence with different "ON & OFF" interval, I use delay() on my sketch and it's work, here is the sketch:
int timerON = 500; // The higher the number, the slower the timing.
int timerOFF = 200;
int ledPins[] = {
2, 7, 4, 6, 5, 3 }; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
void setup() {
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timerON);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
delay(timerOFF);
}
}
and I try to replace delay() with millis but I get a randomize LED blink, here is the sketch:
int ledPins[] = {
5, 6, 7, 8, 9, 10, 11, 12}; // an array of pin numbers to which LEDs are attached
int pinCount = 8; // the number of pins (i.e. the length of the array)
long previousMillis = 0;
long interval1 = 500;
long interval2 = 1000;
void setup() {
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval1) {
digitalWrite(ledPins[thisPin], LOW);
}
if(currentMillis - previousMillis > interval2) {
digitalWrite(ledPins[thisPin], HIGH);
previousMillis = currentMillis;
}
}
}
What's wrong with my sketch?