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

New Feature: Function to scale values with different ranges #102

Closed microbit-carlos closed 2 years ago

microbit-carlos commented 2 years ago

A function like this is quite useful to be able to map inputs an outputs with different value ranges. For example the output from one sensor to an LED brightness value, sound level, or sound effect attribute.

Arduino, and MakeCode have a map() function with the same argument order, so it'd be good to follow the convention:

map(value, fromLow, fromHigh, toLow, toHigh)

Although it's tempting to try to improve it:

map(value, from=(low,high), to=(low, high))

Would that be better? I personally don't feel strongly either way.

Options for the name

Where to we put the function?

dpgeorge commented 2 years ago

Let's go for microbit.scale(value, from=(low, high), to=(low, high).

But also need to decide if the function clamps as well as scales, or just scales?

microbit-carlos commented 2 years ago

I was originally thinking we should clamp, as a common use-case would be to map accelerometer get x/y/z values almost as if they were pitch/roll. In those cases if the board is calmly rotated it normally returns values up to around 1000 mg (1g), but can often be slightly larger than that (and much larger if the board is shaken).

However, the main goal of this function is two scale a value to a different range, so if the value is already out of the "from" range it should be the same for the "to" range. A good example is when converting between celsius and fahrenheit, as you normally would do this as microbit.scale(value, from=(0, 100), to=(32, 212)), and clamping would prevent this from working correctly.

Moreover, the user can still clamp the output value of this function if needed. So no need to do this inside the scale function.

microbit-carlos commented 2 years ago

Docs PR:

dpgeorge commented 2 years ago

Implemented in 0f0766fd7a8a95ead2ea1aa7512ae8780e99f0a9

Note that it does allow negative scaling, which could be useful. Eg map 0 to 100 into 0 to -50.