B4R Question Random Number

Johan Schoeman

Expert
Licensed User
Longtime User
I am seeing something very strange. I am using the below code to generate a random number.

B4X:
Sub p5_StateChanged
    
    If p5click = False Then
        Log("state 5 changed")
        p5click = Not(p5click)
        Dim num As Long = Rnd(0, 361)
        Dim deg As Int = num
        Log("DEG = ", deg)
        Dim steps As Int = 4096 * (deg / 360)
        For i = 0 To steps
            cs.stepSingle(True)
        Next
        stepcount = stepcount + steps
        Log("Step Count = ", stepcount)
    Else
        p5click = False
    End If

End Sub

It does not matter if I recompile the B4R code, reset the UNO, power down and up the stepper motor and reset the UNO - the "random numbers generated always follow the same pattern from a "reset" i.e

B4X:
201, 330, 198, 283, 294, .......

What am I missing here?
 

Johan Schoeman

Expert
Licensed User
Longtime User
It is a pseudo random generator actually. A better way is to read analog value and use it as a seed value.
This solved the issue:

B4X:
#If C

void getRandomNumber (B4R::Object* o) {
   long randNumber;
   randomSeed(analogRead(0));
   randNumber = random(361);
   b4r_main::_num = randNumber;
}

#End If

Thanks @rbghongade
 
Upvote 0

Johan Schoeman

Expert
Licensed User
Longtime User
This solved the issue:

B4X:
#If C

void getRandomNumber (B4R::Object* o) {
   long randNumber;
   randomSeed(analogRead(0));
   randNumber = random(361);
   b4r_main::_num = randNumber;
}

#End If

Thanks @rbghongade
This also seems to be somewhat repetitive.....some of the random generated values are appearing very frequently when there are 360 values to choose from.
 
Last edited:
Upvote 0
Top