B4R QuestionRandom Number

Johan Schoeman

Expert
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?

Active Member
Longtime User
It is a pseudo random generator actually. A better way is to read analog value and use it as a seed value.

Johan Schoeman

Expert
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;
randNumber = random(361);
b4r_main::_num = randNumber;
}

#End If``````

Johan Schoeman

Expert
Longtime User
This solved the issue:

B4X:
``````#If C

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

#End If``````

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:

Erel

B4X founder
Staff member
Longtime User
Inline code is not needed here:
B4X:
``````dim p as Pin
p.Initialize(0, p.MODE_INPUT)

tigrot

Well-Known Member
Longtime User
And the pin must be left floating, I suppose... Or it's better to sold a small wire that can perform like an antenna?

Replies
0
Views
1K
Replies
3
Views
2K
Replies
3
Views
2K
B4R Question Random Number
Replies
2
Views
818
Replies
11
Views
8K