# Simple Speed question - Mapping PWM values

I am working on an Arduino project for school to power a 12V DC cooling fan.

I want to adjust the speed of the fan. The instructions say to set the motor pin at an equation of `(0 to 9) * 10 + 150` to get a range of 150 to 240.

I need to write a mathematical equation but can not figure out what 150 to 240 means. Is this voltage, resistance...? Thanks for the help.

The `analogWrite()` function takes a value that is between 0 (fully off) and 255 (fully on).

Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

• (150 / 255) * 100 = 58.8% on time
• (240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive. Let's call this value "i". You want an output value, let's call it "o".

The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula. 0-9 is i, remember:

• o = i × 10 + 150

If i is 0 then o = 0 × 10 + 150 = 0 + 150 = 150.

If i is 9 then o = 9 × 10 + 150 = 90 + 150 = 240.

As Ignacio mentions, the Arduino API has a `map` function which is meant to be used for this kind of thing;

``````o = map(i, 0, 9, 150, 240);
``````

However: the `map()` function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.

• Doesn't `map` just approximate with integer division instead of using floating-point? – NobodyNada - Reinstate Monica Dec 24 '15 at 5:52
• Actually it looks like the current version does use long not float. I am sure an older iteratipn was float based. They probably changed it because it was too heavyweight. So yes, you can use map if you like, but since it is a generic function it will be less efficient anyway than doing the correct specific simple calculation. – Majenko Dec 24 '15 at 9:24

They're the value to pass to `analogWrite()` in order to generate a PWM waveform with an appropriate duty cycle.

But don't bother writing your own algorithm, just use `map()`.

• He said he needs to write the equation – Rob Dec 23 '15 at 21:08

The map() function is the answer. It "rescales" the range of the data, using this formula:

``````(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
``````

You input these five values:

``````map(value, fromLow, fromHigh, toLow, toHigh)
``````
• `value` is the X value you want to resize
• `fromLow` and `fromHigh` is the range that X is currently in
• `toLow` and `toHigh` is the range that you want to scale X to
• The question wanted to know what the "150 to 240" means so, no, this isn't the answer. – Rob Dec 23 '15 at 21:07