Page 1 of 1

map function

Posted: Sat Jan 18, 2020 9:29 am
by ajocius
Is there equivalent in Micropython of map function in Arduino?

You can use following function in arduino PWMval=map(sensorVAL, 40, 80, 0, 1023). This function would return PWMval between 0 and 1023 in relation of sensorVal value, that is defined to be in the range 40 and 80. This would be linear correlation.

I would like to implement same in micropython, but not sure if this function exists?

Re: map function

Posted: Sat Jan 18, 2020 9:50 am
by OlivierLenoir
ajocius wrote:
Sat Jan 18, 2020 9:29 am
Is there equivalent in Micropython of map function in Arduino?

You can use following function in arduino PWMval=map(sensorVAL, 40, 80, 0, 1023). This function would return PWMval between 0 and 1023 in relation of sensorVal value, that is defined to be in the range 40 and 80. This would be linear correlation.

I would like to implement same in micropython, but not sure if this function exists?
From this page, you can define your own function.

Code: Select all

# Will return a float
def convert(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min


# Will return a integer
def convert(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min


# Will return an integer between out_min and out_max
def convert(x, i_m, i_M, o_m, o_M):
    return max(min(o_M, (x - i_m) * (o_M - o_m) // (i_M - i_m) + o_m), o_m)


# Test
for i in range(200):
    print(i, convert(i, 40, 80, 0, 1023))

Re: map function

Posted: Sat Jan 18, 2020 9:53 am
by jimmo
ajocius wrote:
Sat Jan 18, 2020 9:29 am
Is there equivalent in Micropython of map function in Arduino?
Not that I'm aware of -- I think this generally follows the principle that anything that can be done in Python is better off left to the user's code (whether they write it themselves or use an existing library etc). Unlike Arduino, where if you don't use `map()` then it doesn't take up space in the firmware, MicroPython has to include everything in the default firmware.

(I do agree that a built-in lerp would be really useful though)

If you do implement this yourself, be aware that although it's very easy to do with floating point, if all you want is integer values, then do all the calculations with integers (i.e. use // instead of / for divide) and it'll be much faster and not create any objects in memory. (In many MicroPython ports, floating point values need to be allocated on the heap).
ajocius wrote:
Sat Jan 18, 2020 9:29 am
This would be linear correlation.
"linear interpolation"

Re: map function

Posted: Sat Jan 18, 2020 1:33 pm
by ajocius
thank you both!