30 Days Lost in Space → Help Center

Coding Concepts

randomSeed() and random() in Arduino Code

Without randomSeed(), random() repeats the same numbers after every reset. How seeding works, seeds that silently fail, the excluded max and tested sketches.

random() doesn't make new randomness: it reads the next number from a fixed pseudo-random sequence, so without randomSeed() the board produces exactly the same "random" numbers after every reset. Call randomSeed(analogRead(A0)) once in setup(), with A0 left unconnected, and each run starts at a different point in that sequence.

The rest of this page shows the sequence itself, the two forms of random(), the seeds that silently fail, and three projects from the 30 Days Lost in Space kit.

Pseudo-Random, Not Random

Think of a huge book of numbers, printed once at the factory. Every call to random() reads the next number from the book. Within one run the numbers look random, because they don't follow any pattern you could spot. But every reset opens the book on the same page.

You can see it. With no seed, random(100) on the HERO Board starts 7, 49, 73, 58, 30, every single time. We confirmed it by running the compiled sketch in our simulator:

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < 5; i++) {
    Serial.println(random(100));   // 7, 49, 73, 58, 30 without a seed
  }
}

void loop() {}

The Two Forms of random()

random(max)

Returns a number from 0 up to, but not including, max.

int val = random(6);   // 0, 1, 2, 3, 4 or 5. Never 6.

random(min, max)

Returns a number from min up to, but not including, max.

int val = random(1, 7);  // 1, 2, 3, 4, 5 or 6. Never 7.

The max value is always excluded. This is the number one source of bugs with random(). For a die roll from 1 to 6 you need random(1, 7), not random(1, 6).

| What you want | What to write | |---------------|---------------| | 0 to 255 | random(256) | | 1 to 10 | random(1, 11) | | 0 to 180 (servo) | random(181) | | 0 or 1 (coin flip) | random(2) | | -1, 0 or 1 | random(-1, 2) |

Both forms take and return long, so large ranges work. Two edge cases, both checked in our simulator: random(0) returns 0, and when min is not below max, random(min, max) just returns min (random(5, 5) is 5, random(7, 3) is 7).

randomSeed(): Picking a Different Starting Page

randomSeed(seed) sets where in the sequence random() starts. The same seed always gives the same sequence: randomSeed(42) followed by five random(100) calls gave 94, 23, 9, 43, 26 both times we ran it. A different seed gives a different run.

The classic trick for a different seed on every power-up is to read an unconnected analog pin:

void setup() {
  randomSeed(analogRead(A0));  // A0 with nothing attached: electrical noise
}

A floating pin picks up tiny amounts of noise that vary from one power-up to the next. Call randomSeed() once, in setup(), never in loop().

Seeds That Silently Fail

  • randomSeed(0) is ignored. The function skips a seed of 0, so the sequence stays at its default 7, 49, 73. A pin wired to GND reads 0, and seeds nothing.
  • randomSeed(millis()) in setup(). millis() is still 0 when setup() runs (we printed it), so this is randomSeed(0) in disguise. micros() at that moment is nearly the same on every power-up too.
  • A pin with something connected. If a sensor sits on A0, its reading is a steady value, not noise. Pick a free pin: the course's Day 29 sketch uses A3, which it leaves empty for exactly this.
  • A floating pin that barely floats. Real floating pins often read in a narrow band, so you get far fewer than 1,024 different sequences. In a simulator an unconnected pin can read the same value every run (ours reads 0).

The most reliable seed on a small board is a person. Nobody presses a button on the same microsecond twice, so seed from micros() at the first press, as in Example 1. It works on a real board and in the simulator alike.

Example 1: A Dice Roller Seeded by Your First Press

The rotary encoder in the 30 Days kit has a push switch: wire SW to pin 4 (plus the encoder's power and ground). Each press rolls a die:

// Dice: press the encoder's knob to roll. The first press also seeds random() from
// the exact microsecond you pressed, so no two games roll the same.
const int SW_PIN = 4;   // the rotary encoder's push switch: LOW while pressed
bool seeded = false;
int lastSw = HIGH;

void setup() {
  pinMode(SW_PIN, INPUT_PULLUP);
  Serial.begin(9600);
  Serial.println("Press the knob to roll");
}

void loop() {
  int sw = digitalRead(SW_PIN);
  if (sw == LOW && lastSw == HIGH) {   // a new press
    if (!seeded) {
      randomSeed(micros());            // a person never presses on the same microsecond twice
      seeded = true;
    }
    Serial.print("You rolled ");
    Serial.println(random(1, 7));      // 1 to 6: the 7 is never returned
  }
  lastSw = sw;
  delay(20);                           // also rides out the switch's bounce
}

The first press stores the exact microsecond as the seed, so every game rolls differently, even right after power-up.

Example 2: Random Colors, Never Twice in a Row

Truly random picks repeat more often than people expect: a die shows the same face twice in a row one roll in six. For lights and games that feels broken, so roll again on a repeat. RGB LED legs on pins 9, 10 and 11, each through a 220 Ω resistor:

// Random colors on the RGB LED, never the same color twice in a row.
const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;

const byte COLORS[6][3] = {
  {255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 160, 0}, {0, 255, 255}, {150, 0, 255}
};
int last = -1;

int pickColor() {
  int n;
  do {
    n = random(6);          // 0 to 5
  } while (n == last);      // the same as last time? roll again
  last = n;
  return n;
}

void setup() {
  randomSeed(analogRead(A3));   // A3 left unconnected: floating-pin noise
  Serial.begin(9600);
}

void loop() {
  int c = pickColor();
  analogWrite(RED_PIN, COLORS[c][0]);
  analogWrite(GREEN_PIN, COLORS[c][1]);
  analogWrite(BLUE_PIN, COLORS[c][2]);
  Serial.println(c);
  delay(300);
}

The do { } while loop keeps rolling until the color differs from the last one. With six colors it rarely needs more than one extra roll. The PWM guide explains how analogWrite() mixes the color.

Example 3: Weighted Randomness, from Day 29

Sometimes you want some outcomes more often than others. The 30 Days Day 29 lesson moves a mother ship around the screen with random drift of -1, 0 or +1, but wants "no drift" twice as often. Its trick: roll one extra value and treat it as 0.

const byte DRIFT_CONTROL = 3;  // Must be > 1.  Higher numbers slow drift rate

int getRandomDrift() {
  int drift = random(-1, DRIFT_CONTROL);   // -1, 0, 1 or 2
  if (drift > 1) {  // Values over 1 are changed to 0
    drift = 0;
  }
  return (drift);
}

Raise DRIFT_CONTROL and more of the rolls become 0, so the ship drifts more slowly. The same lesson seeds with randomSeed(analogRead(A3)) on its empty A3 pin.

When You WANT the Same Sequence

Predictable randomness is useful too:

  • Debugging: chasing a bug that only shows up with certain random values? A fixed seed such as randomSeed(1234) replays the same values on every run.
  • Testing: two people with the same seed see exactly the same "random" game.

Practical Ranges

| Project | Call | Why | |---------|------|-----| | LED brightness | random(256) | PWM is 0 to 255 | | Candle flicker delay | random(20, 151) | Looks like a flame | | Random tone | random(200, 2001) | Audible, sounds good on a small buzzer | | Servo position | random(181) | Full sweep: 0 to 180 | | RGB color channel | random(256) | Full range per channel | | Dice roll (1 to 6) | random(1, 7) | Max is excluded, remember |

Common Mistakes

| Mistake | What Happens | Fix | |---------|-------------|-----| | Calling randomSeed() in loop() | Restarts the sequence over and over; the output barely changes | Call it once in setup() | | Off-by-one on max | random(255) never returns 255; random(1, 6) never rolls a 6 | Add one: random(256), random(1, 7) | | Not seeding at all | The same numbers after every reset | Seed from an empty analog pin or a button press | | randomSeed(millis()) in setup() | No effect: millis() is 0 there, and a 0 seed is ignored | Seed from a press, or from an empty analog pin | | Seeding from a pin with a sensor on it | The same seed every time | Use a pin with nothing attached | | Using it for passwords or security | The sequence can be predicted | Fine for games and lights, never for security |

Frequently Asked Questions

Is random() truly random?

No. It's a pseudo-random generator: a formula that produces a long, patternless-looking sequence that is identical every time it starts from the same seed. That's perfect for games, light effects and simulations, and wrong for anything secret.

Why does my board give the same random numbers every time?

Because the sequence starts from the same seed after every reset. Without randomSeed(), random(100) always begins 7, 49, 73, 58, 30. Add randomSeed(analogRead(A0)) in setup() with A0 unconnected, or seed from the first button press.

How do I get a random number between 0 and 255?

random(256). The upper limit is excluded, so random(255) stops at 254.

Where should randomSeed() go?

In setup(), once. Seeding again inside loop() keeps restarting the sequence, which makes the numbers less random, not more.

What does randomSeed(analogRead(A0)) do?

It reads the electrical noise on an analog pin with nothing connected (a number from 0 to 1023) and uses it as the starting point of the sequence. It only works if A0 really is unconnected, and a reading of exactly 0 is ignored.