Random Walk Program (Paul Badger 2007)

The program returns the same value for "stepsize" for each run. I have recorded the first seven step sizes
for ten runs and they are identical (5,1,-4,-3,0,-2,-5).
What am I missing?

How about some links so I don't have to go google surfing for Paul Badger and whatever else? Also if you wrote code, please post it in code tags.

Unless your program has some means of randomly initializing the random number generator (called seeding), it will always return the same sequence of values from startup.

Hi,
Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html

You must assume we know nothing about your project.

Thanks.. Tom.. :slight_smile:

Here is the code in question, from the Arduino Playground.

/* RandomWalk
 Paul Badger 2007
 RandomWalk wanders up and down randomly between two endpoints. The maximum move in one loop is governed by the parameter "stepsize".
 A static variable is moved up and down a random amount. This technique is also known as "pink noise" and "drunken walk".
 Useful for more pleasant electronic music sounds than straight random calls. Flickering LED's?
 My really cursory testing seems to indicate that it has a slight positive bias - meaning that it hangs around the 
 upper end of the range just slightly more than the lower end.
 */

#define randomWalkLowRange -20
#define randomWalkHighRange 20
int stepsize;

int thisTime;
int total;

void setup()
{
  Serial.begin(9600);
  Serial.println("start ");
}

void loop()
{        //  tetst randomWalk function
  stepsize = 5;
  thisTime = randomWalk(stepsize);
  total += thisTime;                  // aggregate values to see if function is really random
  Serial.print(thisTime);
  Serial.print("  ");
  Serial.println(total);
  delay(10);
}

int randomWalk(int moveSize){
  static int  place;     // variable to store value in random walk - declared static so that it stores
                         // values in between function calls, but no other functions can mess with its value

  place = place + (random(-moveSize, moveSize + 1));

  if (place < randomWalkLowRange){                    // check lower and upper limits
    place = randomWalkLowRange + (randomWalkLowRange - place);     // reflect number back in positive direction
  }
  else if(place > randomWalkHighRange){
    place = randomWalkHighRange - (place - randomWalkHighRange);     // reflect number back in negative direction
  }

  return place;
}