0

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

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 Jan 21 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 Jan 21 at 16:22
  • the mx. value of readValue is 728 – dkin Jan 21 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 Jan 21 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 Jan 22 at 14:45
3

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. +1 – dandavis Jan 21 at 21:23
  • Less readable? // add a comment to the line – CrossRoads Jan 22 at 12:37
  • 1
    No need for (less readable) bitshifting - dividing by 8 yields the same compiled code as the right shifts (godbolt.org/z/V82L6Z) – towe Jan 22 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.