Help with Leonardo & Rotary Optical Encoder

I would suggest moving the encoder to pins 2 and 3 and using the pin-change interrupts to detect all transitions. Your current code will fail if the encoder moves faster than your main loop, which means you can never use delay ().

As for the rotary switch, I'm assuming it's a 1-pole, 4-throw? I would put a different value of resistor on each leg so that it forms a variable voltage divider. You can then measure the voltage at the common pin, which will tell you where the switch is. For example:

  • 10k from common to VCC
  • common connects to any analog pin, eg A1
  • 0R from A to ground
  • 3k3 from B to ground
  • 10k from C to ground
  • 30k from D to ground.

That should give you readings of about 0, 250, 500 and 750 for switch positions A, B, C and D respectively; over 1000 when the knob is between settings.