• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

Generating random in micropython.for ESP

Q&A Forum › Category: Home Automation › Generating random in micropython.for ESP
0 Vote Up Vote Down
zolandv asked 6 years ago

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

Question Tags: #IOT, #Smart Home, #Smart village
2 Answers
0 Vote Up Vote Down
Rui Santos Staff answered 6 years ago

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.

0 Vote Up Vote Down
zolandv answered 6 years ago

You are welcome! Hope it’s will be useful for DIY enthusiasts.
I just start to learn Micropython, but it’s fine. Thank for your Book!

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.