- Name:
-
random
- Syntax:
-
RANDOM wordvariable
Wordvariable - is both the workspace and the result. As random generates a pseudo-random sequence it is advised to repeatedly call it within a loop. A word variable must be used, byte variables will not operate correctly.
- Description:
-
The random command generates a pseudo-random sequence of numbers between 0 and 65535.
All microcontrollers must perform mathematics to generate random numbers, and so the sequence can never be truly random. On computers a changing quantity (such as the date/time) is used as the start of the calculation, so that each random command is different. The PICAXE does not contain such date functionality, and so the sequence it generates will always be identical unless the value of the word variable is set to a different value before the random command is used. When used with M2, X1, X2 parts you can set the timer running and then use the timer variable to 'seed' the random command. This will give much better results:
| |
let w0 = timer |
; seed w0 with timer value |
| |
random w0 |
; put random value into w0 |
Another common way to overcome this issue (can be used on all parts) is to repeatedly call the random command within a loop, e.g. whilst waiting for a switch push. As the number of loops will vary between switch pushes, the output is much more random. If you only require a byte variable (0-255), still use the word variable (e.g. w0) in the command. As w0 is made up of b0 and b1, you can use either of these two bytes as your desired random byte variable.