Encoding a rotary switch to save inputs


I imagine the following concepts are pretty straightforward for many builders, but probably not for all, so you will find here how to reduce drastically the number of inputs required to read a multi position rotary switch. The principle is to encode the position in binary. To illustrate the advantage of doing this, here are a few examples of the number of inputs required versus the number of positions used on the switch :

Number of positionsinputs required
12 (and up to 16)4
inputs versus switch positions with binary encoding

So, how to to this in practice ? well, using simple diodes. You can buy some for a few cents, any type will do, but the very common 1N4148 type is particularly suited, and inexpensive. A bit of wiring is required to link your switch pins to your inputs through the diodes. The following schematics illustrate the concept for a common 12 position switch :

If you need less than 12 positions, then just skip the portion corresponding to the excess positions. On the left, the rotary switch can connect the ground connection (0V) to any one single position selected, the on the right part, the connections labeled bit0 to bit4 have to be connected to your input card and they will represent the number of the activated switch position in binary. An activated input is set to 0, while a non activated input is set to 1. This requires that all input are set to 1 by the input card : for example, using an arduino board or similar, you have to configure the input with a PULL_UP activated, to set the input to 1 when not activated (on arduino : pinMode(pin, INPUT_PULLUP), where pin is the card input number). Then you read the different pins, invert their value (input = 1 – input) and read the position by : position = input0 + 2 * input1 + 4*input2 + 8*input3 …

This entry was posted in Tech Tips. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *