Skip to content

randomSeed

gicking edited this page Feb 10, 2018 · 1 revision

back to Command Reference / Random-Numbers

Description

Initialize the pseudo-random number generator, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same.

If it is important for a sequence of values generated by random() and randomIn() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as the ADC voltage on an unconnected pin, or the micros between user inputs.

Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling randomSeed() with a fixed number, before starting the random sequence.

Inclusion

  • defined in misc.h
  • auto-loaded in main_general.h
  • no #define required

Syntax

randomSeed(seed)

Parameters

  • input:

    • seed: number to initialize the pseudo-random sequence (unsigned long)
  • output:

    • none

Returns

  • nothing

Example Code

The below code makes pin PH2 (=LED on muBoard) an OUTPUT and toggles it HIGH and LOW with random delay. Pseudo random number generator is (rudimentarity) randomized with ADC measurement at a floating pin.

#include "main_general.h"   // board-independent main
#include "adc2.h"           // for random seed
    
void setup()
{
  pinMode(&PORT_H, 2, OUTPUT);        // set PH2 as output

  // randomize random number generator (VERY rudimentary)
  pinMode(&PORT_B, 0, INPUT);         // configure ADC0(=PB0) as input float
  ADC2_init(ADC_SINGLE_SHOT);         // configure ADC2 for single measurement
  randomSeed(ADC2_measure_single(0));

}

void loop()
{
  // toggle PD0
  pinToggle(&PORT_D, 0);

  // wait random delay within 50..200ms
  delay(randomIn(50, 200));

}

Relevant Tutorial

  • tbd

Notes and Warnings

  • for implementation details and limitations see compiler documentation for srand()

See also

Clone this wiki locally