 # Need help on the map() function

I get the idea on how the map function work but just want to check can i use it in the way i did in the code below

``````int logValue=0;
int val;
float a;

void setup() {
Serial.begin(9600);

pinMode(A11, INPUT); //analog
}

void loop() {

logValue= analogRead(A11);

val = map(logValue, 0, 1023, 1, 1024);
a = val/1024;
Serial.println(a);
Serial.println(val);
Serial.println(logValue);
delay(1000);
}
``````

The main thing is i need the constant a to be able to show the value of the formula val/1024. Because currently what i see on the serial monitor is 0 when the analog read is at 0 and 1 when the read is at 1023.

If it doesnt work and there is a simpler way to do what i need the suggestion is appreciated :D

As you probably know the code you posted does not compile.

If/when you get it to compile then as written the variable a will not be a float after the calculation.

Change

``````  a = val/1024;
``````

to

``````  a = val/1024.0;
``````

to prevent integer calculation taking place.

Or just go with integer calculation instead. Faster, smaller, no rounding etc Try:

``````val = logValue + 1;
``````
``````  val = map(logValue, 0, 1023, 1, 1024);
``````

Since the range values are all integer values, this will NOT be the same as val = logValue + 1. What, exactly, are you trying to do?

That would be my question. What is it that you need? You never really said. Your code is broken so it’s a bad idea to try to guess from that.

@UKHeliBob Thanks for the suggestion it actually did what i wanted it to do!

And also just so to say it actually complies, should i be concerned?

What i actually wanted it to do is to get a percentageish value like 0.15 or something.

For example my analog read is 900 and so the map makes it 901(this is just a test) so if it puts that into the variable 'val' it would go like this a=901/1024 and the value of a should be like 0.87 .

But when i did it with my code(somehow it compiled), it would only show 0 in this case (and every other analog read) the only time it shows a value is when the analog read is 1023 and that only shows the value of 1.

So i thought it was the map function that was causing the problem

If you want an integer percentage:

``````int percent = map(value, 0, 1023, 0, 100);
``````

If you want a decimal fraction from 0.0 to 1.0:

``````float fraction = value/1023.0;
``````

@johnwasser Oh yeah i could have done that! Thanks for the suggestion!