
I needed an easy way to select a model among 10 for my Arduino-based RC transmitter.
I used this kind of switch, widely available on Ebay:
Between each contact, I soldered a 1kΩ resistor to make the switch act as a fixed-steps 10kΩ potentiometer.
The cursor of the switch is connected to an analog input of the Arduino, and its position is computed with this simple code:
// Read the position of the rotary switch
// return value: [0, ROTARY_SWITCH_STEPS]
#define ROTARY_SWITCH_PIN A6
#define ROTARY_SWITCH_STEPS 10
byte read_rotary_switch() {
byte retval_byt = 0;
const unsigned int step_int = 1024 / ROTARY_SWITCH_STEPS;
const unsigned int offset_int = step_int / 2;
unsigned int limit_int = offset_int;
unsigned int sample_int = analogRead(ROTARY_SWITCH_PIN) & 0xFFF8; // filter noise: ignore least significant 3 bits
while (sample_int > limit_int) {
retval_byt++;
limit_int += step_int;
}
return retval_byt;
}
There is no debouncing in this code. If you need it, you'll find a more sophisticated version of this function in the RC transmitter source code.
Page last modified on February 03, 2015, at 08:39 am
Powered by
PmWiki