Pololu Robotics & Electronics
Menu
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

Random numbers

Is there a way to generate a random number withthe Micro Maestro script? I want 2 servos to move for random intervals and for random durations. I have searched the manual but am unable to see this function addressed.

thanks

Hello,

Unfortunately, there is no built-in random number generator on the Micro Maestro. To get randomness, you could compute a simple pseudo-random number sequence, do ADC on a noisy input, or some combination of the two. Do you have a free line for use as an analog input?

-Paul

I should have. I am only using 2 servos and possibly a switch to turn off and on.

Given some kind of pseudo-random seed, there are lots of ways to generate reasonably random number sequences. Here’s a simple one:

    static int randomNumber(int *seedValue, int returnLessThanThis)
    {
        *seedValue = abs((*seedValue * 125) % 2796203);
        return (*seedValue % returnLessThanThis);
    }

As Paul suggested, you could easily sample some analog voltage input to act as your seed value. Or if your project waits for user input at any point–say, between turning it on and pressing the ‘go’ button–then you could measure the time difference between startup and the user pressing that button and use that as your initial seed value.

1 Like