// https://forum.arduino.cc/t/sequencing-7-red-leds/1198584
// https://wokwi.com/projects/383651205978330113
/*
Fun with millis()
A simple solution for a Larson Scanner
KITT
*/
const int ledPin[] = {2, 3, 4, 5, 6, 7, 8}; // the number of the LED pins
byte ledState = 0; // ledState used to set active LED
char direction = 'U'; // Up or Down
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 333; // interval at which to blink (milliseconds)
const size_t noOfLeds = sizeof(ledPin) / sizeof(ledPin[0]); // calculate the number of LEDs in the array
void setup() {
for (size_t i = 0; i < noOfLeds; i++)
{
pinMode(ledPin[i], OUTPUT);
}
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
digitalWrite(ledPin[ledState], LOW); // switch off "old" LED
if (direction == 'U') {
if (ledState < noOfLeds - 1) { // we can increase
ledState++;
}
else {
ledState--; // we have to decrease
direction = 'D'; // and turn direction
}
}
else { // this is an implicit direction == 'D'
if (ledState > 0) { // we can decrease
ledState--;
}
else {
ledState++; // we must increase
direction = 'U'; // and turn direction
}
}
digitalWrite(ledPin[ledState], HIGH);
}
}