Raspberry Pico randomSeed() ?

I am programming the Raspberry Pico with the Arduino IDE
Using this Pico core: GitHub - earlephilhower/arduino-pico: Raspberry Pi Pico Arduino core, for all RP2040 boards

My problem is I want to get different random values, so I used
randomSeed(analogReadTemp());

But the output is always the same on each boot.

void setup() {
  Serial.begin(115200);
  randomSeed(analogReadTemp());
    for (int i=0; i<10;i++){
    Serial.println(random(10));
  }
  delay(3000);
}

void loop() {
  static int counter;
  counter++;
  // put your main code here, to run repeatedly:
  for (int i=0; i<10;i++){
    Serial.println(random(10));
  }
  Serial.print("vuelta --->");
  Serial.println(counter);
  delay(2000);
}

Maybe randomSeed() is not supported in this core? Is there anything I could do to make numbers different in each run? Thanks!

Yes, is supported, it should work.
Try

randomSeed(analogRead(A0));

If A0 isn't in use, obviously. :wink:

Regards

I'd guess that if you print-out analogReadTemp() it's the same every time and you're using the same seed value.

That depends... I've got an application with audio input so if there is an audio signal when I seed the random number generator, it's "more random" (more unpredictable).

A reliable way to seed is to call random() while waiting for the user to press and release a button. The chances of repeating that button push timing are very, very small.

2 Likes

Notes and Warnings

If the seed is 0, randomSeed(seed) will have no effect.

Thanks all for the answer!

I tried to print out analogReadTemp() and it works, but it's not very precise so there are a few numbers that repeat if the temperature doesn't change. Printing for 2 seconds the output give me this results:

  • 23.39: 52 times
  • 24.33: 285 times
  • 23.86: 586 times
  • 24.80: 3 times
  • 22.93: 13 times

So there is a very high chance at that time of getting 23.86, and half the chance of getting 24.33. So it's not very random.

A reliable way to seed is to call random() while waiting for the user to press and release a button. The chances of repeating that button push timing are very, very small.

This seems the best approach.

Time in micros and only use the low 8 or 16 bits.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.