I am investigating the use of a 3-position-switch for one of my projects to switch between different settings using just one analog input pin. For the three positions I am using ground/0V, ~2.5V (via 2x10k voltage divider) and full 5V. I am doing this also because I am planning to use a 5-position rotary switch in a similar way in the future.
Due to tolerances and noise, the readings on the analog pin are not precisely 0, 511, 1023, but rather 0-1, 509-512 and 1021-1023. To take this into account, I am using the map
function like this:
const byte alarmSwitchPin = A0;
int alrmSwState;
byte alrmSet;
byte alrmPrevSet;
void setup() {
Serial.begin(9600);
pinMode(alarmSwitchPin, INPUT);
}
void loop() {
alrmSwState = analogRead(alarmSwitchPin); // Read input
byte alrmSet = map(alrmSwState, 0, 1023, 0, 2); // Boil input down to three cases
if (alrmSet != alrmPrevSet) { // Only if state of switch has changed
switch (alrmSet) {
case 0:
Serial.println("Low");
break;
case 1:
Serial.println("Medium");
break;
case 2:
Serial.println("High");
break;
}
alrmPrevSet = alrmSet;
delay(200); // For testing purposes
}
}
I only want the setting to change (or, in this case, the console to print) when the state has actually changed. This does not work, though, because the map
function is doing its math in integer, which fails in mapping the High position (in this case).
What are my options if I want to stick with the switch
method? I am curious if it is possible to get this done without if
statements and conditions or, as a more general question, what the best option is to properly map the 10 bit analog input to just 3 cases/numbers.
PS: I thought analogReadResolution()
might be an option but I am working with Arduino UNO where this is unavailable.