randomSeed() and repeatable 'random' number on ESP32

Gridlock
Posts: 1
Joined: Mon Aug 17, 2020 2:15 pm

randomSeed() and repeatable 'random' number on ESP32

Postby Gridlock » Mon Aug 17, 2020 2:33 pm

Code: Select all

long randNumber;

void setup() {
  Serial.begin(9600);
  randomSeed(140584);
  delay(1000);
  Serial.println("BEGIN HERE");
  Serial.println("----------");
}

void loop() {
  randNumber = random(101010100, 757575759);
  Serial.println(randNumber);
  delay(1000);
}
Hi everyone, I am thoroughly enjoying learning development on my new ESP32 and I'm working on an idea that I've had for some time. I'd like to take a number (eventually it will be from a 1D barcode scan but for now I was just using a static number) and use it to generate a repeatable 9 digit number between 101010100 and 757575759. The random() and randomSeed() functions looked like they would be perfect by using pseudo-random numbers in the range I need with random() and then using randomSeed() to make it repeatable by starting at the same point in the random sequence on each execution of the sketch.

I used the code above and found that no matter what seed number I use the numbers are not repeatable, upon further research I found that the ESP32 has a true-random number generator by using the noise values on the WiFi/BLE chip, so that explains it.

This is one of the rare occurrences where the older pseudo-random functionality was more suited then true-random! By default the random() function calls esp_random() so I do not think it is possible to 'downgrade' and force the ESP32 to use seeded pseudo-random number sequences? I've been pulling my hair out with it.

May I ask if anyone has any advice? Many thanks, G

ESP_igrr
Posts: 2071
Joined: Tue Dec 01, 2015 8:37 am

Re: randomSeed() and repeatable 'random' number on ESP32

Postby ESP_igrr » Tue Aug 18, 2020 6:48 pm

You should be able to call srand and rand functions provided by the C standard library.
For example, srand(0) to set the seed and then rand() to get a value between 0 and UINT32_MAX.

Who is online

Users browsing this forum: No registered users and 94 guests