//By NMD weerasinghe COTMD
// To demonstrate Serial In Parallel Out (SIPO) Shift Register and
// Parallel in Serial Out (PISO) Shift Registor 

#define ClkDelay 500 //delay in milliseconds of each half of clock pulse
#define ClockPin 2
#define SerialDataPin 3
#define LatchPin 4
#define PISOClkEn 5 // Piso Clock enable active low
#define PISOPrllLoad 6 // PISO Parallel Load active Low
#define Maxbit 7
#define printEnable 0 // if 1 enable Serial print debug details
#define SOplotEnable 0 // // if 1 enable Serial print of Q7(SO) for serial plot
#define serialOutputRead 10 // read PISO output to draw graph

void sendSerialdata(int fpattern, bool order);
void sendClockpulse(int NoOfPulse);
void printOutput();
void LoadSIPOandRun();

int pattern = 0b10101010;
int mask = 0b0000001;
//int SerialOut;
//int Maxbit = 7;




void setup() {

pinMode(serialOutputRead, INPUT);
pinMode(ClockPin, OUTPUT);
pinMode(SerialDataPin, OUTPUT);
pinMode(LatchPin, OUTPUT);
pinMode(PISOClkEn, OUTPUT);
pinMode(PISOPrllLoad, OUTPUT);

if(SOplotEnable) Serial.begin(9600);
if(printEnable) Serial.begin(9600);
delay(1000);
digitalWrite(ClockPin,LOW); // clock pin to low initially
digitalWrite(PISOClkEn,HIGH); // disable SIPO clock pin  initially
digitalWrite(PISOPrllLoad,HIGH);// disable SIPO parallel load pin  initially

//sendClockpulse(8);
delay(1000);
//sendSerialdata(pattern,false); // true left to right false right to left to SIPO
//delay(ClkDelay*3);
//LoadSIPOandRun();
//sendSerialdata(pattern,true); // to SIPO
//delay(ClkDelay*3);



}

void loop() {
  // put your main code here, to run repeatedly:
LoadSIPOandRun();
delay(ClkDelay*3);
}


void LoadSIPOandRun()
{
    
    digitalWrite(PISOPrllLoad,LOW);// enable SIPO parallel load pin
    delay(ClkDelay*2);
    digitalWrite(PISOPrllLoad,HIGH);// disable SIPO parallel load pin
    delay(100);
    digitalWrite(PISOClkEn,LOW); // enable SIPO clock pin
    sendClockpulse(Maxbit);
    digitalWrite(PISOClkEn,HIGH); // disable SIPO clock pin
    //digitalWrite(PISOPrllLoad,HIGH);// disable SIPO parallel load pin

}

void sendClockpulse(int NoOfPulse)
{
  //Serial.println("Entclockpulse");
  for (int i = 0 ; i < NoOfPulse; i++)
  {
       // Serial.println(digitalRead(serialOutputRead));
        //printOutput();
        //Serial.println(digitalRead(serialOutputRead)); // serial print Q7 for graph

        digitalWrite(ClockPin,HIGH);
        printOutput();
        delay(ClkDelay);
        digitalWrite(ClockPin,LOW);
        printOutput();
        delay(ClkDelay);
  }

}

void printOutput()
{
  if(SOplotEnable) 
  {
    Serial.println(digitalRead(serialOutputRead));
  }
}

74HC165