Shop OBEX P1 Docs P2 Docs Learn Events
Creating a function and using the results. — Parallax Forums

Creating a function and using the results.

I have the following formula:
map_val=((in_val-in_min)/(out_max-out_min)*(in_max-in_min))+out_min
It works when I use the formula for each calculation. But when I attempt to create a PUB function, Iam not getting the correct answers. The in/out values are constants with different values passed by the calling object. In_val is passed from the out of an adc object.
How do I write that such that I can call it passing the 5 parameters and using the map_val calculated?
Thanks
Jim

Comments

  • JonnyMacJonnyMac Posts: 9,085
    edited 2023-04-18 22:13

    I use this method in the P2 (with slight changes for the P1 [gte/lte operators])

    pub map(value, inmin, inmax, outmin, outmax) : result
    
    '' Maps value in range inmin..inmax to new value in range outmin..outmax
    
      if (value <= inmin)
        return outmin
      elseif (value >= inmax)
        return outmax
      else
        return (value - inmin) * (outmax - outmin) / (inmax - inmin) + outmin
    

    I use the if-else-elseif structure to skip unnecessary * and / instructions for the P1 (not a problem for the P2).

    For example, if you wanted to scale a 0-3.3v input to a new range of 0 to 100 (%), you would do this:

      percent := map(adcval, 0, 3300, 0, 100) 
    

    This assumes that you're analog input is in millivolts (I do this in my P2 ADC object).

    You can even flip output value polarity. My friend, John, makes camera platforms and we sometimes do things like this with a joystick or center-sprung pot.

      speed := adc.read()
      if (speed >= 0) && (speed <= 1550)                            ' left of deadband (reverse)
        set_motor(map(speed, 0, 1550, -100, 0))                     
      elseif (speed >= 1750) && (speed <= 3300)                     ' right of deadbadn (forward)
        set_motor(map(speed, 1750, 3300, 0, 100))
      else                                                          ' in deadband (stop)
        set_motor(0)
    
  • Thanks Jon, I will give that a try
    Jim

  • @JonnyMac
    Installed your code and as usual, it worked grreat.
    Thanks
    Jim

  • JonnyMacJonnyMac Posts: 9,085
    edited 2023-04-22 15:11

    I suspected it would. Good luck with your project.

Sign In or Register to comment.