Microcontroller-based products sometimes require rotary switches. As many microcontrollers have an onboard ADC, it is easy to replace the rotary switch with a low cost potentiometer, when a rotary switch is too expensive or unavailable.
Although digitizing a potentiometer setting to act like a switch requires only a few instructions, an immediate problem is that instabilities in value occur at the switching threshold between one value and the next due to electrical or mechanical noise. The solution is to introduce upper and lower hysteresis thresholds about each transition so that the potentiometer needs to move beyond a threshold before another switch state is validated. For every updated switch state, another pair of thresholds replaces the previous. In this manner, the hysteresis provides clean switching between states.
There are many advantages to this: one port pin vs. N port pins for a rotary switch, lower cost, easier availability, and debounced switching. A disadvantage is the loss of detent feel. An additional feature of the setpoints is that they can be at arbitrary positions, for example, to compensate for nonlinear variations in potentiometer responses.
The hysteresis is typically a few counts greater than any noise that would cause unwanted switching. A capacitor is recommended between the potentiometer wiper and ground to filter out any contact noise.
Figure 1 Replacing N-throw Switch
The algorithm is illustrated in Figure 2. Once the pot setting is digitized by the ADC, it is compared with the lower threshold, and if below, the switch state is decremented and limited to zero. If the potentiometer setting is above the upper threshold, the switch state is incremented and limited to the maximum value. If there is a change in switch state, the lower and upper threshold values are updated and the subroutine ends.
Figure 2 Flowchart
For this hysteresis algorithm to work, the potentiometer setting must be read periodically and compared to the last switch state. This is to distinguish between the potentiometer setting crossing a threshold from a different state or being at the same potentiometer setting and the same state.
For more detail: Replace a rotary switch with a potentiometer