# Timing problem with millis

**URL:** <https://forum.arduino.cc/t/timing-problem-with-millis/1228406>\
**Category:** Programming\
**Created:** [February 25, 2024, 6:54pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406 "2024-02-25T18:54:00Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 6:54pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/1 "2024-02-25T18:54:00Z")

</div>

Hi, I'm new to Arduino programming i tried to make the Arduino control two LEDs by gradually turning up the brightness of said LEDs to the desired amount and then gradually turning it down in a loop  
if the speed of the two LEDs are the same the program works correctly but when one of the LEDs is half the speed of the other one they desynchronize after a bit of time is there a way to fix this?

```arduino
const int whiteLed = 2;
const int blueLed = 3;

long prevWhiteTimeMillis = 0;
boolean whiteState = false;

long prevBlueTimeMillis = 0;
boolean blueState = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(whiteLed, OUTPUT);
  pinMode(blueLed, OUTPUT);

}
int timer = 0;
void loop() {
  whiteLedControl();
  blueLedControl();
}

int whiteLedBrightness = 0;
int whiteLedMaxBrightness = 50;
boolean whiteLedSwitch = false;

void whiteLedControl() {
  if (millis() - prevWhiteTimeMillis >= 500 / 25) {
    if (whiteLedBrightness >= whiteLedMaxBrightness) {
      whiteLedSwitch = true;
    }
    if (whiteLedBrightness <= 1) {
      whiteLedSwitch = false;
    }

    if (!whiteLedSwitch) {
      if (whiteLedBrightness <= whiteLedMaxBrightness) {
        whiteLedBrightness++;
      } else {
        whiteLedSwitch = true;
      }
    } else {
      if (whiteLedBrightness >= 0) {
        whiteLedBrightness--;
      } else {
        whiteLedSwitch = false;
      }
    }
    prevWhiteTimeMillis = millis();
  }
  analogWrite(whiteLed, whiteLedBrightness);
}

int blueLedBrightness = 0;
int blueLedMaxBrightness = 50;
boolean blueLedSwitch = false;

void blueLedControl() {
  if (millis() - prevBlueTimeMillis >= 500 / 50) {
    if (blueLedBrightness >= blueLedMaxBrightness) {
      blueLedSwitch = true;
    }
    if (blueLedBrightness <= 1) {
      blueLedSwitch = false;
    }

    if (!blueLedSwitch) {
      if (blueLedBrightness <= blueLedMaxBrightness) {
        blueLedBrightness++;
      } else {
        blueLedSwitch = true;
      }
    } else {
      if (blueLedBrightness >= 0) {
        blueLedBrightness--;
      } else {
        blueLedSwitch = false;
      }
    }
    prevBlueTimeMillis = millis();
  }
  analogWrite(blueLed, blueLedBrightness);
}

```

thanks to user @Delta_G the problem was in this line

```arduino
prevBlueTimeMillis = millis();

```

because the millis() function does not run every millisecond exactly it causes problems  
this is the code working now

```arduino
const int whiteLed = 2;
const int blueLed = 3;

long prevWhiteTimeMillis = 0;
boolean whiteState = false;

long prevBlueTimeMillis = 0;
boolean blueState = false;

unsigned long currentMillis;

void setup() {
  // put your setup code here, to run once:
  pinMode(whiteLed, OUTPUT);
  pinMode(blueLed, OUTPUT);

}
int timer = 0;
void loop() {
  currentMillis = millis();
  blueLedControl();
  whiteLedControl();
}

int whiteLedBrightness = 0;
int whiteLedMaxBrightness = 50;
boolean whiteLedSwitch = false;

void whiteLedControl() {
  if (currentMillis - prevWhiteTimeMillis >= 500 / 25) {
    if (whiteLedBrightness >= whiteLedMaxBrightness) {
      whiteLedSwitch = true;
    }
    if (whiteLedBrightness <= 1) {
      whiteLedSwitch = false;
    }

    if (!whiteLedSwitch) {
      if (whiteLedBrightness <= whiteLedMaxBrightness) {
        whiteLedBrightness++;
      } else {
        whiteLedSwitch = true;
      }
    } else {
      if (whiteLedBrightness >= 0) {
        whiteLedBrightness--;
      } else {
        whiteLedSwitch = false;
      }
    }
    prevWhiteTimeMillis += 500 / 25;
  }
  analogWrite(whiteLed, whiteLedBrightness);
}

int blueLedBrightness = 0;
int blueLedMaxBrightness = 50;
boolean blueLedSwitch = false;

void blueLedControl() {
  if (currentMillis - prevBlueTimeMillis >= 500 / 50) {
    if (blueLedBrightness >= blueLedMaxBrightness) {
      blueLedSwitch = true;
    }
    if (blueLedBrightness <= 1) {
      blueLedSwitch = false;
    }

    if (!blueLedSwitch) {
      if (blueLedBrightness <= blueLedMaxBrightness) {
        blueLedBrightness++;
      } else {
        blueLedSwitch = true;
      }
    } else {
      if (blueLedBrightness >= 0) {
        blueLedBrightness--;
      } else {
        blueLedSwitch = false;
      }
    }
    prevBlueTimeMillis += 500 / 50;
  }
  analogWrite(blueLed, blueLedBrightness);
}

```

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [February 25, 2024, 7:25pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/2 "2024-02-25T19:25:45Z")

</div>

> [@morteza20deris](#):
>
> is there a way to fix this?

I can't see right away why they get out of sync.

But the easiest way to do one thing twice as fast as the other is to have one timing section instead of two, and then within that section do the half fast thing only every other time. Do the fully fast thing every time.

You can use a simple counter for this

```arduino
// every N milliseconds ... 
  static byte counter;

  counter++;
  if ((counter % 2) == 1) { // number is odd?
     doHalfFastThing();
  }

  doFullyFastThing();

```

Since one will be done exactly twice as often, they cannot get out of sync unless the times are not just a factor of two different.

Which makes me curious again about why your code does. Get out of sync.

a7

---

<div class="post-metadata">

**Author:** ![Koepel](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/koepel/32/637546_2.png) [@Koepel](https://forum.arduino.cc/u/Koepel)\
**Post date:** [February 25, 2024, 7:31pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/4 "2024-02-25T19:31:08Z")

</div>

Your sketch in Wokwi simulation: [Timing problem with millis - Wokwi ESP32, STM32, Arduino Simulator](https://wokwi.com/projects/390731361339855873)

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 7:45pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/5 "2024-02-25T19:45:12Z")

</div>

I tried that and didn't work for me

```arduino
const int whiteLed = 2;
const int blueLed = 3;

long prevWhiteTimeMillis = 0;
boolean whiteState = false;

long prevBlueTimeMillis = 0;
boolean blueState = false;

unsigned long currentMillis;

void setup() {
  // put your setup code here, to run once:
  pinMode(whiteLed, OUTPUT);
  pinMode(blueLed, OUTPUT);

}
int timer = 0;
void loop() {
  currentMillis = millis();
  blueLedControl();
  whiteLedControl();
}

int whiteLedBrightness = 0;
int whiteLedMaxBrightness = 50;
boolean whiteLedSwitch = false;

void whiteLedControl() {
  if (currentMillis - prevWhiteTimeMillis >= 500 / 25) {
    if (whiteLedBrightness >= whiteLedMaxBrightness) {
      whiteLedSwitch = true;
    }
    if (whiteLedBrightness <= 1) {
      whiteLedSwitch = false;
    }

    if (!whiteLedSwitch) {
      if (whiteLedBrightness <= whiteLedMaxBrightness) {
        whiteLedBrightness++;
      } else {
        whiteLedSwitch = true;
      }
    } else {
      if (whiteLedBrightness >= 0) {
        whiteLedBrightness--;
      } else {
        whiteLedSwitch = false;
      }
    }
    prevWhiteTimeMillis = currentMillis;
  }
  analogWrite(whiteLed, whiteLedBrightness);
}

int blueLedBrightness = 0;
int blueLedMaxBrightness = 50;
boolean blueLedSwitch = false;

void blueLedControl() {
  if (currentMillis - prevBlueTimeMillis >= 500 / 50) {
    if (blueLedBrightness >= blueLedMaxBrightness) {
      blueLedSwitch = true;
    }
    if (blueLedBrightness <= 1) {
      blueLedSwitch = false;
    }

    if (!blueLedSwitch) {
      if (blueLedBrightness <= blueLedMaxBrightness) {
        blueLedBrightness++;
      } else {
        blueLedSwitch = true;
      }
    } else {
      if (blueLedBrightness >= 0) {
        blueLedBrightness--;
      } else {
        blueLedSwitch = false;
      }
    }
    prevBlueTimeMillis = currentMillis;
  }
  analogWrite(blueLed, blueLedBrightness);
}

```

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 7:50pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/8 "2024-02-25T19:50:59Z")

</div>

even if this works it will lose the option of any timing that i would want

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 7:51pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/9 "2024-02-25T19:51:33Z")

</div>

Arduino mega 2560

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 7:52pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/10 "2024-02-25T19:52:27Z")

</div>

they are not flashing the brightness changes on those timings

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 7:59pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/12 "2024-02-25T19:59:41Z")

</div>

the LEDs start synced together meaning they both start at the same time and their brightness oscillates  
the blue LED oscillates double the speed of the white one so every other time that the blue LED starts it should start with the white one  
they do that at first but after a while the blue LED falls behind

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 8:03pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/13 "2024-02-25T20:03:27Z")

</div>

each cycle (the rise and the fall of the LED's brightness) of the white LED takes 2 seconds and the blue LED takes a second so it's pretty obvious by watching

---

<div class="post-metadata">

**Author:** ![Koepel](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/koepel/32/637546_2.png) [@Koepel](https://forum.arduino.cc/u/Koepel)\
**Post date:** [February 25, 2024, 8:12pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/15 "2024-02-25T20:12:04Z")

</div>

@morteza20deris It took some before we understood the syncing problem, but I think that Delta\_G is right.

If two timings are related, then I would use a single millis-timer.  
Since the led is seen by the human eye, it is possible to run a millis-timer at a fixed rate (something 20...100Hz) and deal with the brightness in the millis-timer.

I have updated the Wokwi simulation to a Mega board: [Timing problem with millis - Wokwi ESP32, STM32, Arduino Simulator](https://wokwi.com/projects/390731361339855873)

This is the sync problem after 2 minutes:  
 ![afbeelding](https://europe1.discourse-cdn.com/arduino/original/4X/c/c/0/cc0acd9021773666e88d328f92db9caaaf4bdc7f.png)

---

<div class="post-metadata">

**Author:** ![LarryD](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/larryd/32/215550_2.png) [@LarryD](https://forum.arduino.cc/u/LarryD)\
**Post date:** [February 25, 2024, 8:16pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/16 "2024-02-25T20:16:44Z")

</div>

BTW

long prevWhiteTimeMillis = 0;

long prevBlueTimeMillis = 0;

- These should be **unsigned long**.

---

<div class="post-metadata">

**Author:** ![david\_2018](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/david_2018/32/1013044_2.png) [@david\_2018](https://forum.arduino.cc/u/david_2018)\
**Post date:** [February 25, 2024, 8:23pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/17 "2024-02-25T20:23:16Z")

</div>

> [@Delta\_G](#):
>
> So let's think about this line. What happens if previousMillis is 100 and the currentMillis is 111. Then it changes the brightness and sets previousMillis to 111. So the next change will happen at 121 and not 120.

What is even worse, occasionally millis() increments by 2 instead of 1 (because the millis() interrupt occurs at 1.024mS intervals instead of exactly 1mS). This would eventually throw off the timing because the shorter delay would have a higher probability of hitting the increment by 2.

> [@Delta\_G](#):
>
> The fix is to set previousMillis to where it should have triggered instead of where it did trigger.  
> `prevBlueTimeMillis += 20;`  
> or  
> `prevBlueTimeMillis += 10;`

That would have been my suggestion.

---

<div class="post-metadata">

**Author:** ![morteza20deris](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/morteza20deris/32/1047181_2.png) [@morteza20deris](https://forum.arduino.cc/u/morteza20deris)\
**Post date:** [February 25, 2024, 8:23pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/18 "2024-02-25T20:23:33Z")

</div>

this fixed it  
it was exactly as you said it is  
the two LEDs are now perfectly in sync as far as my eyes can see  
thanks a lot you are a brilliant person

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [August 23, 2024, 8:25pm UTC](https://forum.arduino.cc/t/timing-problem-with-millis/1228406/20 "2024-08-23T20:25:35Z")

</div>

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
