/*
74HC165 Shift register input with buttons example
https://wokwi.com/projects/461142583144035329
AnonEngineering 4/26
*/
const int DATA_PIN = 2; // data out (Q7)
const int CLK_PIN = 3; // clock (CP)
const int LATCH_PIN = 4; // latch (PL)
const int NUM_BITS = 8; // set to 8 * number of shift registers
int oldResult = 0;
void printBits(byte data) {
Serial.print(" Bits: ");
for (int i = 7; i >= 0; i--) {
Serial.print(bitRead(data, i));
}
//Serial.println();
}
void setup() {
Serial.begin(115200);
pinMode(DATA_PIN, INPUT);
pinMode(CLK_PIN, OUTPUT);
pinMode(LATCH_PIN, OUTPUT);
}
void loop() {
int result = 0;
int btnNumber = 0;
// latch inputs
digitalWrite(LATCH_PIN, LOW);
digitalWrite(LATCH_PIN, HIGH);
// shift bits
for (int i = 0; i < NUM_BITS; i++) {
int bit = digitalRead(DATA_PIN);
result += bit << i;
digitalWrite(CLK_PIN, HIGH); // Shift out the next bit
digitalWrite(CLK_PIN, LOW);
}
// show results if changed (and not 0)
if (result != oldResult && result != 0) {
oldResult = result;
for (int i = 0; i < 8; i++) {
if (bitRead(result, i) == HIGH) {
btnNumber = 8 - i;
}
}
Serial.print("Button: ");
Serial.print(btnNumber);
printBits(result);
Serial.print(" Decimal: ");
Serial.println(result);
}
//delay(1000);
}MSB
LSB