I'd like to know if there is a function or some way to define min and max value to potentiometer, for example: I'm using a mechanical part that only tour the potentiometer a little bit, what means the potentiometer doesn't start in the beginning and doesn't finish in the end. So, how can I make this space the potentiometer tour means 0 to 255 the start to end, respectively?
3 Answers 3
You cannot declare that the min
and max
values of a potentiometer are x
and y
. What you can do is map()
the values of the potentiometer to your own desired scale.
To do this, you'll have to get the following values:
- Minimum value of the potentiometer,
pMin
- Maximum value of the potentiometer,
pMax
But these values aren't what you want. For example, what you want is pmin
to be 0
and pMax
to be 100
. So, you'll have to scale pMin
and pMax
to those values.
For this, you use the map()
function. What map()
does is changing the value in a given scale, to that of another scale. Let's get some example code:
int pMin = 14; //the lowest value that comes out of the potentiometer
int pMax = 948; //the highest value that comes out of the potentiometer.
int x = 0; //we will use this value to store the readings of the potentiometer
void setup(){
Serial.begin(9600); //Serial monitor can be used to check the values
}
void loop(){
x = analogRead(A0); //connect the potentiometer to the A0 pin of the Arduino
Serial.print(x); //prints the original reading
x = map(x, pMin, pMax, 0, 100) //take the value of x, compared it to the scale of the potentiometer pMin to pMax, and translate that value to the scale of 0 to 100
Serial.print("\t"); //a tab to make the reading more easy
Serial.println(x); //post mapped value, println is a linebreak as well
delay(100); //so we don't post to much in the serial and you can read data better.
}
With this example you can clearly see how your potentiometer behaves and how you can use the 'weird' values from its readings in a useful way for your projects.
-
You can even make it auto-calibrating. In the loop, if (x > pMax) { pmax = x ), and vice versa for pMin. But then the user would have to twiddle the pot every time the device starts, unless you save the min and max to eeprom.Dampmaskin– Dampmaskin07/15/2016 10:50:57Commented Jul 15, 2016 at 10:50
Either use a reference voltage closer to the maximum voltage the potentiometer is capable of, or use map()
to map the existing limited range to a larger range. Note that using map()
will not improve precision.
If the values from the pot are 0 - 1023 you can divide the number by 4 which would give you a closer range to what you need. The map() function can be used instead.
Explore related questions
See similar questions with these tags.