quesetion about interfacing with rotary switch

Just thought of another way to do what you are after last night. Put 1K resistors between each of the pins, with the last connected to ground and the last on the other end connected to +5V. Then take the common and connect it to an analogue input and read the voltage.

This is a great technique. Only one pin required regardless of the number of stops. Here's a C++ fragment to decode the analog pin value into an integer switch stop number without the need for calibration or hardcoding stop values :slight_smile:

class RotarySwitchImpl
{
private:
      int _analogPin;
      int _numberOfStops;
      
public:
      void setup(int analogPin_,int numberOfStops_);
      int readPosition();
};
void RotarySwitchImpl::setup(int analogPin_,int numberOfStops_)
{
      _analogPin=analogPin_;
      _numberOfStops=numberOfStops_;
}


int RotarySwitchImpl::readPosition()
{
      int idealStep,value,i,nearestStop,diff,nearestDiff;

      value=analogRead(_analogPin);
      idealStep=1024/(_numberOfStops-1);

      for(i=0;i<_numberOfStops;i++)
      {
            diff=abs(value-i*idealStep);
            if(i==0 || diff<nearestDiff)
            {
                  nearestDiff=diff;
                  nearestStop=i;
            }
      }

      return nearestStop;
}