How to use arduino uno millis function()

I wrote a program for Arduino UNO with attached Funshield, which will animate the following pattern on the four vertical LEDs. At any given moment, exactly one LED (of four) is turned on (we are starting with the topmost one). In each step of the animation, the active LED moves one slot down. When it hits the bottom, it bounces and moves upwards again, until it reaches top. The animation repeats itself forever.
here is my code

#include <funshield.h>


int ledPin[] = {led1_pin, led2_pin, led3_pin, led4_pin};

void setup() {
  for (int i = 0; i<5; i++)
    pinMode(ledPin[i], OUTPUT);
}

void loop() {
  int i = 0;
  for (i = 5-1; i>=0; i--)
    digitalWrite(ledPin[i], LOW);
    delay(1000);
    digitalWrite(ledPin[i], HIGH);
    
  for (i; i<5; i++) {
    digitalWrite(ledPin[i], LOW);
    delay(500);
    digitalWrite(ledPin[i], HIGH);
  }
}

it works perfectly,but when i need use millis() function , it doesn't work anyway.

#include <funshield.h>


int ledPin[] = {led1_pin, led2_pin, led3_pin, led4_pin};

void setup() {
  for (int i = 0; i<5; i++)
    pinMode(ledPin[i], OUTPUT);
}

void loop() {
  unsigned long nowtime;
  if(unsigned long)(millis()-nowtime>300){
  int i = 0;
  for (i = 5-1; i>=0; i--)
    digitalWrite(ledPin[i], LOW);
    delay(1000);
    digitalWrite(ledPin[i], HIGH);
  }  
  for (i; i<5; i++) {
    if(unsigned long)(millis()-nowtime>300){
    digitalWrite(ledPin[i], LOW);
    delay(500);
    digitalWrite(ledPin[i], HIGH);
  }
  }
}

Replace Delay with milis(). have a counter, and turn on/off leds based on that counter.

I don't know exactly how to do it ,I have tried replacing but it doesn't work. :sleepy:

millis()-nowtime

What is the value of nowtime ?

Take a close look at the BlinkWithoutDelay example to see how you should be doing this

By the way, using delay() in the for loops is also going to mess up your timing

See Using millis() for timing. A beginners guide and Several things at the same time

1 Like

show picture

byte ledPin[4] = {2, 3, 4, 5};
byte i = 0;
bool isCountUp = true;

void setup() {
  for (byte i = 0; i < 5; i++)
    pinMode(ledPin[i], OUTPUT);
}

void loop() {
  digitalWrite(ledPin[i], HIGH);
  unsigned long nowtime = millis();
  while (millis() - nowtime < 300);
  digitalWrite(ledPin[i], LOW);
  if (isCountUp) {
    if (i < 4)i++;
    else isCountUp = false;
  } else {
    if (i > 0)i--;
    else isCountUp = true;
  }
}

Whatever else y'all are doing, you are accessing beyond the end of the pin numbers array. I Stick some print statemnets on in there in the last best version:

2 goes HIGH
2 goes LOW
3 goes HIGH
3 goes LOW
4 goes HIGH
4 goes LOW
5 goes HIGH
5 goes LOW
32 goes HIGH
32 goes LOW
32 goes HIGH
32 goes LOW
5 goes HIGH
5 goes LOW
4 goes HIGH
4 goes LOW
3 goes HIGH
3 goes LOW
2 goes HIGH...

And this

 for (i; i<5; i++) {...

compiles, which surprises me, to be clearer and avoid future mishaps when circumstances chage you should prolly

 for (i = 0; i < 5; i++) {...

But mostly the array thing.

a7

Shouldn't the first and second lines use int? because i have """#include "funshield.h"""

i don't see what does it do. if i right the Funshield does not contain a "vertical 4 LED" element.
due to this I ask in post #6 to show pictures of your project.

near to every type of variable will work in this case.

This line is doing nothing for 300 milliseconds, exactly like a delay(300);

Was this the intention?

no

Name of tread is "How to use millis() function".
My sketch demonstrate this. Of course not in every single possible way.

The highlighted instruction has the exact same effect as delay(300):
it freezes the MCU without doing anything else for 300 milliseconds, so what benefit should this implementation have?
The mere fact that it says millis() instead of delay()?

Hello bismarckfunf
Try this small sketch using an array containing all relevant data.
A time handler based on the milli() function takes care about the led pattern timing.

/* BLOCK COMMENT
  ATTENTION: This Sketch contains elements of C++.
  https://www.learncpp.com/cpp-tutorial/
  Many thanks to LarryD
  https://europe1.discourse-cdn.com/arduino/original/4X/7/e/0/7e0ee1e51f1df32e30893550c85f0dd33244fb0e.jpeg
  https://forum.arduino.cc/t/how-to-use-arduino-uno-millis-function/969287
  Tested with Arduino: Mega[ ] - UNO [X] - Nano [ ]
*/
#define ProjectName "How to use arduino uno millis function()"
// HARDWARE AND TIMER SETTINGS
// YOU MAY NEED TO CHANGE THESE CONSTANTS TO YOUR HARDWARE AND NEEDS
constexpr byte LedPins[] {9, 10, 11, 12};    // portPin o---|220|---|LED|---GND
// VARIABLE DECLARATION AND DEFINITION
unsigned long currentTime;
struct TIMER {              // has the following members
  unsigned long duration;   // memory for interval time
  unsigned long stamp;      // memory for actual time
  bool onOff;               // control for start/stop
};

// make array for led pattern and timing information
struct LedDelay {
  TIMER wait;
  byte  ledPattern[sizeof(LedPins)];
};
LedDelay ledDelays[] {
  {1000, 0, true, {false, false, false, false}},
  {1000, 0, false, {true, false, false, false}},
  {1000, 0, false, {false, true, false, false}},
  {1000, 0, false, {false, false, true, false}},
  {1000, 0, false, {false, false, false, true}},
  {500, 0, false, {false, false, false, false}},
  {500, 0, false, {false, false, false, true}},
  {500, 0, false, {false, false, true, false}},
  {500, 0, false, {false, true, false, false}},
  {500, 0, false, {true, false, false, false}},
};

// time handler
bool timerEvent (TIMER &timer) {
  return (currentTime - timer.stamp >= timer.duration && timer.onOff);
}
// -------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  Serial.println(F("."));
  Serial.print(F("File   : ")), Serial.println(__FILE__);
  Serial.print(F("Date   : ")), Serial.println(__DATE__);
  Serial.print(F("Project: ")), Serial.println(ProjectName);
  pinMode (LED_BUILTIN, OUTPUT);  // used as heartbeat indicator
  //  https://www.learncpp.com/cpp-tutorial/for-each-loops/
  for (auto Output_ : LedPins) pinMode(Output_, OUTPUT);
}
void loop () {
  currentTime = millis();
  digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);
  // get access to the ledDelay array
  for (auto &ledDelay : ledDelays) {
    // it´s time for action?
    if (timerEvent(ledDelay.wait)) {
      // yes, switch off current timer
      ledDelay.wait.onOff = false;
      // make local variable
      static int patternCounter = 0;
      // did we get all members of the array?
      patternCounter = (patternCounter + 1) % (sizeof(ledDelays) / sizeof(ledDelays[0]));
      // set time duration for pattern
      ledDelays[patternCounter].wait.stamp = currentTime;
      // switch timer ON
      ledDelays[patternCounter].wait.onOff = true;
      // make local variable
      int element = 0;
      // and copy led pattern to leds
      for (auto ledPin : LedPins) digitalWrite(ledPin, ledDelays[patternCounter].ledPattern[element++]);
    }
  }
}

Have a nice day and enjoy coding in C++.

Hi @paulpaulson
Thanks for sharing your code, but for me is quite clear how to use millis() :wink:

I was just trying to make it clear to @kolaha that the highlighted line is equivalent to delay() because of

;

at the end of while which is in effect a line of instruction that does nothing. Probably he forgot the braces.

Sorry that went wrong.
I´ve correct the name now.

@bismarckfunf : are you still interested ?

If yes: your simple LED-program is one of the rarely cases where delay is sufficient.
As long as the program stays as it is delay is really sufficient.

millis() come into play if you want to do a second thing in parallel to the LED-blinking.

So you would have to describe a different functionality that does something in parallel to the LED-blinking.
As soon as you have posted this functionality specific suggestions can be made

best regards Stefan

1 Like

@StefanL38 Of course,thank your response,i just want write a program for Arduino UNO with attached Funshield, which will animate the following pattern on the four vertical LEDs. At any given moment, exactly one LED (of four) is turned on (we are starting with the topmost one). In each step of the animation, the active LED moves one slot down. When it hits the bottom, it bounces and moves upwards again, until it reaches top. The animation repeats itself forever.

One step of the animation takes exactly 300ms. The most important is i want use milli function().

The animation works perfectly when only using the DELAY function

why?

1 Like

Because that what their homework says they have to do!