I have a boolean expression (I think it's called), and it will always return false after 32 seconds of running, and I'm very confused now.

if (millis() > stepTime+lightCmd[stepe][5]) {
  stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
  stepTime = millis();
  Serial.println("changing"); // debugging

This runs inside the main loop.

Also, I've tried using an exponent when trying to get some lights to appear to fade linearly and in about the same amount of time, 32 seconds, it would start fading in reverse.


millis(); wouldn't go backwards after it stopped working

  • 1
    Use the arduino.cc/en/tutorial/BlinkWithoutDelay example. You should not compare millis to a value and you should not add something to the millis value. If you have a problem, please provide a full working sketch, so we can test it.
    – Jot
    Dec 15 '17 at 0:30
  • 1
    @Jot please turn your comment into an answer.
    – per1234
    Dec 15 '17 at 0:31
  • 1
    Is stepTime an unsigned long ?
    – Dave X
    Dec 15 '17 at 0:41
  • 2
    You code is nothing like the blink without delay. There is a specific way to use millis: "the current millis" - "a previous millis value" >= interval. And the current millis and the previous millis must be a "unsigned long". The current millis can also be a call to millis() of course. An integer? And the 32 seconds is perhaps 32767 milliseconds?
    – Jot
    Dec 15 '17 at 0:55
  • 1
    @Gerben I won't need to run it nearly that long, so it won't be a problem.
    – F4Tornado
    Dec 16 '17 at 15:37

When dealing with millis and micros you must always use unsigned long variables; otherwise, values will be overflow/truncate.

When doing time arithmetic, you must always use differences, not additions, because of the nature of unsigned arithmetic.

Your updated sketch is this:

void setup()
    Serial.println(); Serial.println("Test");

#define STEPS 3
unsigned long lightCmd[STEPS] = {4000, 60000, 90000};
int stepe = 0;
unsigned long stepTime = 0;

void loop()
    if(millis() - stepTime >= lightCmd[stepe]) {
        Serial.print(".- ");
        stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
        stepTime = millis();
        Serial.println(" changing"); // debugging

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.