Hi!
I´ve got a moisture sensor which gives values from 456 to 856. How can I get values in percentage: 456=100% and 856=0% in MicroPython?
Hi José.
What do you mean?
You want something similar to the map function in Arduino?
You can create your own function like this, for example:
def my_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)
- x is the value you want to get in percentage.
- in_min: in this case is 856
- in_max: in this case is 456
- out_min: in this case is 0(%)
- out_max: is 100 (%)
So, for example, if you want to convert the value 556, you can do it like this:
value_percentage=my_map(556, 856, 456, 0, 100) print(value_percentage)
Tell me if this is what you were looking for.
Regards,
Sara
Perfect. Thanks.
After a couple of tries the following code gives a number form 0-100:
from machine import Pin, ADC
from time import sleep
hum = ADC(0)
def my_map(hum_value, in_min, in_max, out_min, out_max):
return int((hum_value-in_min) * (out_max-out_min) / (in_max-in_min) + out_min)
while True:
hum_value = hum.read()
hum_percent = my_map(hum_value, 856, 456, 0, 100)
print(hum_percent)
sleep(0.1)