Random.choice in ESP8266

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
Felix Zangano
Posts: 2
Joined: Sun Dec 01, 2019 9:30 pm

Random.choice in ESP8266

Post by Felix Zangano » Sun Dec 01, 2019 9:44 pm

Hi all, i'm new here.

First of all, sorry for my bad english... I'm trying to make a simple program (i'm not a programmer) where it has to choose a random string in a list. I wrote in python, and it works, but in ESP8266 with micropython, this sentence:

random.choice(list_of_strings)

doesn't work, and retry this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'choice'


Of course i import random module. ¿It's possible that in micropython doesn't exist the attribute choice? I know it's a silly thing to make this kind of programs in ESP8266, but i'm trying to introduce my son in programming with a simple program displaying random stupid names in a little oled screen.

Thanks!

User avatar
jimmo
Posts: 892
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: Random.choice in ESP8266

Post by jimmo » Sun Dec 01, 2019 11:48 pm

Unfortunately random.choice isn't available in MicroPython on the ESP8266 -- it's one of the things that gets removed on the smaller microcontrollers, otherwise there wouldn't be enough room (but it is enabled on ESP32 and STM32).

On ESP8266, all you get is random.getrandbits().

But you can implement random.choice yourself -- it's the same as

def choice(x):
return x[randrange(0, len(x)]

And randrange (to get a random number between two numbers) can be copied from https://github.com/micropython/micropyt ... /random.py

Felix Zangano
Posts: 2
Joined: Sun Dec 01, 2019 9:30 pm

Re: Random.choice in ESP8266

Post by Felix Zangano » Mon Dec 02, 2019 2:52 pm

Thanks jimmo!!

I will try your example to see how works. I will try too with a M5Stack that has ESP32 (but i think micropython isn't totally implemented on it)

Post Reply