HELP with randomizing command

Discussion in 'Programmer's Corner' started by pr1111, Nov 27, 2011.

  1. pr1111

    Thread Starter Member

    Jul 8, 2010
    if(P1_0 == 1)
    {P1_1 = 0; //command 1
    P1_2 = 1; //command 2
    P1_3 = 1; //command 3
    P1_4 = 0;} //command 4

    what code can be used so that the output will execute the commands randomly every time I run the program?

    for example:
    1st run
    command 1,2,3,4 will be executed
    2nd run
    command 3,2,4,1 respectively will be executed

    thanks for those who can help me
  2. thatoneguy

    AAC Fanatic!

    Feb 19, 2009
    What is the processor?

    What are your other inputs?

    Is user input something that determines the outputs?

    If so, run a timer and capture the time between a couple of user choices, use those to seed the random number generator each time, or, if RNG isn't present in compiler library, use the LSB of the input timings. That will get close to random.

    If no user input, ADC sample the voltage, but with a zener diode with a large resistor in series for the Vin, use the LSB digit there as well.
  3. Markd77

    Senior Member

    Sep 7, 2009
    Depending on the processor you may have a normal oscillator and a watchdog timer which run at different and varying rates. You can use that variance to seed the random number generator.
  4. someonesdad

    Senior Member

    Jul 7, 2009
    You first need to tell us what language you're using (could be C or C++), what processor it's for, what compiler, etc.

    If it's C, then a common tool is the pseudorandom number generator in the library function rand() (include stdlib.h). The execution of the functions is then controlled by the value returned from rand(). One way would be to look at the remainder of an integer division by the number of functions you have to call and use that to e.g. control a case statement.

    If you're in an embedded context, you may not have such a library function available. You can find short assembler routines that work reasonably well as pseudorandom number generators. Also consult Knuth (a standard reference) and "Numerical Recipes" also gives some generators, especially if you have floating point arithmetic available.