Rand

From Pinguino
Jump to: navigation, search

Name

rand - pseudo-random number generator

Description

Returns a pseudo-random integer in the range [0, RAND_MAX]

RAND_MAX is 32767 on Pinguino

Syntax

value = rand();

Output
A pseudo-random integer

Example

Blink a LED on port 11 for random periods.

#define MYLED 11

// Time to sleep
unsigned short pause;

void setup(void)
{
        pinMode(MYLED,OUTPUT);
        // Init random generator with a fixed random value
	randomSeed(55);
}
 
void loop(void)
{
        // Pause is between 0 and 0b111 (7 in decimal)
	pause = rand() & 0x007;
        // Light ON
        digitalWrite(MYLED,HIGH);
        // delay is between 200ms and 1.6s
        delay(200 * (pause + 1));
        // Light off
        digitalWrite(MYLED,LOW);
        // Delay 200ms
        delay(200);
}

Bugs

See also

Comments