74hc165 works crazy

Hi, guys. First time i’m trying to use input shift register IN74HC165AN

I Plugged it to ARDUINO and use this code

#include <SPI.h>

enum { REG_LATCH = 8 };


void setup()
{
  Serial.begin(9600);
  SPI.begin();

  pinMode(REG_LATCH, OUTPUT);
  digitalWrite(REG_LATCH, HIGH);
}


void loop()
{
  static uint8_t last_input_states = 0;

  digitalWrite(REG_LATCH, LOW);
  digitalWrite(REG_LATCH, HIGH);

  uint8_t states = SPI.transfer(0);

 
  if (states != last_input_states)
  {
 
    uint8_t changed = states ^ last_input_states;
    last_input_states = states; // ?????????? ??????? ?????????

    for (int i = 0; i < 8; ++i)
    {
      if (changed & 1) // ???? ????????? ?????? ??????????…
      {
        Serial.print("#");
        Serial.print(i); // ???? ????? ??????
        Serial.print(" -> ");
        Serial.println(states & 1); // … ? ????? ?????????
      }
      changed >>= 1;
      states >>= 1;
    }
  }
}

The problem is - in serial port i see every millsecond changes! The data randomly changes. But! I do not even plag any buttons! Why data is changing?

If that is your actual schematics, then your inputs are floating.
Use pull up resistors or pull down resistors (whatever suits your needs).

Thank you! But, where i should connect them?

To the floating inputs! Try 10k resistors - if the resistor goes to GND, have the push-button go
to 5V (or vice versa).

CMOS inputs have infinite input resistance (almost, 10^10 ohms or so) and will pickup
any nearby signals via stray capacitance if left "floating".

I plugged this way but it still send random data& ((((