# Arduino:

**Generating random numbers**

## How to:

Arduino provides straightforward functions for generating random numbers: `randomSeed()`

and `random()`

. To start, seed the random number generator to ensure different sequences of numbers each time your program runs. An often-used approach is to seed with an analog read from an unconnected pin.

```
void setup() {
Serial.begin(9600);
// Initialize random seed
randomSeed(analogRead(0));
}
void loop() {
// Generate a random number between 0 and 99
int randomNumber = random(100);
Serial.println(randomNumber);
delay(1000); // Delay for a second for readability of output
}
```

The above program initializes the random number generator in the `setup()`

function and generates a new number between 0 and 99 in each loop iteration, outputting the number to the Serial Monitor.

Sample output:

```
42
17
93
...
```

## Deep Dive

Arduino’s `random()`

function under the hood leverages a pseudo-random number generator (PRNG), which follows a deterministic sequence but looks statistical random. The initial value, or seed, of the sequence highly influences its unpredictability, hence the common use of `randomSeed()`

with a somewhat random input as a starting point. It’s important to note that the randomness generated by Arduino is sufficient for most hobbyist projects but may not meet the criteria for high-security applications due to its predictability over time. For cryptographic purposes, it’s advisable to look into more sophisticated algorithms and hardware random number generators (HRNGs), which can provide true randomness by utilizing physical processes.