BASIC code for Aduino MAP function

JSDL

Senior Member
Hi everyone, I am trying to create a program that reads a POT value into a word variable, then maps it on a scale of 75 to 225 for use with a servo. I found the documentation on the Arduino MAP function which revealed the following:

private 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;
}

How would I go about writing the equivalent BASIC code. I know that:

-X value would be the word variable value
-"in-min" would be 0
-"out-max" would be 255
-"in-max would be 1023
-"out-min" would be 75

however, when I tried this it did not produce the results I expected.
 

hippy

Technical Support
Staff member
servo = 75 to 225

Or

Servo = ( 0 to 150 ) + 75

So you need to convert your pot of '0 to 1023' to ' 0 to 150' ...

0 to 150 = ( 0 to 1023 ) * 150 / 1023

So ...

servo = pot * 150 / 1023 + 75

But with 'pot' at 1023 * 150 will overflow 16-bits, so you need to either divide top and bottom by 10 and use ...

servo = pot * 15 / 102 + 75

or, more accurately, by dividing top and bottom by 3 ...

servo = pot * 50 / 341 + 75

or convert 150/1023 to 9609/65536 and then use ...

servo = pot ** 9609 + 75

Because 1023 * 50 does not overflow I would personally go for ...

servo = pot * 50 / 341 + 75
 
Last edited:

JSDL

Senior Member
servo = 75 to 225

Or

Servo = ( 0 to 150 ) + 75

So you need to convert your pot of '0 to 1023' to ' 0 to 150' ...

0 to 150 = ( 0 to 1023 ) * 150 / 1023

So ...

servo = pot * 150 / 1023 + 75

But with 'pot' at 1023 * 150 will overflow 16-bits, so you need to either divide top and bottom by 10 and use ...

servo = pot * 15 / 102 + 75

or, more accurately, by dividing top and bottom by 3 ...

servo = pot * 50 / 341 + 75

or convert 150/1023 to 9609/65536 and then use ...

servo = pot ** 9609 + 75

Because 1023 * 50 does not overflow I would personally go for ...

servo = pot * 50 / 341 + 75
worked perfect! The only thing I overlooked was the fact that not scaling down the two numbers proportionately resulted in an overflow, hence I was getting an incorrect value. The divide by 3 solved it. Thanks again Hippy!!
 
Top