Saturday, June 23, 2018

Using shiftIn with a 74165 shift register


The Arduino shiftIn function is written to be used with a CD4021.  The 74165 shift register is another inexpensive and widely available parallel-input shift register that works slightly different than the 4021.  The logic diagram of the 74HC165 is depicted in the figure above, and shows Qh is connected directly to the output of the 8th flip-flop.  This means that the state of Qh needs to be sampled before the first clock pulse.  With the 4021, the serial output is sampled after the rising edge of the clock.  This can also be determined by looking at the source for shiftIn, which sets the clock pin high before reading the serial data pin:
  for (i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST)
      digitalWrite(dataPin, !!(val & (1 << i)));
    else  
      digitalWrite(dataPin, !!(val & (1 << (7 - i))));
      
    digitalWrite(clockPin, HIGH);
    digitalWrite(clockPin, LOW);    
  }

By setting the clock pin high, setting the latch (shift/load) pin high, and then calling shiftIn, the first call to digitalWrite(clockPin, HIGH) will have no effect, since it is already high.  Here's the example code:
  // set CLK high before shiftIn so it works with 74165
  digitalWrite(CLK, HIGH);
  digitalWrite(LATCH, HIGH);
  uint8_t input = shiftIn(DATA, CLK, MSBFIRST);
  digitalWrite(LATCH, LOW);

Like much of the Arduino core, the shiftIn function was not well written.  For a functionally equivalent but faster and smaller version, have a look at MicroCore.

No comments:

Post a Comment