I want to generate some binary arrays to control the brightness of an LED without a controller. Rather than generate the pulse widths on the microcontroller (which would take up instruction cycles that should be used for other things), I'll hard-code them as a look-up table, and loop through the binary array over and over, setting the LED either on or off at that instruction.
Assuming I have an array length of 4, I would have 5 brightness levels:
{{ 0, 0, 0, 0 },
{ 1, 0, 0, 0 },
{ 1, 0, 1, 0 },
{ 1, 1, 1, 0 },
{ 1, 1, 1, 1 }}
Notice that I have tried to distribute the 1's as evenly as possible throughout the array, which is not always possible but small anomalies shouldn't be visible to the human eye.
Let's say I have an array length of 8, and I want a brightness of 5/8:
{ 1, 0, 1, 1, 0, 1, 1, 0 };
This seems like a good spread, but I could have also used:
{ 1, 0, 1, 1, 1, 0, 1, 0 };
Which is better? The average brightness is, of course, the same. The number of changes from one state to another is also the same. The standard deviation is the same. Looking at the runs, however, the first example has a much lower variance of run length which means it's more uniform and, therefore, better.
Anyway. I need an algorithm to generate these arrays for a given length and brightness. If possible, the algorithm should find an optimal array - one that's as uniform as possible.
It's not as simple as it sounds. To be honest, I'm tempted to just write a brute-force algorithm that compares all possibilities and returns the best.
I was even considering putting together an Integer Programming model, but that seems like overkill for this problem.
Unless someone has a better idea?
Edit:
It turns out that { 1, 1, 1, 1, 0, 0, 0, 0 } has the same run variance as { 1, 0, 1, 0, 1, 0, 1, 0 }, so the metric needs to be a little more complicated as the second example is clearly superior to the first. (For longer array lengths, some LED flicker might be visible of the 1's are bunched up).