Specifications

BASIC Stamp II
Page 296 • BASIC Stamp Programming Manual 1.8 • Parallax, Inc.
Random
RANDOM
variable
Generate a pseudo-random number.
Variable
is a byte or word variable whose bits will be scrambled
to produce a random number.
Explanation
Random generates pseudo-random numbers ranging from 0 to 65535.
They’re called “pseudo-random” because they appear random, but are
generated by a logic operation that always produces the same result
for a given input. For example:
w1 = 0 ' Clear word variable w1 to 0.
RANDOM w1 ' Generate "random" number.
debug dec ? w1 ' Show the result on screen.
In applications requiring more apparent randomness, it’s a good idea
to seed Random’s wordvariable with a different value each time. For
instance, in the demo program below, Random is executed continu-
ously while the program waits for the user to press a button. Since the
user can’t control the timing of button presses to the nearest millisec-
ond, the results approach true randomness.
Demo Program
Connect a button to pin 7 as shown in figure I-13 and run the program
below. The program uses Random to simulate a coin toss. After 100
trials, it reports the total number of heads and tails thrown.
flip var word ' The random number.
coin var flip.bit0 ' A single bit of the random
number.
trials var byte ' Number of flips.
heads var byte ' Number of throws that came up
heads.
tails var byte ' Number of throws that came up
tails.
btn var byte ' Workspace for Button instruction.
start:
debug cls, "Press button to start"