Basic Library
Digital I/O
Analog I/O
Advanced I/O
Time
Math
Trigonometry
Random Numbers
Bits and Bytes
Interrupts
Serial Comm.
Standard Library
Camera
Servo Motor
Stepping Motor
Character LCD
SPI
I2C (Wire)
SD Card
SD (File Operations)
Periodic Operation
Clock (RTC)
Mbed Tips
Random Number
This library obtains random numbers. True random numbers can be obtained from ESP32 as shown in the sample.
randomSeed
- Description
- randomSeed() initializes 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.
- Syntax
- randomSeed(unsigned int seed)
- Parameters
- seed: A number to generate the seed
- Returns
- None
random
- Description
- Obtains the random numbers. Always call the randomSeed function before using this function.
- Syntax
- long random(long min_num, long max_num)
- Parameters
- min_num: Lower bound of the random value, inclusive (optional)
max_num: Upper bound of the random value, exclusive (optional) - Returns
- A random number (long)
Sample Program
This example outputs a random number between 0 and 99 in 100ms intervals via serial communications.
#include <Arduino.h>
#define INTERVAL 100
void setup()
{
Serial.begin(9600);
randomSeed(millis());
}
void loop()
{
Serial.println( random(0, 100) );
delay(INTERVAL);
}
Get a 32-bit true random number.
#include <Arduino.h>
#include <Wire.h>
#define ESP32_I2C_ADDR 0x28
void setup() {
Serial.begin(9600);
Wire.setFrequency(150000);
Wire.begin();
pinMode(PIN_ESP_EN, OUTPUT);
pinMode(PIN_ESP_IO0, OUTPUT);
pinMode(PIN_SW0, INPUT);
pinMode(PIN_SW1, INPUT);
digitalWrite(PIN_ESP_IO0, HIGH);
delay(100);
digitalWrite(PIN_ESP_EN, HIGH);
delay(1000);
}
void loop() {
Wire.beginTransmission(ESP32_I2C_ADDR);
Wire.write(0);
Wire.endTransmission();
uint32_t rand;
Wire.requestFrom(ESP32_I2C_ADDR, 4);
rand = Wire.read();
rand <<= 8;
rand += Wire.read();
rand <<= 8;
rand += Wire.read();
rand <<= 8;
rand += Wire.read();
Serial.print(rand, HEX); // print the character
Serial.println();
delay(100);
}