PDA

View Full Version : Random



SELTZER
- 13th April 2006, 02:25
I Want To Use This In A Program, In The Pic Basic Book It Says That Var Is A Seed And The Holder Of The Final Data. How Do I Use Var In This Case. I Need A Sample.

Melanie
- 13th April 2006, 05:48
I though the manual pretty much said it perfectly...

MyWord var WORD ' Variable must be a WORD and must NOT be an array.

.. .. ..

MyWord=1234 ' Word must contain a starting number or 'seed'

.. .. ..

Random MyWord ' Random generates a new number conained in MyWord

Random takes the 'seed' (your starting value) you gave it somewhere at the start of your program, and uses it to generate a new value which then replaces the previous contents of the variable MyWord. Thereafter you can simply use that result to keep on generating new numbers, each will replace the previous one.

Dice Example


RandomValue var WORD
Dice var BYTE

ButtonPress var PortB.0

RandomValue var 9876

Loop:
If ButtonPress=1 then goto Loop ' Button Not Pressed
Random RandomValue ' Generate Random Value
Dice=(RandomValue//6)+1 ' Convert it to range 1-6
Pause 75 ' Debounce Delay for Button
While ButtonPress=0:Wend ' Wait for Button to be Released
Gosub DisplayDice ' Display Result
Goto Loop ' Do it again

The starting 'seed' value always ensures that the Random command starts it's sequence from the same repeatable point (so you can repeat EXACTLY the same sequence each time you run your code). This is called pseudo-random. If you want TRUE random, then you must start with a different seed each time.

This second example shows a way of ensuring your sequence is never repeated (unless you reprogram the PIC)...


RandomValue var WORD
Dice var BYTE

ButtonPress var PortB.0

Data @0,148,38 ' Just a Starting Seed value
Read 0,Randomvalue.Lowbyte ' Load RandomValue from EEPROM
Read 1,Randomvalue.Highbyte

Loop:
If ButtonPress=1 then goto Loop ' Button Not Pressed
Random RandomValue ' Generate Random Value
Dice=RandomValue//6)+1 ' Convert it to range 0-5
Dice=Dice+1
Pause 75 ' Debounce Delay for Button
While ButtonPress=0:Wend ' Wait for Button to be Released
Gosub DisplayDice ' Display Result
Write 0,RandomValue.Lowbyte ' Save Random Value for Future use
Write 1,Randonvalue.Highbyte
Goto Loop ' Do it again

SELTZER
- 13th April 2006, 16:48
Thanks for your help