Tell me more ×
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It's 100% free, no registration required.

I'm wondering how to effectively generate random numbers with my PICAXE 08M2. The following is my code:

; Inputs
symbol push_red = C.1 ; In 1
symbol push_buzzer = C.3; In 3

; Outputs
symbol buzzer = C.2; Out 2
symbol led_red = C.4;

symbol action = b0
symbol randnum = w5; 
symbol randbit = w6; 

main:

    FOR action = 1 TO 5
        RANDOM randnum
        LET randbit = randnum // 10
        IF randnum > 4 THEN
            PAUSE 500
            low led_red
            pause 500
            high led_red
        ELSE
            SOUND buzzer,(100, 100)
        ENDIF
    NEXT action

    SOUND buzzer,(120, 200)

Even though I'm generating a new random number with every loop, the result is always the same: LEDs light up, no sound generated. I've read some articles about dividing randnum by an appropriate number, but not sure how that works.

share|improve this question
The line "IF randnum > 4 THEN" should be "IF randbit > 4 THEN". – Dave Tweed Sep 18 '12 at 21:14

1 Answer

up vote 0 down vote accepted

Like Dave says: you're using the wrong variable in the IF statement.

IF randnum > 4 THEN  

should be

IF randbit > 4 THEN

As I understand from another question randnum is in the range 0..65535, then the probability that it's less than 5 is less than 1 in 10 000. So if you repeat the test a lot of times you'll hear the buzzer once or twice, but those chances are slim for a loop executed only 5 times.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.