Giovanni Carrera Runs a Four-Switch DIP Switch From Just One Analog Input on Any Arduino
Using a series of resistors, Carrera's technique allows for a four DIP switch component on just one analog input — or eight on two.
Giovanni Carrera has published a guide to reading a quad DIP switch — four switches with two positions each, giving a total of 16 possible positions — on any Arduino-compatible microcontroller using just a single analog pin.
"Normally the DIP switches require as many digital input pins as there are DIP switches used and also with pull-up resistors enabled," Carrera explains of the issue in using DIP switches on resource-constrained microcontrollers. "In the proposed circuit I use only one analog input for four dip switches. This article is also particularly useful for applications with ESP8266 which has few I/O pins but has an analog input with a full-scale of 1V."
Based on an earlier project reading a 4x3 keypad with three analog inputs, the technique works by placing five resistors into the circuit: Each resistor has roughly double the value of the last, causing a predictable voltage drop depending on which switches are in which position.
Having simulated the circuit first, Carrera found the resistor values that would work for the 16 possible states of the four-switch DIP switch - two states per switch, ranging from all-off to all-on — and wrote an Arduino sketch demonstrating the functionality. "In this example I use Arduino Uno's pin A0 as an analog input," he writes, "and in the setup I insert the analogReference (INTERNAL)
instruction to set the internal Vref at 1.1V, more stable and less noisy than the default at 5V."
Carrera's circuit design, sketch, and more information can be found on the ArduPicLab blog; Carrera has also indicated that the same approach can be used for an eight DIP switch circuit, by using a second analog input pin.