typestar

random in Arduino

Seed from a floating pin, then draw from a range.

// A floating analog pin seeds random with real-world noise.
const int LAMP_PIN = 11;

void setup() {
  pinMode(LAMP_PIN, OUTPUT);
  randomSeed(analogRead(A5));
  Serial.begin(9600);
}

void loop() {
  // random(min, max) excludes the top: 0..255 here.
  int flicker = random(0, 256);
  analogWrite(LAMP_PIN, flicker);
  if (flicker > 250) {
    Serial.println("Full flare");
  }
  delay(random(40, 120));
}

How it works

  1. randomSeed(analogRead(A5)) uses electrical noise as entropy.
  2. random(0, 256) excludes the top bound.
  3. Even the delay is random — candle-flicker timing.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
385
Tokens
86
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 3 of 3 in Peripherals, step 24 of 27 in Language basics.

← Previous Next →