I am using the Grove - Slide Potentiometer (http://wiki.seeedstudio.com/Grove-Slide_Potentiometer). How can I set the potValue so that at maximum it will 128?
int potPin= A0;
int readValue;
int potValue;
void setup() {
pinMode(potPin, INPUT);
Serial.begin(9600);
}
void loop() {
readValue = analogRead(potPin);
potValue = (255./500.) * readValue;
Serial.print("You are writing a value of ");
Serial.println(potValue);
}
2 Answers 2
You can use the map
function, see https://www.arduino.cc/reference/en/language/functions/math/map/.
Example: If your pot meter gives values from 100 to 1000 and you want to map that range to a range of 0 to 128 you can easily write:
potValue = map(readValue, 100, 1000, 0, 128);
High likely, in your case and if the potentiometer is 'perfect' it returns values from 0 to 1023 and you can write:
potValue = map(readValue, 0, 1023, 0, 128);
-
with potValue = map(readValue, 0, 1023, 0, 128); I get the max value of 186.dkin– dkin2020年01月21日 16:21:20 +00:00Commented Jan 21, 2020 at 16:21
-
What is the maximum raw value you get? ... you can increase the value of 1023 to assume a higher maximum (set it to the maximum value you get from the pot).Michel Keijzers– Michel Keijzers2020年01月21日 16:22:40 +00:00Commented Jan 21, 2020 at 16:22
-
the mx. value of readValue is 728dkin– dkin2020年01月21日 16:25:23 +00:00Commented Jan 21, 2020 at 16:25
-
According to the documentation, map(728, 0, 1023, 0, 128) should be something like 91. (728/1023*128). If you would use map(value, 0, 728, 0, 128) you should get values upto 128.Michel Keijzers– Michel Keijzers2020年01月21日 16:26:57 +00:00Commented Jan 21, 2020 at 16:26
-
Consider that map is using integer arithmetics (truncating). To get evenly spaced areas, you'd rather
map (readValue,0,1024, 0,129);
( Will transform 0..1023 to 0..128 and everything > 1016 will show 128) If this is really what you want.DataFiddler– DataFiddler2020年01月22日 14:45:34 +00:00Commented Jan 22, 2020 at 14:45
analogRead() returns 0x0000 to 0x03ff
If the max data 0x03ff is shifted to the right by 3 bits (or divide by 8), then 0x03ff becomes 0x007f, or 127.
I think this will do it:
desiredMax = analogRead(A0) >> 3; // divide 1023 max by 8, becomes 127 max
-
fast and simple, but less readable. +1dandavis– dandavis2020年01月21日 21:23:39 +00:00Commented Jan 21, 2020 at 21:23
-
Less readable? // add a comment to the lineCrossRoads– CrossRoads2020年01月22日 12:37:22 +00:00Commented Jan 22, 2020 at 12:37
-
1No need for (less readable) bitshifting - dividing by 8 yields the same compiled code as the right shifts (godbolt.org/z/V82L6Z)towe– towe2020年01月22日 14:29:41 +00:00Commented Jan 22, 2020 at 14:29