Sitemap / Advertise

Information



Tags



Share

How to replicate the Arduino map function in Python for Raspberry Pi

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement


Banggood
Banggood


Definition

In this tutorial, I will show you how to copy the integrated map function in the Arduino IDE in Python. In this way, you can use the map function in your Raspberry Pi projects. If you need to rearrange a set of numbers in a defined range with the Arduino map function, copy the _map() function to the source code of your Raspberry Pi project.

Code

- The _map() function is exactly the same function in the Arduino IDE named the map() function.

- If you want to get more information about the map() function, read the following part.

Syntax(1):

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.

The function also handles negative numbers well.

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


-------------- Python --------------

#  Prominent Arduino map function :)
def _map(x, in_min, in_max, out_min, out_max):
    return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
	
# TEST
y = _map(25, 1, 50, 50, 1)
print(y)

Result:

Inspect my electronics project in which I used the same method to replicate the Arduino map function in Python from here :)

References

(1) https://www.arduino.cc/reference/en/language/functions/math/map/