After some discussion it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.
- There was ansome initial programming bugconfusion (see the edits) where the
hasBeenSet
flag was initialized the wrong way around. - I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
- Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
- Possibly faulty WS2812 chip - try with another one.
- Possibly faulty Arduino - try with another one.
- Possibly Arduino running at the wrong clock speed which would throw the timings out.
- Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
- Possible bug in the library. We eliminated that by trying with my library for Neopixels.
In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.
We never really worked out why doing it in loop
rather than setup
made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.
I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.