Read eight switches through three pins (74HC165)
A 74HC165 shift register reads a DIP switch's eight positions into one byte, three pins in total.
Logic · Intermediate
In a real product: Arcade cabinet (Consumer electronics): A shift register reads many buttons with three pins.
The 74HC165 is the 595's opposite: it reads eight inputs at once and hands them to the board one bit at a time. It is how keyboards, arcade panels and control desks read dozens of buttons without dozens of pins.
What you'll learn
- Loading a parallel-in shift register and clocking its bits out
- Assembling a byte from bits, and printing it in binary
- Reacting only when the inputs change
How it works
Pulling PL (parallel load) LOW copies the eight inputs D0 to D7 into the chip. With PL back HIGH, Q7 already shows D7. readInputs() reads Q7, then pulses CP (the clock), which moves the register one place towards Q7, so the next read gets D6, and so on down to D0. Reading before each clock pulse matters: Arduino's shiftIn() raises the clock first and would miss D7.
The DIP switch's top pins (1a to 8a) go to 5V and its bottom pins to D0 to D7, so a switch that is on puts 5V on its input. CE (clock enable) is tied to GND so the clock always works.
On real hardware each input also needs a pull-down resistor (10 kΩ to GND, or one resistor network) so an open switch reads a firm LOW. The simulator reads an unconnected input as LOW.
Try this
- Click the switches while it runs: each change prints a new line.
- Use the byte: light the Uno's LED (pin 13) when switch 1 is on, with
bitRead(value, 0). - Chain a second 74HC165 (its Q7 to the first one's DS) and read 16 switches with 16 clock pulses.
sketch.ino
// A 74HC165 reads a DIP switch's eight positions; the board prints the byte whenever it changes.
const int LOAD = 8; // to PL: LOW copies the inputs in
const int CLOCK = 12; // to CP
const int DATA = 11; // from Q7
byte readInputs() {
digitalWrite(LOAD, LOW);
delayMicroseconds(5);
digitalWrite(LOAD, HIGH);
byte value = 0;
for (int i = 7; i >= 0; i--) { // D7 comes out first
if (digitalRead(DATA)) value |= 1 << i;
digitalWrite(CLOCK, HIGH);
digitalWrite(CLOCK, LOW);
}
return value;
}
int last = -1;
void setup() {
Serial.begin(9600);
pinMode(LOAD, OUTPUT);
pinMode(CLOCK, OUTPUT);
pinMode(DATA, INPUT);
digitalWrite(LOAD, HIGH);
}
void loop() {
byte value = readInputs();
if (value != last) {
Serial.print("switches 8..1: ");
for (int i = 7; i >= 0; i--) Serial.print(bitRead(value, i));
Serial.print(" = ");
Serial.println(value);
last = value;
}
delay(50);
}