// 74hc165  ingressi
const int REG_SL = 2; // limegreen
const int REG_CK = 3; // violet
const int REG_DI = 4; // cyan
// 74hc595 uscite
const int latchPin = 5; // limegreen
const int clockPin = 6; // violet
const int dataPin  = 7; // cyan
// 74hc165  ingressi 2
const int REG_SL2 = 8; // limegreen
const int REG_CK2 = 9; // violet
const int REG_DI2 = 10; // cyan
// 74hc595 uscite 2
const int latchPin2 = 11; // limegreen
const int clockPin2 = 12; // violet
const int dataPin2  = 13; // cyan

byte data[5];

const int pulseDelay = 2;

void setup() {
  //Serial.begin(115200);

  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  pinMode(REG_SL, OUTPUT);
  digitalWrite(REG_SL, HIGH);  // set default high
  pinMode(REG_CK, OUTPUT);     // default low
  pinMode(REG_DI, INPUT);
}

void loop() {
  // acquisizione porte d'ingresso
  digitalWrite(REG_SL, LOW);
  delay(pulseDelay);
  digitalWrite(REG_SL, HIGH);
  delay(pulseDelay);
  for(int i=4; i>=0; i--) {
    for (int j=0; j<8; j++) {
      int bit = digitalRead(REG_DI);
      bitWrite(data[i],j,bit);

      digitalWrite(REG_CK, HIGH);
      delay(pulseDelay);
      digitalWrite(REG_CK, LOW);
      delay(pulseDelay);
    }
  }
  //printData();

  digitalWrite(latchPin, LOW);
  delay(pulseDelay);
  for(int i=0; i<5; i++) {
    shiftOut(dataPin, clockPin, LSBFIRST, data[i]);
  }
  digitalWrite(latchPin, HIGH);
  delay(pulseDelay);
}
/*
// Print the 40 bits.
void printData() {
  // index of array
  for(int i=4; i>=0; i--) {
    // walk the bits
    for(int j=7; j>=0; j--) {
      int bit = bitRead(data[i],j);
      if(bit == 0)
        Serial.print("_");  // or "○"
      else
        Serial.print("#");  // or "●"
    }
    Serial.print(" ");
  }
  Serial.println();
}
*/
74HC595
74HC595
74HC595
74HC595
74HC595
74HC595
74HC595
74HC595
74HC595
74HC595
74HC165
74HC165
74HC165
74HC165
74HC165
74HC165
74HC165
74HC165
74HC165
74HC165
DS: dataPin (cyan) SHCP: clockPin (violet) STCP: latchPin (limegreen)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
1 ... 2 ... 3 ... 4 ... 5 ... 6 ... 7 ... 8 ... 9 ... 10
11 . 12 .13 . 14 . 15 .16 . 17 . 18 .19 . 20
21 . 22 .23 . 24 . 25 .26 . 27 . 28 .29 . 30
31 . 32 .33 . 34 . 35 .36 . 37 . 38 .39 . 40
RELAY 1
RELAY 40