• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

percentage in Micropython

Q&A Forum › percentage in Micropython
0 Vote Up Vote Down
José Magalhães asked 5 years ago

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?

3 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

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

0 Vote Up Vote Down
José Magalhães answered 5 years ago

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)

0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi again.
That’s great!
I’ll mark this issue as resolved. If you need further help, you just need to open a new question in our forum.
Regards,
Sara

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [eBook Updated] Learn Raspberry Pi Pico/Pico W with MicroPython eBook – Version 1.2 May 26, 2025
  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.