# Map function returning incorrect value

I am trying to create a program to control a variable speed refrigeration compressor based on temperature. The part I am stuck at is on the map function. It should return a value between 0 and 255 but instead 1147 comes out. What is meant to happen is when the temperature is 5 degrees c the compressor is at full speed and when it is at 0 degrees the compressor runs at the slowest speed.

``````  float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
compspeed = map(tempC, 1, 5, 0, 255);
Serial.println();
Serial.print (compspeed);
``````

and here is the output Temp C: 19.06 1147

You tell map that the range of tempC is 0 to 5. Then you give it 19.

Skip the map. You need if conditions to tell it what to do outside of 0-5 degC.

Map doesn't work with floats, here's one idea.

`````` float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
int dtempC = tempC * 10;
dtempC = constrain(dtempC,10,50;
compspeed = map(dtempC, 10, 50, 0, 255);
Serial.println();
Serial.print (compspeed);
``````

Also, compressor may not be able to start with too low PWM, think I would start with compspeed = map(dtempC, 10, 50, 64, 255);

You could use floats in map with a little change to the map formula, but your way skips the hassle. Well, I should say you can create a map that does work with floats, as it's a simple formula anyway.

Over my ol' head :confused: but tnx for the tip.

edgemoron: Map doesn't work with floats, here's one idea.

`````` float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
int dtempC = tempC * 10;
dtempC = constrain(dtempC,10,50;
compspeed = map(dtempC, 10, 50, 0, 255);
Serial.println();
Serial.print (compspeed);
``````

Also, compressor may not be able to start with too low PWM, think I would start with compspeed = map(dtempC, 10, 50, 64, 255);

I stuck a frozen ready meal on top of the sensor to test and this worked perfectly! Thanks so much for your help.

Temp C: 3.75 172