/*

Author: GC1CEO
DateL 10/24/2024

The 74HC165 PISO Shift Register takes in eight inputs -- in this case each of them
is a motion sensor. Since it's doubtful all eight motion sensors would be in precisely
the same location I'd created an array of eight fictional locations to match to each
motion sensor. When a motion sensor detects motion it'll broadcast that to the Serial
Monitor along with its location, it'll remove itself from that list once it no longer
detects motion, and there'll be an all clear message once no motion detectors are
active.

The shift register takes in the off/on state of all 8 motion sensors at once and
sends them as serial data to the Nano. There is also a reset button that resets
the eight states -- something I threw in because sometimes the motion condition
sticks.

*/

const int dataPin = 2;   /* Q7 */
const int clockPin = 3;  /* CP */
const int latchPin = 4;  /* PL */
const int cePin = 5; /* CE */
const int resetPin = 6; /* RESET BUTOON */

byte incomingBits;
byte prevBits;
String mdLocs[8] = {"Hallway A", "Hallway B", "Hallway C", "Hallway D", "Room A", 
"Room B", "Room C", "Room D"};

 
void setup() {
  Serial.begin(9600);
  pinMode(dataPin, INPUT_PULLUP);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(cePin, OUTPUT);
  pinMode(resetPin, INPUT);
  digitalWrite(cePin, LOW);
}
 
void loop() {

if(digitalRead(resetPin) == HIGH) {
  incomingBits = 0x00;
  prevBits = 0x00;
  Serial.println("Resetting system.");
  delay(1000);
}  

digitalWrite(latchPin, LOW);
digitalWrite(latchPin, HIGH);

digitalWrite(clockPin, HIGH);
digitalWrite(cePin, LOW);
incomingBits = shiftIn(dataPin, clockPin, LSBFIRST);

digitalWrite(cePin, HIGH);

if(incomingBits != prevBits & incomingBits != 0x00) {
Serial.println("Motion Detected: ");
for(int i = 0; i < 8;i++) {
//Serial.print(bitRead(incomingBits,i), BIN);
  if(bitRead(incomingBits, i)) {
    Serial.println(mdLocs[i]);
  }
} }
if(prevBits != incomingBits & incomingBits == 0x00){
  Serial.println("ALL CLEAR!");
  Serial.println();
}

prevBits = incomingBits;

delay(100);


}

$abcdeabcde151015202530fghijfghij
$abcdeabcde151015202530354045505560fghijfghij
74HC165