Monday 23 December 2013

A note about random()

I have seen quite a few people struggling with the Arduino random() function. The problem lies in creating a simple random '1' or '0'. It is tempting to write
random(0,1);
But this doesn't work as it returns '0' every time. What random() does is to generate a random number from START to FINISH - 1.
random(START, FINISH);
So to get a random '0' and '1' returned you have to do this:

#define START 0
#define FINISH 1

random(START, FINISH + 1);
so it outputs from START '0' to FINISH '1'

No comments: