For testing my Smart Village I need random generation of temperature, humidity, pressure, smoke etc., so, using my knowlege, based on Micropython book by Rui, I wrote random generation module using os.urandom() module
def rand( floor, mod=0, negative = False): # return random value from -floor.mod to floor.nod if negative is True from os import urandom as rnd sign = 1 if ord(rnd(1))%10 > 5 else -1 sign = sign if negative else 1 if mod: value = float(('{}.{}').format(ord(rnd(1))%floor, ord(rnd(1))%mod)) else: value = int(('{}').format(ord(rnd(1))%floor)) return sign*value
For example, if I need random temperature in range -39.9 to 39.9:
for _ in range(10): print(rand(40,10,True))
or True/False sequence
for _ in range(10): print(rand(2))
Worked fine both on ESP32 and ESP8266
2 Answers
Thanks for posting a detailed solution on how to generate random numbers with MicroPython! I’ll point anyone that has this question to this thread.