'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. One step of the animation takes exactly 300ms

#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);
  }
}

if i using the delay() function, it works perfectly,but when i used millis() function , 4 LEDs light up at the same time.I would like to know what is causing the animation to stall.

#include "funshield.h"

unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 300;
const byte liu = 4;
int ledPin[] = { led1_pin, led2_pin, led3_pin, led4_pin };

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

void loop()
{
    currentMillis = millis();
    if (currentMillis - startMillis >= period)
        int i = 0;
    for (int i = 0; i > 4; i++) {
        digitalWrite(liu, !digitalRead(liu));
        digitalWrite(ledPin[i], LOW);
        digitalWrite(ledPin[i], HIGH);
        startMillis = currentMillis;
    }

    
    for (int i = 4; i >= 0; i--) {
        digitalWrite(liu, !digitalRead(liu));
        digitalWrite(ledPin[i], LOW);
        digitalWrite(ledPin[i], HIGH);
        startMillis = currentMillis;
    }
}


Solution 1:[1]

first of all unsigned long nowTime; should be at the top, outside of your loop

secondly, you need to use nowTime = millis(); for the specific time that you want to record the current time (this should be before you use the (millis()-nowtime>300)

and lastly, remove (unsigned long) from this line if(unsigned long)(millis()-nowtime>300)

for further clarification on how to use millis, read this article on arduino's official website

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmed .I