random() returning numbers at bottom of range

Hi there :slight_smile:
I was just messing around with a row of 10 LEDs connected to pins 4-13, and wrote a simple function to make a random number of LEDs flash in a random order, however only the LEDs connected on pins 4-9 behaved as expected, the other LEDs on pins 10-13 just occasionally lit up every(obviously it varies but approx) 10 seconds, then stayed on for a while, then switched back off again.

int L[] = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4};

void setup(){
//pinModes
}

void loop(){
  Random();
}

void Random(){
  digitalWrite(L[random(4,14)], HIGH);
  delay(50);
  digitalWrite(L[random(4,14)], LOW);
  delay(50);
}

Even when I tried this exactly the same problem happened

  void Random(){
  digitalWrite(L[random(4,10)], HIGH);
  delay(50);
  digitalWrite(L[random(4,10)], LOW);
  delay(50);
  digitalWrite(L[random(10,14)], HIGH);
  delay(50);
  digitalWrite(L[random(10,14)], LOW);
  delay(50);
}

Any help much appreciated :slight_smile:

Apart from any other problem, every time you run the program you will get the same sequence of (non)random numbers.

You're overstepping the bounds of your L array.

This:

  digitalWrite(L[random(4,14)], HIGH);

Could simply be this:

  digitalWrite(random(4,14), HIGH);

You're using random to get the pins you want, which in this case means you don't need L at all. If you want to use L, you reed to get a random number between 0 and 9 to address the array properly.

Also the built-in random function is, if I recall right, not brilliant.

You're overstepping the bounds of your L array.

So, the correct solution is to change the arguments to the random() function, not discard the array.

MarkT:
Also the built-in random function is, if I recall right, not brilliant.

https://www.google.com/search?q=park+miller+minimum+standard

Speed-wise it's not too bad (there are now much faster). Quality-wise it's certainly good enough to blink LEDs (it has some weaknesses / fails a few basic tests; there are now much better).

I tested it and four reasonable replacements...
http://zygomorphic.com/arduino-tiny/?p=78

wildbill:
You're overstepping the bounds of your L array.

This:

  digitalWrite(L[random(4,14)], HIGH);

Could simply be this:

  digitalWrite(random(4,14), HIGH);

You're using random to get the pins you want, which in this case means you don't need L at all. If you want to use L, you reed to get a random number between 0 and 9 to address the array properly.

Thanks very much, don't know why I didn't see that myself :slight_smile: