Arduino has a map()
function that scales an integer value from one range to another. For example, you can take input from an 8-bit ADC sensor that ranges from 0–1024, and proportionally scale it to the range 0-100.
How would I do this in Python?
Arduino has a map()
function that scales an integer value from one range to another. For example, you can take input from an 8-bit ADC sensor that ranges from 0–1024, and proportionally scale it to the range 0-100.
How would I do this in Python?
Like buran mentioned in the comments, the Arduino reference page for map()
shows the full implementation, which can be copied almost verbatim into Python.
Here's the Arduino C++ code:
long map(long x, long in_min, long in_max, long out_min, long out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
And here's what it would look like in Python. The only real gotcha is that /
in Python returns a float even when both operands are integers; //
is specifically integer division.
def map_range(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
(I've also renamed it so it doesn't shadow Python's own map
, which is something different entirely.)
Why don't you just divide by the original range max value and multiply by new range max-value?
new_value = (int) (my_value/max_value)*new_range_max
EDIT: if the original value is binary you can convert it to decimal by doing:
int(b, 2) # Convert a binary string to a decimal int.