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?

## map function

- OlivierLenoir
**Posts:**60**Joined:**Fri Dec 13, 2019 7:10 pm**Location:**Picardie, FR

### Re: map function

From this page, you can define your own function.ajocius wrote: ↑Sat Jan 18, 2020 9:29 amIs 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?

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))
```

Last edited by OlivierLenoir on Sat Jan 18, 2020 9:58 am, edited 1 time in total.

Olivier Lenoir

https://gitlab.com/olivier.len02

https://gitlab.com/olivier.len02

### Re: map function

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).

"linear interpolation"