I am trying to use a pot to set a number between 1 and 3 using the code below but can only get it to read as Bay:1 on a pro micro. Any tips or is there something I am doing wrong?
#define pot1 A2
int North = 1;
int Middle = 2;
int South = 3;
int bay;
void setup() {
Serial.begin(9600);
analogRead(pot1);
}
void loop(){
if (pot1 > 0 && pot1 < 200) {
bay= North;
}
if (pot1 > 200 && pot1 < 400) {
bay = Middle;
}
if (pot1 > 400 && pot1 < 600){
bay = South;
}
Serial.println(analogRead(pot1));
Serial.print("Bay:"); Serial.println(bay);
delay(2000);
}
The map() function has a place, I assume, but it is always a good idea to check what it is (or is not!) doing for you. In particukar, map() is hard to use with small ranges on either the input or output side.
is a demo that shows that map(a2, 0, 1023, 1, 3) will return 3 only when the value being maped is 1023, whilst 1 and 2 will each enjoy being reported for 49.95 percent of the range being mapped.
So it is a bit of a challenge to get 1, 2 and 3 to share that range. I have usually rejected map() after a brief struggle. It also does cheerfully map values that are out of the input range, which is why the constrain() function is often mentioned in the same breath.
The maths of mapping are simple. But in this case, using extended case ranges as @noiasca shares is the clearest expression and the easiest to get right and/or modify. Nice when the buckets aren't all 1/Nth of the total, too.
// https://wokwi.com/projects/361085264872987649
// https://forum.arduino.cc/t/using-a-pot-to-set-a-number-between-1-and-3/1110731
void setup() {
Serial.begin(115200);
Serial.println("map function\n");
}
void loop() {
int a2 = analogRead(A2);
int m2 = map(a2, 0, 1023, 1, 3);
Serial.print(a2); Serial.print(" in, ");
Serial.print(m2); Serial.print(" out ");
Serial.println();
delay(333);
}