microbit-foundation / micropython-microbit-v2

Temporary home for MicroPython for micro:bit v2 as we stablise it before pushing upstream
MIT License
42 stars 23 forks source link

Turning on the radio by default #97

Closed microbit-carlos closed 2 years ago

microbit-carlos commented 2 years ago

For the micro:bit radio to be used example programmes are usually like this:

import radio

radio.on()
radio.send('hello')
from microbit import *
import radio

radio.on()
while True:
    message = radio.receive()
    if message:
        display.scroll(message)

In all cases radio.on() is necessary to start using the radio, otherwise functions like radio.send() or radio.receive() will throw an exception ValueError: radio is not enabled.

The majority of the micro:bit features, specially those that can be turned off like the display, are "on" by default. The reason this is not the case for radio is because it has a significant impact on power consumption, about 10 mA as measure by Damien from USB, however:

If we are to enable the radio by default we have two options: a) Do it on import

We also need to consider if this would be a breaking change, as ideally we'd like to avoid that.

And, of course, we would have to mirror this to the MicroPython for V1 port.

microbit-carlos commented 2 years ago

About this being a breaking change or not, the majority of programmes would behave more or less the same, some of the biggest differences I can think of are:

Larger power consumption In programmes like this the additional power consumption might be noticeable:

import radio

# A lot of code executed here before sending data

radio.on()
radio.send("hello")

Expected Exceptions might not be thrown This would not throw an exception and therefore wouldn't print anything:

import radio

while True:
    try:
        radio.send("hello")
    except ValueError:
        print("turning on radio")
        radio.on()

Any other examples for consideration are very welcome.

microbit-carlos commented 2 years ago

a) Do it on import

  • Disadvantage: If an existing programme runs a lot of code before calling radio.on(), this is time with a larger power consumption b) Do it on the first call of radio.send()/.receive()/etc
  • Disadvantage: In this case the first call of radio.receive() would only turn on the radio, as it cannot receive anything while it's off

From these two options I think a) is better. This way it works out of the box, no incoming radio messages are missed, and a user can always do radio.off() immediately after import to conserve energy.

microbit-carlos commented 2 years ago

Decided to turn on the radio on import ✅

dpgeorge commented 2 years ago

Done in ca108e7d609c14b1c2a6c2e895eb019056a3e92d