Here the sketches behind the Wokwi links: Millis() Function Example /* ============================ Millis() Function Example ============================ This is an example of a non-blocking millis() function replacing delay() First Edition 2023-04-02 ec2021 Simulation:… Answer from ec2021 on forum.arduino.cc
🌐
Reddit
reddit.com › r/arduino › using millis () between for loops
r/arduino on Reddit: Using millis () between for loops
October 3, 2021 -

Hi! I have this simple application with WS2812 Led Ring, which makes a 'wheel' effect, lights the LEDs one after the other. I'm trying to learn how to use millis () with loops, the delay () function causes a pause in the operation of an application, or so I understood.

void loop() {

unsigned long currentTime = millis();

for(s = 0; s < 73; s++){ // 6 colors x 12 LEDs

Serial.println(s); // just print the value

for(s = 0; s < 12; s++){

// here I would write

if ( currentTime - previousTime >= eventTime) { // eventTime = 1000

for(i = 0; i < NUMPIXELS; i++){

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255

pixels.setPixelColor(i, pixels.Color(bright,0,0)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

//delay(delayval); // Delay for a period of time (in milliseconds).

}

if(i==NUMPIXELS){

pixels.clear();

break;}

previousTime = currentTime;}

}// 1st for

for(s = 11; s < 24; s++){

for(j = 0; j < NUMPIXELS; j++){

pixels.setPixelColor(j, pixels.Color(0,bright,0)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // 1s delay

}

if(j==NUMPIXELS){

pixels.clear();

break;}

}// 2st for

//************** other for loops follow

if((s > 71) && (s < 73)){

pixels.setPixelColor(n, pixels.Color(bright,bright,bright)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval);

} // if

}// BIG For

}// loop

You can see that I use several for loops, but I can't create the 1s delay between them with millis (). Where am I wrong ? Where should I put the millis () function?

slowing down a for loop with millis May 23, 2021
r/arduino
5y ago
Run two loops at once? Jul 23, 2024
r/arduino
last yr.
Question about using millis() efficiently Mar 1, 2024
r/arduino
2y ago
More results at reddit.com
🌐
Arduino Forum
forum.arduino.cc › projects › tutorials
Millis() instead of delay and loop() instead of for-loop - Tutorials - Arduino Forum
April 2, 2023 - One of the most frequently asked questions by beginners is how to handle delays and for-loops in loop() without blocking other functions. In this thread I like to publish some small sketches do demonstrate the use of millis() instead of delay() and how to implement the functionality of a for-loop ...
Discussions

Using millis () between for loops [solved]
Hi! I have this simple application with WS2812 Led Ring, which makes a 'wheel' effect, lights the LEDs one after the other. I'm trying to learn how to use millis () with loops, the delay () function causes a pause in the… More on forum.arduino.cc
🌐 forum.arduino.cc
18
0
October 3, 2021
Using millis() in a for loop as delay
Hello all, I'm working on a project that includes an LCD5110. So in the middle of the code progress, I want to make a loading effect by using three dots. I want them to be printed one by one periodically (let's say it's 350 ms). So the first dot comes, after350 ms the second one comes, after ... More on forum.arduino.cc
🌐 forum.arduino.cc
0
0
May 23, 2021
c - Replace delay() with millis inside a for loop Arduino - Stack Overflow
In my code I want to replace the effect of delay() with millis or any other method that allows the use of button inputs while the code still runs. I am making an obstacle-type game where the player... More on stackoverflow.com
🌐 stackoverflow.com
Using millis() for timing. A beginners guide
Part 1 It is not usually long before new Arduino users discover that although the delay() function is easy to use it has side effects, the main one of which is that its stops all activity on the Arduino until the delay is finished (not quite true, I know, but that is usually how the problem ... More on forum.arduino.cc
🌐 forum.arduino.cc
3
42
October 2, 2017
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How to use millis within a for loop [SOLVED] - Programming - Arduino Forum
September 3, 2016 - I understand how to use millis as a replacement for delay except for one part; in for loops. Specifically, I have a chaser with a shift register using hardware SPI but I need to be able to set the delay based on a potentiometer attached to an analog pin and not have to wait the 500 milliseconds ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Using millis() in a for loop as delay - Programming - Arduino Forum
May 23, 2021 - Hello all, I'm working on a project that includes an LCD5110. So in the middle of the code progress, I want to make a loading effect by using three dots. I want them to be printed one by one periodically (let's say it's 350 ms). So the first dot comes, after350 ms the second one comes, after 350 ms the third one comes and after 350 ms, all of the dots go.
🌐
Arduino Forum
forum.arduino.cc › projects › tutorials
Using millis() for timing. A beginners guide - Tutorials - Arduino Forum
October 2, 2017 - Part 1 It is not usually long before new Arduino users discover that although the delay() function is easy to use it has side effects, the main one of which is that its stops all activity on the Arduino until the delay is finished (not quite true, I know, but that is usually how the problem ...
Find elsewhere
Top answer
1 of 5
2

I was wrong being too confident about my whole code. When people suggested posting my whole code, I should have just done it!!!

Anyway, here is the mistake I made. I initialized the variable flash_time as an 8-bit integer. Of course, 8 bit can only hold up to 255. I am trying to store 9000!!! The following code has this bug fixed.

const long sleep_interval = 3000; 
const long awake_interval = 250; 
const int ledPin = 3;

const uint16_t flash_time = 9000;  //bug fixed by using uint16_t instead of uint8_t
const uint16_t t1 = 5; 
const uint16_t t2 = 495;

void flash() {  
    unsigned long x = millis();
    while(millis() - x < flash_time){ 
        digitalWrite(ledPin, HIGH);
        delay(t1);
        digitalWrite(ledPin, LOW);
        delay(t2);
    }   
}   

void setup() {
    Serial.begin(57600);  
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long x = millis();
    while(millis() - x < awake_interval){
        Serial.println("flash time!");
        flash();    
    }

    unsigned long y = millis();; 
    while (millis() - y < sleep_interval) {  //sleep_interval = 3 secs
        Serial.println("Sleep time!");
    }
}

So, nested loops that use millis() to determine the terminating conditions work just fine, even if loop 1 runs for 250 ms and loop 2 (that's inside loop 1) runs for much longer, like 9 seconds.

Apologies if I have wasted too much of people's time.

2 of 5
1

Your logic is wrong. If you update previousMillis with millis() value in the first line, you are always subtracting the time difference between the the first and second lines of your code (which is the same you are doing in the loop inside flash()). If what you need is to get the time passed since the program started running, you need to have a fixed variable for that in setup() instead of updating it every time in loop().

Even so, I don't see why millis() is necessary in your case. Using delay() would be much more simple and still get the job done. Example:

void setup() {
delay(250);
}

void loop(){

    for(int i = 0; i < 9; i++){
        digitalWrite(LED, HIGH);
        delay(time);
        digitalWrite(LED, LOW);
        delay(time);

        delay(1000 - 2*time); //Delays the loop exactly one second per iteraction
    }

}
🌐
Reddit
reddit.com › r/arduino › how to use millis function with for loop?
r/arduino on Reddit: How to use millis function with for loop?
September 25, 2021 -

I know that the code is completely wrong because once it is in the for loop it doesn't stop until all the decrement is done, but is there a way to make the decrement in the for loop happen once every second?

void loop() {

unsigned long currentTime = millis();

if (currentTime - previousTime >= interval) {

previousTime = currentTime;

for(i=10; i>0; i--) {

lcd.print(i);

}

}

Top answer
1 of 5
4

You have made the code to go in the loop every “interval” ms; now you have two options:

  1. create another “interval” and “previousTime” variable (changing the name of course) and place another condition inside

  2. add a “delay(1000);” after the lcd.print(i).

The difference is the following:

  1. you maintain the code multi-task oriented, that is, you can check if (a) you have to launch the lcd updating with the current code and (b) check if you indeed have to change the value shown in the lcd (with the new addition to the code). Whatever it is the state (update or not, change “i” or not), you can then do other things before checking again (that is, you can read a sensor or blink a LED or do whatever you need). This is the best practice to get the most out of the Microcontroller.

  2. with the delay, however, your code will simply wait one second on every loop tick. This means that yOu will have 10 seconds spent (indeed, wasted) every time you get in that loop (which for a microcontroller is equivalent to years of time :D). Therefore, any other task will only happen, regardless your need, every 10 seconds. This is a waste of potential.

I avoided writing code examples to invite you to explore options. Let me know if you need some inspiration. I recommend you to give it a try, the “ingredients” are there already :)

2 of 5
3

//Timers

unsigned long timer1000ms = 0;

void setup() {

}

void loop() {

if (timer1000ms + 1000 < millis()) { //Run code every 1000ms (1s)

timer1000ms = millis();

}

🌐
Adafruit
learn.adafruit.com › multi-tasking-the-arduino-part-1 › using-millis-for-timing
Using millis() for timing | Multi-tasking the Arduino - Part 1 | Adafruit Learning System
November 3, 2014 - Used here to // set pin numbers: ... (milliseconds) void setup() { // set the digital pin as output: pinMode(ledPin, OUTPUT); } void loop() { // here is where you'd put code that needs to be running all the time....
🌐
Arduino Forum
forum.arduino.cc › projects › general guidance
millis() and while loop - General Guidance - Arduino Forum
October 12, 2019 - Good day I need some advice on using the mills function with while loops. I would like to execute some code section for a specified amount of time, eventually serving as time wasting instead of the delay() function. I noticed that the timer gets stuck in the while loop, and stops counting.
🌐
Bald Engineer
baldengineer.com › home › millis() tutorial: arduino multitasking
millis() Tutorial: Arduino Multitasking - Bald Engineer
March 31, 2022 - I am after millis implementation using fastled patterns and i have to admitt it is pain….. inserting inside a for loop…. below is a demo for loop which cannot work with millis, what it does is waiting for the interval time i set and then passes all leds at very fast speed. the purpose i want is to use BLYNK platform which does not like delays….. any help will be much apreciated…… · [arduino] #include "FastLED.h" #define NUM_LEDS 54 #define DATA_PIN 6 CRGB leds[NUM_LEDS];
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Replace delay with millis () within "for loop" - Programming - Arduino Forum
April 23, 2017 - Is it possible to replace delay with millis in this "for loop" ? My goal is to draw one pixel every 100 ms, without delay. TFT Screen.. for (int pixel = 80; pixel < 122; pixel++) { myGLCD.drawPixel(pixel, 206); dela…
🌐
Programming Electronics Academy
programmingelectronics.com › home › arduino sketch with millis() instead of delay()
millis() instead of delay() with Arduino [Guide + Code]
November 13, 2023 - Millis returns the number of milliseconds that have passed since this upload was completed. Essentially, it’s a timer for how long the current program has been running. This is independent of the number of times the “void loop ()” has iterated.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Array/For loop with 'millis' - Programming - Arduino Forum
December 10, 2013 - How would you write the code to run a 'for loop' or 'array' using millis and no delays at all? Or any other way just without using delay. Thank you if you can help!! 🙂
🌐
Arduino
arduino.cc › reference › en › language › functions › time › millis
millis() | Arduino Documentation
October 31, 2023 - millis() is incremented (for 16 MHz AVR chips and some others) every 1.024 milliseconds, then incremented by 2 (rather than 1) every 41 or 42 ticks, to pull it back into sync; thus, some
🌐
Norwegian Creations
norwegiancreations.com › 2017 › 09 › arduino-tutorial-using-millis-instead-of-delay
Arduino Tutorial: Using millis() Instead of delay() – Norwegian Creations
September 5, 2017 - The only difference between the code above and a code with delay(1000) at the end is that the loop in the above code will run quite accurately once each second. The loop in a code with · delay(1000) will run a bit less frequent since it also takes some time to execute Serial.println("Hello"). We will now look at two advantages with millis() compared to delay().
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Looking for a help with for loop and millis. - Programming - Arduino Forum
August 28, 2017 - Hi. Im not very good in programming, but usually im trying to sort it out by myself. This time im stuck for two days. Not asking for code itself, just point me to the right direction, please. Tried about 72 different modifications, but it just dont work. So, i have 7 LEDs, witch i am trying to blink one after another by using millis.
🌐
Reddit
reddit.com › r/arduino › how does someone go about replacing delay with milis in for loops so the loop doesn't block the rest of the code?
r/arduino on Reddit: how does someone go about replacing delay with milis in for loops so the loop doesn't block the rest of the code?
April 7, 2023 - This way the rest of your sketch can be running without being affected, will behave like a multithreaded application basically. void Task() { if (millis() >= tmillis) { … do your logic …. tmillis += 5; // delay 5 milli state++; } return; } Than simply call your “Task()” function from the loop and whola. It’s a simple basic multi task handling procedure without going down into developing a kernel. ... Btw, you can’t do anything else outside of a for loop until it’s finished.