DIP switch binary reader
Read four DIP switches as the bits of a binary number and print it in decimal.
Input · Beginner
In a real product: Industrial sensor node (Industrial): DIP switches set each node's bus address on the factory floor.
A DIP switch is a row of tiny switches, often used to set an address or a configuration on a board. Reading four of them as bits gives a number from 0 to 15.
What you'll learn
- Reading several inputs with pull-ups
- Building a number from bits with
|=and<< - Binary to decimal
How it works
Switches 1 to 4 each connect a pin (2 to 5) to GND when they are on. Their other sides are chained together and go to GND. With INPUT_PULLUP, a pin reads LOW when its switch is on.
The loop builds a number: if switch i is on, it sets bit i (value |= 1 << i). Switch 1 is the lowest bit. The diagram starts with switches 1 and 3 on, so the value is 1 + 4 = 5, printed as 0101 = 5.
Try this
- Click the switches while it runs and watch the value change.
- Use all eight switches for a value from 0 to 255.
- Show the value on a 7-segment display instead of the Serial Monitor.
sketch.ino
// Read DIP switches 1-4 (on pins 2-5, other side to GND) as a 4-bit number. On = 1.
const int PINS[4] = {2, 3, 4, 5};
int last = -1;
void setup() {
for (int i = 0; i < 4; i++) pinMode(PINS[i], INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int value = 0;
for (int i = 0; i < 4; i++) {
if (digitalRead(PINS[i]) == LOW) value |= 1 << i; // switch on pulls the pin to GND
}
if (value != last) {
last = value;
Serial.print("Switches 4-1: ");
for (int i = 3; i >= 0; i--) Serial.print(bitRead(value, i));
Serial.print(" = ");
Serial.println(value);
}
delay(50);
}