Playing with GAS
Playing with GAS

Reputation: 585

microbit Python: When using time module, how to keep sleep() units in milliseconds?

In microbit muPython: sleep(ms), the units is milliseconds.

However, if import time module and use sleep() then muPython uses time module’s sleep(s) which is units of full seconds. Coder must substitute time module’s sleep_ms(ms) to get units of milliseconds.

If using time module, how can I force use of the ‘normal’ sleep(ms)?

Or more generally, how can I specify using any command from the ‘normal’ muPython as opposed to the same-spelled command from an imported module?

# Task: Show SAD, sleep 1 sec, show HAPPY
# Problem: HAPPY takes 17 minutes to appear
from microbit import *
from time import *
display.show(Image.SAD)
sleep(1000) # uses time.sleep(units=sec) so 1,000 sec
display.show(Image.HAPPY)

Upvotes: 1

Views: 719

Answers (1)

Rob Hansen
Rob Hansen

Reputation: 317

Use from ... import ... as notation.

from microbit import sleep as microbit_sleep
from time import sleep as normal_sleep

microbit_sleep(1000) # sleeps for one second
normal_sleep(1000) # sleeps for much longer

Or, if you need everything in those two modules, just do a normal import.

import microbit
import time

microbit.sleep(1000)
time.sleep(1)

from ... import * is generally considered bad Python style precisely for the reasons you've discovered here. It's okay for really quick scripts, but best avoided as projects get larger and depend on more modules.

Upvotes: 3

Related Questions