Random numbers

Posted on
  • Is there currently any way to get a random number from the ESP8266? I currently have a bit of code that needs to generate a random ID on boot, but each time it gets the same ID.

    I've tried seeding the software random (which seems to do nothing) and the hardware random number generator (which also gives the same result each time).

    Thanks!

  • I haven't done anything special with random number stuff for the esp8266 port. I'm not seeing anything in the SDK to get a random number, so I think you have to seed the software random number generator with something clever...

  • E.srand(v) should seed it, but for some reason isn't.

    Looking at the implementation of it it seems to have an if statement for STM chips which gets a random number from an analog reading, but (I think) on other chips just gets a random number from the generator (which is always the same).

  • Yes, E.srand() should seed with whatever number you pass in. I wonder whether the ESP8266 port is using some ESP8266-provided rand function, and that isn't using srand?

    The STM32 (in jshardware.c) tries to seed the random number generator on startup using noise from the bottom bit of the ADC while looking at (iirc) the temperature of the chip.

  • jshGetRandomNumber listerally returns rand(). I suppose that's either a glib thing or a freertos thing? Dunno...

  • Ahh, right. rand() is probably the random number generator that you're seeding with jshGetRandomNumber :) Is there any source of entropy on ESP8266 that could be used? Internal voltage/temperature reference that you could take the bottom bit of?

  • yup, the ADC would probably work, even if it's measuring a floating pin...

  • @tve is the ADC currently accessible? Does it need a considerable amount of work to get it up and running? Thanks!

  • use

    analogRead(D0)
    
  • Unfortunately any call to analogRead seems to return 1, regardless of the pin. It doesn't even currently check whether a pin is valid, analogRead(100) and analogRead() also return 1.

  • on ESP8266 12E it is attached to the ADC pin, no input no value.

  • Ah, that's the problem there. I hooked it up and managed to get a reading out of 1024, but without something to create noise it's always going to be a fixed value.

  • I've found that this bit of code is just about good enough for me for the time being:

    var getRandom = function() {
      var r = getTime() * 10000;
      r -= parseInt(r);
      return r;
    };
    
    

    It gives a pseudo-random number due to the granularity of the timer.

  • works fine for me, if you like, use the short way to convert r to integer ;-)

    ...
    r=getTime()*1e6|0;
    ...
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Random numbers

Posted by Avatar for AlexOwen @AlexOwen

Actions