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.


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.

Applies To:
See Also:
Related Create:

    Turn on outputs in a random combination

    Random numbers are constantly generated - when C.1 goes high, the higher byte of the current random number is transfered to Port B

    Code Example:
    	if pinC.1 =1 then
    	  let pinsB = b1	; put random byte value on output pins
    	  pause 100		; wait 0.1s
    	end if
    	goto main
    Copy Code Submit an Example

    Flash a LED at random rates


    Code Example:
    	pause w0		; pause for a random amount of time
    	toggle B.1		; toggle the LED
    	goto main
    Copy Code Submit an Example

    Submit Your Own Code!



    • Login to leave a comment.