// Define Connections to 74HC165
const int dataPin = 17;   /* Q7 */
const int clockPin = 16;  /* CP */
const int latchPin = 15;  /* PL */
// const int clockEnablePin = 5; // CE pin 15

byte a[8];
const int numBits = 8;   /* Set to 8 * number of shift registers */

// Define Connections to 74HC595

const int latchPinA = 26; // ST_CP pin 12
const int clockPinA = 27; // SH_CP pin 11
const int dataPinA = 25; // DS pin 14

const byte LED_A[9] = {  // 記錄0~9的七段數字
  //GFEDCBA
  B00000000,
  B10000000,
  B01000000,
  B00100000,
  B00010000,
  B00001000,
  B00000100,
  B00000010,
  B00000001
};

void setup() {
  Serial.begin(115200);
  pinMode(dataPin, INPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  digitalWrite(latchPin, HIGH);


  pinMode(latchPinA, OUTPUT);
  pinMode(clockPinA, OUTPUT);
  pinMode(dataPinA, OUTPUT);


}

void turn_on() {
    // Step 1: Sample
    digitalWrite(latchPin, LOW);
    digitalWrite(latchPin, HIGH);
    // Step 2: Shift
    // Serial.print("Bits: ");
    for (byte i = 0; i < 8; i++) {
      // byte bit = digitalRead(dataPin)<<7 ;
      a[i] = digitalRead(dataPin);
      // Serial.print(a[i]);
      digitalWrite(clockPin, HIGH); // Shift out the next bit
      digitalWrite(clockPin, LOW);
    }
  }

// void turn_on() {

//   byte val = 0;

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

// 	for (byte i = 0; i != 8; i++) {
		
// 		// if (bitOrder == LSBFIRST)
// 			// val = (val>>1) | (digitalRead(dataPin)<<7);
      
// 		// else
// 			val = (val<<1) | digitalRead(dataPin);
//       a[i]=val;
//     digitalWrite(clockPin, HIGH);
// 		digitalWrite(clockPin, LOW);
// 	}
// 	// return val;
// }

void loop() {

 turn_on();

  Serial.print(a[0]);
  Serial.print(a[1]);
  Serial.print(a[2]);
  // Serial.print(a[3]);
  // Serial.print(a[4]);
  // Serial.print(a[5]);
  // Serial.print(a[6]);
  // Serial.print(a[7]);
  Serial.println("");



  // Define Connections to 74HC595

  //  for (char j = 0; j < 8; j++) {
  // Relayonoff(1);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  Relayonoff(2);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  // Relayonoff(3);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  // Relayonoff(4);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  // Relayonoff(5);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  // Relayonoff(6);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  // Relayonoff(7);
  // delay(200);
  // Relayonoff(0);
  // delay(200);
  // Relayonoff(8);
  // delay(200);
  // Relayonoff(0);
  delay(200);
  //  }
}

void Relayonoff(char comdata) {

  digitalWrite(latchPinA, LOW);
  shiftOut(dataPinA, clockPinA, LSBFIRST, LED_A[comdata]);// 先放個位數字HH
  digitalWrite(latchPinA, HIGH);

}
74HC165
74HC595