Reverse Map function

I converted the analog value to percentage so 1024 is 100% and 0 is 0% and for that, I used the map function (map(960, 1023, 644, 0, 100)). Now I want to reverse that so I can input 100% and can get 1024. I read that it's possible to do that with the map function but it didn't work. The analog value comes from a moisture sensor to read the soil humidity

think again:
you have found the map function to convert 1023-644 to 0-100.
now you search for function to convert 0-100 to x-1023 ?

which function could be used?

"does not work" is not a appropriate error message.
Make a short compileable sketch showing your problem, and others might be able to help you.
Describe what your sketch does currently
Describe what your sketch should do instead.

so if you do map(x, 1023, 644, 0, 100); you are asking to get a value between 0 and 100 when x varies from 1023 to 644

if you want to get a value between 1023 and 644 when x varies between 0 and 100, you do the opposite: map(x, 0, 100, 1023, 644);

remember it's integer only so you get rounded down to the nearest int and if your input value is not in the listed range then the output value won't be in the target range either. (it's just a linear mapping)

Why would you use map() for such a trivial conversion? It's simple scaling. Assuming your application can afford the time to do floating point multiply, just use:

  percent = adcReading * (100.0 / 1023.0);
  adcReading = percent * 10.23;

Assuming both adcReading and percent are integer data types.
You could also add rounding to the nearest integer value:

  percent = adcReading * (100.0 / 1023.0) + 0.5;
  adcReading = percent * 10.23 + 0.5;

because it's highly readable and maintainable and with compiler optimisation probably not slower that writing down the exact formula (esp. if you go float it will be slower)

1 Like

As long as you understand the implications of it being implemented with integer math.

What you think your function does is not what your function does

1 Like

fair to insist on this too

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.