Electronic – RANDOM command in PBASIC

picaxe

I'm trying to use the random command in PBASIC and I'm not sure how it works. I'm using a PICAXE-08 Proto Board Kit, and the chip specifically is a PICAXE-08M2.

Here is the code I'm using:

symbol randnum = w0
RANDOM randnum
randnum = randnum // 2

FOR action = 1 TO 5
    IF randnum > 0 THEN
        LOW led_red
        PAUSE 500
        HIGH led_red
        PAUSE 500
    ELSE
        SOUND buzzer,(100, 100)
        PAUSE 500
    ENDIF
NEXT action

(Perhaps due to assembly mistakes, the LED's HIGH corresponds to LOW and vice-versa).

First of all, I expected to put the RANDOM randnum command within the for loop, but if I do this, the loop count becomes incorrect. Instead of 5 actions, I get only 2.

The second problem is that I'm expecting randnum to be either 0 or 1, so that 50% of the time the LED is lit and 50% of the time the buzzer sounds. However, the LED is lighting 100% of the time, even across multiple trials. Obviously, randnum is never 0. However, according to documentation, RANDOM should give the variable a value between 0 and 65535, inclusive.

What is the issue here?

Best Answer

The RANDOM command doesn't simply generate a random number for you; what it's actually doing is taking whatever value is already in the variable and transforming it in a pseudorandom way. In other words, the variable you give it is the internal state of the random number generator. You must not modify that variable in any other way if you want the generated numbers to be as random as possible.

When you set randnum = randnum // 2, you are forcing it to be either 0 or 1. It would seem that when the RANDOM command sees a value of 1, it generates a new number that is odd, so you once again set randnum to 1.

What you need to do is use a second variable to hold the binary result:

RANDOM randnum
randbit = randnum // 2

(I can't explain the problem with the loop count changing; that would seem to be a separate issue.)