Home ArduinoArduino Tutorials Tutorial: Arduino Random Numbers

Tutorial: Arduino Random Numbers

by shedboy71

In Arduino, random number generation is essential for applications like gaming, simulating sensor data, or adding unpredictability to your projects.

Arduino provides built-in functions to generate random numbers, which can be controlled and tailored to your needs.

This tutorial explains how to use Arduino’s random number functions, how to set seeds for better randomness, and provides practical examples.

Table of Contents 1. What Are Random Numbers in Arduino?

Arduino can generate pseudo-random numbers, which are numbers generated using a mathematical algorithm. These numbers may seem random but are determined by an initial value called the seed. By setting the seed, you can control the sequence of random numbers.

2. Random Number Functions

2.1 randomSeed(seed)

  • Initializes the random number generator with a seed.
  • If you don’t set a seed, Arduino will use the default, leading to the same sequence of numbers each time.

Example: Set a Random Seed

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(A0));  // Use an analog pin to generate a random seed
}

void loop() {
  Serial.println(random(100));  // Generate random numbers
  delay(500);
}

2.2 random(min, max)

  • Generates a random number within a range.
  • Syntax:
    • random(max): Generates a number from 0 to max-1.
    • random(min, max): Generates a number from min to max-1.

Example: Generate Random Numbers

void setup() {
  Serial.begin(9600);
}

void loop() {
  int randNum = random(10, 20);  // Generate a number between 10 and 19
  Serial.println(randNum);
  delay(500);
}

3. Generating Random Numbers

3.1 Without Bounds

If you call random() without parameters, it generates a random long integer.

Example: Random Long Number

void setup() {
  Serial.begin(9600);
}

void loop() {
  long randNum = random();  // Generate a random long number
  Serial.println(randNum);
  delay(500);
}

3.2 Within a Range

Use random(min, max) to constrain the random number to a range.

Example: Random Number Between 1 and 100

void setup() {
  Serial.begin(9600);
}

void loop() {
  int randNum = random(1, 101);  // Generate a number from 1 to 100
  Serial.println(randNum);
  delay(500);
}

4. Practical Examples

4.1 Simulating Dice Rolls

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(A0));  // Initialize random seed
}

void loop() {
  int dice = random(1, 7);  // Generate a number between 1 and 6
  Serial.print("You rolled: ");
  Serial.println(dice);
  delay(1000);
}

4.2 Random LED Selection

const int ledPins[] = {2, 3, 4, 5};  // Define LED pins
const int numLeds = 4;

void setup() {
  for (int i = 0; i < numLeds; i++) {
    pinMode(ledPins[i], OUTPUT);  // Set all LED pins as output
  }
  randomSeed(analogRead(A0));  // Initialize random seed
}

void loop() {
  int randomLed = random(0, numLeds);  // Pick a random LED
  digitalWrite(ledPins[randomLed], HIGH);
  delay(500);
  digitalWrite(ledPins[randomLed], LOW);
  delay(500);
}

4.3 Random Delays

const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  randomSeed(analogRead(A0));  // Initialize random seed
}

void loop() {
  digitalWrite(ledPin, HIGH);  // Turn LED on
  delay(random(100, 1001));    // Random delay between 100ms and 1000ms
  digitalWrite(ledPin, LOW);   // Turn LED off
  delay(random(100, 1001));    // Random delay between 100ms and 1000ms
}

4.4 Random Walk

Simulate a random walk by incrementing or decrementing a value randomly.

int position = 50;  // Start at the middle position

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(A0));  // Initialize random seed
}

void loop() {
  int step = random(-1, 2);  // Random step: -1, 0, or 1
  position += step;

  // Constrain position to 0-100
  position = constrain(position, 0, 100);

  Serial.print("Position: ");
  Serial.println(position);

  delay(200);
}

5. Best Practices for Using Random Numbers

  1. Use a Random Seed:
    • For better randomness, initialize the seed using an analog pin:
      randomSeed(analogRead(A0));
      
  2. Constrain Random Values:
    • Use random(min, max) to generate numbers within a specific range.
  3. Avoid Predictable Patterns:
    • If you need true randomness, avoid using fixed seeds.
  4. Validate Output:
    • Test the generated numbers to ensure they meet your project’s requirements.
  5. Use Delays Carefully:
    • When generating random delays, ensure the minimum value is reasonable to avoid unresponsive behavior.

Conclusion

Random number generation in Arduino opens up opportunities to add unpredictability to your projects, from simple games to complex simulations.

By using random() and randomSeed() effectively, you can generate numbers for a variety of applications.

This tutorial provides the foundational knowledge and practical examples to get you started.

For more details, visit the official Arduino reference.

 

You may also like