Skip to content
gicking edited this page Feb 10, 2018 · 1 revision

back to Command Reference / Random-Numbers

Description

Generate a pseudo-random number within [0;32767]

Notes:

  • the used pseudo random number generator by default starts with a fixed seed of 1. To randomize the result, call randomSeed() with a random parameter, e.g. from a floating ADC input (see example)
  • randomIn() can be used to generate a random number in a specified range

Inclusion

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

Syntax

r = random()

Parameters

  • input:

    • none
  • output:

    • none

Returns

  • pseudo-random numbers within [0;RAND_MAX], with RAND_MAX=32767 for both SDCC and Cosmic

Example Code

The below code makes pin PD0 (=LED on STM8S Discovery Board) OUTPUT and toggles it HIGH and LOW with random delay. Note that without random seed via randomSeed(), the sequence is always the same.

#include "main_general.h"   // board-independent main
    
void setup()
{
  pinMode(&PORT_D, 0, OUTPUT);        // configure PD0 as output
}

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

  // wait random delay between 50..200ms
  delay(50 + random() % 150);
}

Relevant Tutorial

  • tbd

Notes and Warnings

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

See also

Clone this wiki locally