How to scale numbers / values

I work with hardware that I communicate with VIA serial control using a proprietary programming language that looks like a very dumb version of C.

The device requests the current volume when requested. The range is from -60 to + 20. How do I scale it to the range 0-255, which increases in increments of 3?

Can you also give an example of a different value and a different scale, i.e. from -15 to 15, scaled to 0-165, etc.

+4
source share
2 answers

This is really simple math.

First remove the need for a negative number:

For the range -60 ↔ + 20: x + 60

Now we have a range of 0 ↔ 80, just scale it to 255: (x / 80) * 255

Put this all in the formula, and this is what you should get: y = ((x + 60) / 80) * 255

So basically:

y = ((x + negativeValue) / MaxValue) * MaxScale

I hope you understand now!

+6
source

To scale the range x0..x1 to the new range y0..y1:

y = y0 + (y1 - y0) * (x - x0) / (x1 - x0) 

So, for your first example above, x0 = -60, x1 = 20, y0 = 0, y1 = 255:

  y = 0 + (255 - 0) * (x - -60) / (20 - -60) => y = 255 * (x + 60) / 80 
+6
source

Source: https://habr.com/ru/post/1440596/


All Articles