74HC165N - ShiftIn()

Hi everyone. I am trying to read data from a SN74HC165N shift register connected to an arduino.
I am using pull down resistors and correctly connected the 74HC165 as:

  • Vcc to +5v
  • Clock_INH to GND
  • Q7 to Arduino pin 4
  • GND to GND
  • SH/LD to Arduino pin 2
  • Clock to Arduino pin 3

I am having issues with the ShiftIn() function called as in my sketch:

const int PL = 2;   // Parallel Load
const int CLK = 3;  // Clock
const int DATA = 4; // Data Output

void setup() {
  Serial.begin(115200);
  pinMode(PL, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(DATA, INPUT);
}

void loop() {
  digitalWrite(PL, LOW);
  delayMicroseconds(5);
  digitalWrite(PL, HIGH);

  byte buttons = shiftIn(DATA, CLK, MSBFIRST); 

  Serial.print("State: ");
  for (int i = 0; i < 8; i++) {
    Serial.print((buttons >> i) & 1); 
    Serial.print(" ");
  }
  Serial.println();
  delay(100);
}

with the output being

State: 0 0 0 0 0 0 0 1

when pressing the button connected to pin D6 on the shift register.

If I use this script, which calls the digitalRead() function, everything works fine:

const int dataPin = 4;   /* Q7 */
const int clockPin = 3;  /* CP */
const int latchPin = 2;  /* PL */

const int numBits = 8;   /* Set to 8 * number of shift registers */

void setup() {
  Serial.begin(115200);
  pinMode(dataPin, INPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
}

void loop() {
  // Step 1: Sample
  digitalWrite(latchPin, LOW);
  digitalWrite(latchPin, HIGH);

  // Step 2: Shift
  Serial.print("Bits: ");
  for (int i = 0; i < numBits; i++) {
    int bit = digitalRead(dataPin);
    if (bit == HIGH) {
      Serial.print("1");
    } else {
      Serial.print("0");
    }
    digitalWrite(clockPin, HIGH); // Shift out the next bit
    digitalWrite(clockPin, LOW);
  }

  Serial.println();
  delay(1000);
}

Can you please tell me why I am not able to read the D7 pin using the shiftIn function? It looks like it is shifted by one bit!

thanks a lot!

1 Like

If you read the docs for shiftIn():
https://docs.arduino.cc/language-reference/en/functions/advanced-io/shiftIn/

For each bit, the clock pin is pulled high, the next bit is read from the data line, and then the clock pin is taken low.

which is not the same as your other code. That reads a bit, then pulses the clock high/low.

Does this print before shifting the variable, or after?

This is the doc page for the part in the wokwi simulator

at the bottom of the page are links to complete working examples you can study for code and wiring.

HTH

a7

Thanks for the answer! So I need to pull the clock pin low before calling the shiftIn()?

Thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.