You need to maintain more state information to have 'case 3' work like a KITT-style back and forth LED scanner. I think you can do it with three state variables, j for which pair of LEDs is active, backwardsScan to say which way to go, and timer4 to remember where in the 91ms cycle we are with the active pair of LEDs.

Try something like this:

...
int backwardsScan = 0;
...

case 3: // KITT-like scanning back and forth 90us/1us
  // j remembers which LED pair is active
  // backwardsScan remembers which direction to scan
  // timer4 handles the 90ms/1ms on-off cycle.
  // 
  // reset output leds appropriately for (j,timer4):
  for(int ii=0;ii<=5;ii++){
    digitalWrite(ledArray[ii],( (ii==j) && (timer4 <90))); 
  }
  // update KITT state based on (j,backwardsScan,timer4)
  if(timer4 > 91){ 
     j += backwardsScan? -1 : 1 ;
     if (j > 5){
        backwardsScan = 1;
        j = 5;
        }
     if (j < 0) {
        backwardsScan = 0;
        j = 0;
        }
     timer4 = 0;
     }

  break;

The main trick with state machines is being able to fully determine the complete state from what you are keeping track of--It should be memoryless, in that the state variable(s) fully specify the state, and you don't need to remember the prior state. If you find you need to know more than one thing, you might need a vector or set of state variables. One could map the whole led-backwardsScan-timer4 state vector into a single state variable (timer4, modulo 182ms for example,) but that would be unnecessarily complicated. Recognizing all the variables required to fully specify the state is important.

Answer from Dave X on Stack Exchange
🌐
Arduino
docs.arduino.cc › libraries › elapsedmillis
elapsedMillis | Arduino Documentation
August 1, 2024 - elapsedMillis · Home / Programming / Library / elapsedMillis · Timing · MIT License · V1.0.6 · Paul Stoffregen · 08/01/2024 · Peter Feerick <peter.feerick@gmail.com> http://github.com/pfeerick/elapsedMillis/wiki · peter.feerick@gmail.com · Makes coding responsive sketches easier.
🌐
GitHub
github.com › pfeerick › elapsedMillis
GitHub - pfeerick/elapsedMillis: Arduino 'port' of the elapsedMillis library · GitHub
Arduino 'port' of the elapsedMillis library. Contribute to pfeerick/elapsedMillis development by creating an account on GitHub.
Starred by 89 users
Forked by 26 users
Languages   C++
Discussions

millis() vs. elapsedMillis ?
It also eliminates any perceived issue with millis() rollover So does subtraction due to how integer overflow is handled by basically all relatively modern ALUs, including the AVR's as well as GCC's uint32_t code - so both of your code samples are functionally identical, but one simply moves a bit of it to a library. A disadvantage is the minor "time slippage" that occurs in the delay between the compare if (TaskTimer > TaskDelay) and resetting the timer taskTimer = 0. Which is precisely why I use if ((millis() - nextTime) & ~(~0UL >> 1)) { nextTime += timeout; doStuff(); } or similar instead of calling millis() a second time. If your elapsedMillis library was sensible, you'd be able to feed a timeout to its constructor then implement the above in a bool operator()() so your main project would basically become elapsedMillis taskTimer(300) ... if (taskTimer()) { doStuff; } What's your preferred method, and why? In addition to the above technique, here's an old project where I use timer flags from an interrupt for timed events if you're curious for other ways to approach things - including some fractional integer accumulation just for fun. More on reddit.com
🌐 r/arduino
2
3
March 16, 2021
are there any DISadvantages in using lib elapsedMillis() over millis() ?
Hi everybody, I just came across the library elapsedMillis.h which can be installed with the Arduino-IDE-libraby manager This library offers variables that get updated automatically every millisecond / microsecond So … More on forum.arduino.cc
🌐 forum.arduino.cc
7
0
January 3, 2021
millis - Question about ElapsedMillis() library and state machines - Arduino Stack Exchange
I'm making a sort of state machine with 3 states, and I'm actually doing some tests by configuring at the start of my code state=3. I've wired on each pin 2 leds, for a total of 12 leds. I'm using More on arduino.stackexchange.com
🌐 arduino.stackexchange.com
December 11, 2021
Help with elapsedMillis!
I am trying to program a timer that can be reset/retriggered by a digital input. I stumbled upon the "elapsedMillis" library which seems like it would do just what I need. However, I cannot get anywhere with it. When I u… More on forum.arduino.cc
🌐 forum.arduino.cc
0
0
March 13, 2014
🌐
Reddit
reddit.com › r/arduino › millis() vs. elapsedmillis ?
r/arduino on Reddit: millis() vs. elapsedMillis ?
March 16, 2021 -

I'm thinking about writing an article* about how to implement cooperative multi-tasking on Arduino-compatible microcontrollers. Working title: Beyond "Blink without Delay". Much of the article will talk about ways structure a program to simplify the handling of multiple concurrent "tasks" with different timing requirements, based on my own experience.

At a lower level, I'd like to discuss the pros and cons of the various methods to measure task time intervals. At minimum I'll cover the blink-without-delay method based on millis(), as well as the elapsedMillis library. I've tried a few different methods, including the Ticker library, but have come to rely exclusively on elapsedMillis for all my projects. But before I go off and profess my love for elapsedMillis, I'd like to get your input.

For reference, here's a brief synopsis of the blink-without-delay/millis() method:

unsigned long currentTime, previousTime;
unsigned int taskDelay = 300;
void loop() {
  currentTime = millis();
  if ((currentTime - previousTime) > taskDelay) {
    previousTime = currentTime;    
    // Perform task 
  }
}  

And here's the elapsedMillis equivalent:

elapsedMillis taskTimer;
unsigned int taskDelay = 300;
void loop() {
  if (taskTimer > taskDelay) {
    taskTimer = 0;
    // Perform task
  }
}

The key advantage of the elapsedMillis method is that the code is more concise and readable. It also eliminates any perceived issue with millis() rollover (which isn't really an issue with unsigned variables).

A disadvantage is the minor "time slippage" that occurs in the delay between the compare if (TaskTimer > TaskDelay) and resetting the timer taskTimer = 0. This is only an issue if the cumulative delays need to maintain long-term timing accuracy (a rare situation I think).

In addition to "going deep" on the two methods shown above, I'l also provide a brief survey of other timing methods, including Ticker and also the EVERY_N_MILLISECONDS method provided by the FastLED library.

What do you folks think? What's your preferred method, and why?

*If you want to see examples of my other articles, check here.

🌐
PJRC
pjrc.com › teensy › td_timing_elaspedMillis.html
Using elapsedMillis & elapsedMicros
#include <Bounce.h> Bounce myButton = Bounce(2, 10); // pushbutton on pin 2 elapsedMillis sincePrint; void setup() { Serial.begin(9600); pinMode(2, INPUT_PULLUP); } void loop() { myButton.update(); if (myButton.fallingEdge()) { Serial.println("Button Press"); } if (myButton.risingEdge()) { Serial.println("Button Release"); } if (sincePrint > 2500) { // "sincePrint" auto-increases sincePrint = 0; Serial.println("Print every 2.5 seconds"); } }
🌐
Arduino Libraries
arduinolibraries.info › libraries › elapsed-millis
elapsedMillis - Arduino Libraries
December 2, 2019 - https://github.com/pfeerick/elapsedMillis/wiki · Github · https://github.com/pfeerick/elapsedMillis · Category · Timing · License · MIT · Library Type · Contributed · Architectures · Any · When using delay(), your code can not (easily) respond to user input while the delay is happening ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
are there any DISadvantages in using lib elapsedMillis() over millis() ? - Programming - Arduino Forum
January 3, 2021 - Hi everybody, I just came across the library elapsedMillis.h which can be installed with the Arduino-IDE-libraby manager This library offers variables that get updated automatically every millisecond / microsecond So the non-blocking blink-example gets as easy and short like this #include // variables of type elapsedMillis get automatically incremented each millisecond elapsedMillis MyTestTimer = 0; const byte OnBoard_LED = 13; void setup() { Serial.begin(115200);...
🌐
Codebender
codebender.cc › example › elapsedMillis › GettingStarted
Library example: elapsedMillis : GettingStarted
<iframe style="height: 510px; width: 100%; margin: 10px 0 10px;" allowTransparency="true" src="https://codebender.cc/embed/example/elapsedMillis/GettingStarted" frameborder="0"></iframe> You can also embed the Serial Monitor section! Just use this HTML code. <iframe style="height: 510px; width: 100%; margin: 10px 0 10px;" allowTransparency="true" src="https://codebender.cc/embed/serialmonitor" frameborder="0"></iframe> ... This example was tested on 2016-06-11 and it compiles on Arduino Uno, Arduino Leonardo, Arduino Mega
🌐
Codebender
codebender.cc › example › elapsedMillis › timingComparison
Library example: elapsedMillis : timingComparison
<iframe style="height: 510px; width: 100%; margin: 10px 0 10px;" allowTransparency="true" src="https://codebender.cc/embed/example/elapsedMillis/timingComparison" frameborder="0"></iframe> You can also embed the Serial Monitor section! Just use this HTML code. <iframe style="height: 510px; width: 100%; margin: 10px 0 10px;" allowTransparency="true" src="https://codebender.cc/embed/serialmonitor" frameborder="0"></iframe> ... This example was tested on 2016-06-11 and it compiles on Arduino Uno, Arduino Leonardo, Arduino Mega.
Find elsewhere
🌐
Rip Tutorial
riptutorial.com › measure how long something took, using elapsedmillis and elapsedmicros
arduino Tutorial => Measure how long something took, using...
#include <elapsedMillis.h> void setup() { Serial.begin(115200); elapsedMillis msTimer; elapsedMicros usTimer; long int dt = 500; delay(dt); long int us = usTimer; long int ms = msTimer; Serial.print("delay(");Serial.print(dt);Serial.println(") took"); Serial.print(us);Serial.println(" us, or"); Serial.print(ms);Serial.println(" ms"); } void loop() { }
Top answer
1 of 1
2

You need to maintain more state information to have 'case 3' work like a KITT-style back and forth LED scanner. I think you can do it with three state variables, j for which pair of LEDs is active, backwardsScan to say which way to go, and timer4 to remember where in the 91ms cycle we are with the active pair of LEDs.

Try something like this:

...
int backwardsScan = 0;
...

case 3: // KITT-like scanning back and forth 90us/1us
  // j remembers which LED pair is active
  // backwardsScan remembers which direction to scan
  // timer4 handles the 90ms/1ms on-off cycle.
  // 
  // reset output leds appropriately for (j,timer4):
  for(int ii=0;ii<=5;ii++){
    digitalWrite(ledArray[ii],( (ii==j) && (timer4 <90))); 
  }
  // update KITT state based on (j,backwardsScan,timer4)
  if(timer4 > 91){ 
     j += backwardsScan? -1 : 1 ;
     if (j > 5){
        backwardsScan = 1;
        j = 5;
        }
     if (j < 0) {
        backwardsScan = 0;
        j = 0;
        }
     timer4 = 0;
     }

  break;

The main trick with state machines is being able to fully determine the complete state from what you are keeping track of--It should be memoryless, in that the state variable(s) fully specify the state, and you don't need to remember the prior state. If you find you need to know more than one thing, you might need a vector or set of state variables. One could map the whole led-backwardsScan-timer4 state vector into a single state variable (timer4, modulo 182ms for example,) but that would be unnecessarily complicated. Recognizing all the variables required to fully specify the state is important.

🌐
GitHub
github.com › pfeerick › elapsedMillis › blob › master › elapsedMillis.h
elapsedMillis/elapsedMillis.h at master · pfeerick/elapsedMillis
Arduino 'port' of the elapsedMillis library. Contribute to pfeerick/elapsedMillis development by creating an account on GitHub.
Author   pfeerick
🌐
Google Groups
groups.google.com › a › arduino.cc › g › developers › c › FAw_W0Vn7kg
Request to have elapsedMillis/elapsedMicros data-type added to standard Arduino
These are all good points.� The variable scope issue has come up a few times over the last couple years.� But overall, feedback from users about elapsedMillis has been very positive.� Everybody seems to "get it" pretty easily.� Then again, Teensy tends to appeal to slightly more technically savvy users, so I wouldn't claim that experience necessarily would apply to all or even many Arduino users.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Help with elapsedMillis! - Programming - Arduino Forum
March 13, 2014 - I am trying to program a timer that can be reset/retriggered by a digital input. I stumbled upon the "elapsedMillis" library which seems like it would do just what I need. However, I cannot get anywhere with it. When I use the example code given at Arduino Playground - elapsedMillis Library #include elapsedMillis timeElapsed; //declare global if you don't want it reset every time loop runs // Pin 13 has an LED connected on most Arduino boards. int led = 13; // delay in mil...
🌐
Arduino Forum
forum.arduino.cc › projects › general guidance
Using elapsedMillis for multiple delays in tone() function - General Guidance - Arduino Forum
January 25, 2019 - Hi! I'm doing a school project but I'm stuck on using Millis for multiple delays. I already checked the forums and BlinkWithoutDelay but still couldn't fix it. I just don't understand ;( The reason why I'm using tone() instead of melody is, because for some kind of reason, I keep getting an ...
🌐
GitHub
github.com › PaulStoffregen › cores › blob › master › teensy › elapsedMillis.h
cores/teensy/elapsedMillis.h at master · PaulStoffregen/cores
#define elapsedMillis_h · #ifdef __cplusplus · · #if ARDUINO >= 100 · #include "Arduino.h" #else · #include "WProgram.h" #endif · · class elapsedMillis ·
Author   PaulStoffregen
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Having trouble with elapsedMillis - Programming - Arduino Forum
April 24, 2017 - First of all I am pretty new to coding in general and probably am just misunderstanding something simple but I cannot seem to figure it out. I am trying to use an arduino to automate a dishwasher to keep it going for many cycles. I have a series of actions that happen to open/close the door ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Arduino - elapsedMillis ERROR - Programming - Arduino Forum
September 25, 2023 - hi, having problems with a segment of code involving elapsedMillis, i have created a time loop so serial out prints every 1 second, this works for 32 seconds and then for some reason the function no longer executes even though it meets the condition, i have placed serial out to check that indeed ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How to implement elapsed millis as the timer for my motor spinning time? - Programming - Arduino Forum
April 8, 2017 - I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.
🌐
GitHub
github.com › pfeerick › elapsedMillis › wiki
Home · pfeerick/elapsedMillis Wiki · GitHub
Arduino 'port' of the elapsedMillis library. Contribute to pfeerick/elapsedMillis development by creating an account on GitHub.
Author   pfeerick