microbit-foundation / micropython-microbit-v2

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

Display rotation #153

Closed microbit-carlos closed 2 weeks ago

microbit-carlos commented 1 year ago

CODAL has added a way to rotate the display, which is useful to illustrate/teach how phones use an accelerometer to rotate their display.

One API proposal could be:

from microbit import display

display.rotate(display.ROTATION_XX)

Where ROTATION_XX can be ROTATION_0, ROTATION_90, ROTATION_180 or ROTATION_270.

CODAL uses a 0-3 enum for these values, but it makes sense to use 0, 90, 180 and 270 for the user API so that this can still work display.rotate(180).

Should setting an invalid value throw an exception? Some of the other APIs do a "best effort approximation", but I'm not sure if it's a good approach that display.rotate(45) could end up doing a 0 or 90 degree rotation.

With exceptions for incorrect values I think it's important to have the display.ROTATION_XX constants. If exceptions aren't used I guess we could save a bit of memory by not using the constants and documenting the values. To be fair this argument is easy to guess, it's not like a limited list of words (like the sound expressions).

Another thing that would only work without exceptions is something like:

while True:
    for x in range(0, 360):
        display.rotate(x)
        sleep(10)

But to be fair, with exceptions this is also an option.

while True:
    for x in (0, 90, 180, 270):
        display.rotate(x)
        sleep(1000)

Right now I'm leaning towards no exceptions, no constants and documenting the values. Thoughts?

dpgeorge commented 1 year ago

Right now I'm leaning towards no exceptions, no constants and documenting the values.

I think the "no constants" option is a good one. Because, as you say, it's very easy to guess what the allowed values are for the argument.

There are also lots of other cases in the API where numbers are used instead of constants, eg UART baudrate, volume level.

Regarding exceptions or not: I'm on the fence there. If users want to use an expression to calculate the angle (eg display.rotate(accelerometer.get_x())) then it would be better not to raise an exception but instead round the value.

Also, might make sense to support negative values, eg -90 is the same at 270.

dpgeorge commented 3 weeks ago

See #220 for an implementation.

dpgeorge commented 2 weeks ago

Implemented in ff39fbf5d7635035b5a84e625b9d248dbb380b4b

microbit-carlos commented 2 weeks ago

Docs PR: