Another caveat to remember is that until something external happens (like a button press), all blinks are deterministically the same and all will do exactly the same thing. So, for example, this code will always end up with a GREEN blink. Always, on every blink, every time it is startedā¦
void setup() {
// put your setup code here, to run once:
}
bool colorSetFlag = false;
void loop() {
// put your main code here, to run repeatedly:
if (!colorSetFlag) {
byte randomColorPicker = millis() % 3;
switch (randomColorPicker) {
case 0: setColor(RED); break;
case 1: setColor(GREEN); break;
case 2: setColor(BLUE); break;
}
colorSetFlag = true;
}
}
If you have a bunch of blinks and you download this program to them all, they will all dutifully turn GREEN at the end of the download.
While this might seem like a contrived example, it did come up in real games. That is why I had to make the entropy-based randomize()
function. (Note that it is very hard to find entropy inside a blink before any button presses.
)
Also note that if your application can use a range that happens to be a power of two, then you can save an additional ~80 bytes. So, for exampleā¦
byte coinFlip = millis() % 2;
ā¦is smaller than
byte centuryToss = millis() % 100;
This happens because the compiler can reduce a mod
of a power of 2 down to a single binary and
, whereas a mod
of an non-power of two requires a divide and multiply (very expensive on this chip).
ā¦and finally I need to add the warning that random numbers are a surprisingly tricky business to do right. You might see the above, and writeā¦
byte dieRoll = min( (millis() % 8 ) , 5 );
Seems fine because it is random (or at lest pseudo) and the result is always in the range 0-5⦠but it is not evenly distributed. If you used this for a craps game then youād find some very bad outcomes! Whole empires have fallen when hapless programmers have fallen for this mistake!
And on a closing warning note, do you see why even this is no good and terribly wrong?..
randomize();
byte twoDiceRoll = random( 11 ) + 1;
If you are interested, Knuth has much to say about this topic.