8 years, 9 months ago.

How can we use map() function

How can we use map() function like arduino map function as double temperature = map(analogRead(pSENSOR), 0, 1023, 0, 100);

why i get this error when trying to use it?

"Error: Return value type does not match the function type in "cuba.cpp", Line: 30, Col: 15"

posted by Khananard Khamphan 12 May 2017

2 Answers

8 years, 9 months ago.

As Kamil said, the mbed analog in defaults to giving a value between 0 and 1, you can normally convert this to whatever range you need with a single multiplication or worst case an addition and a multiplication.

However if you want something generic to make it easier to port code the following should emulate the behavior of the map function:

float map(float in, float inMin, float inMax, float outMin, float outMax) {
  // check it's within the range
  if (inMin<inMax) { 
    if (in <= inMin) 
      return outMin;
    if (in >= inMax)
      return outMax;
  } else {  // cope with input range being backwards.
    if (in >= inMin) 
      return outMin;
    if (in <= inMax)
      return outMax;
  }
  // calculate how far into the range we are
  float scale = (in-inMin)/(inMax-inMin);
  // calculate the output.
  return outMin + scale*(outMax-outMin);
}

Also going by the range in your question you have a 10 bit ADC, using a double rather than a float in that situation is completely pointless and only serves to slow the code down. On most mbeds a float multiply will take about 30 clock cyles, using doubles it will be over 100.

EDIT: Code changed to speed up range checking when inMin is more than inMax (a valid but weird use case going by the arduino documentation).

Accepted Answer

This is what Arduino uses:

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;
}

long = 32-bit integer iirc.

posted by Erik - 08 Jul 2015

I think that works out to be identical to the last two lines of my code only with integers rather than floats. At least I hope it does.

No reason you couldn't overload it and have both integer and float versions.

The rest of my the code was range checking so that the output was always between out_min and out_max. The arduino code would allow out of range outputs if the input was also out of range, it makes for simpler code but if a function tells me the output will be between two values and then in some situations can output a value outside of that range I would consider it a bug.

Thinking about it it would be quicker to do the checking differently if the input range is backwards rather than swap the values around in that situation.

posted by Andy A 08 Jul 2015

how to read the data from this and display it on lcd?

posted by Khananard Khamphan 12 May 2017
8 years, 9 months ago.

I think standart analogread function of mbed already does it, but between 0 and 1... With some mathematics you can use it for your needs..