cancel
Showing results for 
Search instead for 
Did you mean: 

random number 0 to 255.

jdo
Associate II

Hi! i want generate a random number into 0 to 255, i want use the random number for rutine neopixel color. i can use the rand() c function? the eand() function not generate number 0 to 255. Not need to be in ordem ascend or descend.

6 REPLIES 6
gbm
Lead III

For random animation, any pseudorandom will be ok. use rand with modulo 256. In my WS2812 and other light-related projects I use 32-bit lfsr pseudorandom generator, sligtly better than rand(), initializing it with UUID value from MCU's Flash, which makes sense if you have few identical devices in the same room.

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice
KiptonM
Lead

The rand() function generates an integer from 0 to 32767. There are many ways to generate a random number, depending on your requirements for randomness. I am guessing by your question that you really are not concerned with highly statistical randomness. Just something that spits out a random number,

Probably the easiest way to do it is to just shift it to get the range you want. The highest number rand gives you is 32767. The highest number you want is 255.

The simple answer is just shift.

uint16_t x;

x = rand() >> 7;

But that only creates 255 if the rand() result is exactly 32767. If it is 32766 it results in 254. That means you only get 255 in one of 32767 tries instead of one in 255.

A better result is to round. It is not perfect but better.

uint16_t x, y;

y = rand();

x = y >> 7;

if ((y & 0x80) != 0) x++;

It is still not perfect but better and probably good enough, it gives you a chance of 255 at about 1/2 the chance of any other number,

Another way is to just and the results. and use only the lower 8 bits;

x = rand() & 255;

I have no idea how this will work statistically but it is probably the best at getting closer to equal chances for every number. Depending on your application I would try this one first.

jdo
Associate II

is there an application note that I can use or an example? never used dac with lfsr with bluepill

i going to test, i don´t want work statisticfally, so want eandom number for color ws2812, not relaionated.

Then doing the and will probably be good enough and it is fast.

S.Ma
Principal

When you will want a true random (as crypto demand), check out TRNG peripheral.