B4R Question Random Number

Discussion in 'B4R Questions' started by Johan Schoeman, Jul 20, 2019.

  1. Johan Schoeman

    Johan Schoeman Expert Licensed User

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

    Code:
    Sub p5_StateChanged
        
        
    If p5click = False Then
            
    Log("state 5 changed")
            p5click = 
    Not(p5click)
            
    Dim num As Long = Rnd(0361)
            
    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

    Code:
    201330198283294, .......
    What am I missing here?
     
  2. rbghongade

    rbghongade Active Member Licensed 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 likes this.
  3. Johan Schoeman

    Johan Schoeman Expert Licensed User

    This solved the issue:

    Code:
    #If C

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

    #End If
    Thanks @rbghongade
     
  4. Johan Schoeman

    Johan Schoeman Expert Licensed User

    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: Jul 20, 2019
  5. Erel

    Erel Administrator Staff Member Licensed User

    Inline code is not needed here:
    Code:
    dim p as Pin
    p.Initialize(
    0, p.MODE_INPUT)
    RndSeed(p.AnalogRead)
     
    hatzisn and Johan Schoeman like this.
  6. tigrot

    tigrot Well-Known Member Licensed 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?
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice