How can I map an analogue input to 0-100?
You pretty much answered your own question: use the map command.
so val=map(val, 0, 1023, 0, 100)?
Unless you also need to keep the original value, in which case map val to say mappedVal or something and have both.
I dislike the map() function because it hides some of the pitfalls. My preference is for doing the calculation. For example
int val = analogRead(0);
int volts = map(val, 0, 1023, 0, 5);
int mV = volts *1000;
will give rubbish results because you lost precision with the map() function - volts is an integer.
@arduino10134 Installation and Troubleshooting is for Problems with the Arduino itself NOT your project. It says so in the description of the section. Therefore I have moved your post here. Please be more careful where you post in future.
You may want to read this before you proceed:-
how to get the best out of this forum
Why is that addressed to me? I'm not the OP, that was arduino10134.
Sorry, my bad. Corrected now.
float percentVal = analogRead(0) * 0.0977517;
Only gives 0-99 on my Uno
0-99 is evenly spaced (about 10 A/D values), but 99-100 is not (one A/D value).
This would be better.
val = map(val, 0, 1024, 0, 101); // 0-100 with even spacing
If the values come from a pot, then try this sketch.
Leo..
// converts the position of a 10k lin(B) pot to 0-100%
// pot connected to A0, 5volt and ground
int rawValue;
int oldValue;
byte potPercentage;
byte oldPercentage = 101;
void setup() {
Serial.begin(9600);
}
void loop() {
// rawValue = analogRead(A0); // add dummy read, if needed
rawValue = analogRead(A0); // read pot
// ignore bad hop-on region of a pot by removing 8 values at both extremes
rawValue = constrain(rawValue, 8, 1015);
// add some deadband
if (rawValue < (oldValue - 4) || rawValue > (oldValue + 4)) {
oldValue = rawValue;
// convert to percentage
potPercentage = map(oldValue, 8, 1008, 0, 100);
// Only print if %value changes
if (oldPercentage != potPercentage) {
Serial.print("Pot is: ");
Serial.print(potPercentage);
Serial.println(" %");
oldPercentage = potPercentage;
}
}
}
My Uno and WOKWi Uno gives 100.00 max ...
void setup() {
Serial.begin(115200);
float percentVal = 1023 * 0.0977517; // max reading
Serial.println(percentVal);
}
I think I left the variable declared as int during experimenting.
That... of course results in 99.
Leo..
i would use
void setup() {
Serial.begin(115200);
//uint16_t rawValue = analogRead(A0); // read pots
uint16_t rawValue = 512; // simulate any value
uint16_t val = rawValue * 100L / 1024;
Serial.println(val);
}
void loop() {
// put your main code here, to run repeatedly:
}
or if you really insist on 0..100
uint16_t val = rawValue * 101L / 1024;
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.