Shop OBEX P1 Docs P2 Docs Learn Events
Scale function in Spin — Parallax Forums

Scale function in Spin

jdoleckijdolecki Posts: 726
edited 2013-11-12 19:18 in General Discussion
Arduino has a scale function to scale data

val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)

How do i do this in spin?

Comments

  • SRLMSRLM Posts: 5,045
    edited 2013-11-12 19:06
    Take a look at the source:
    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;
    }
    

    If you assume that the minimum of the ranges are always 0 then you can simplify:
    long map(long x, long in_max, long out_max)
    {
      return (x) * (out_max) / (in_max);
    }
    
  • Beau SchwabeBeau Schwabe Posts: 6,566
    edited 2013-11-12 19:18
    Here is a Spin PUB function which takes a similar approach to SRLM's version

    pub map(_val,lowIN,highIN,lowOUT,highOUT)|deltaIN,deltaOUT
        deltaIN  := highIN-lowIN
        deltaOUT := highOUT-lowOUT
        result := ((deltaOUT * (_val-lowIN)) / deltaIN)+lowOUT
    
Sign In or Register to comment.