#include <SPI.h>

uint8_t rec_buffer_1 = 0xff;
uint8_t rec_buffer_2 = 0xff;
uint8_t pre_rec_buffer_1 = 0xff;
uint8_t pre_rec_buffer_2 = 0xff;

void setup() {
  Serial.begin(115200);
  pinMode(SS, OUTPUT);
  pinMode(SCK, OUTPUT);
  pinMode(MISO, INPUT);
  SPI.begin();
  SPI.setDataMode(SPI_MODE3);
  //SPI.setBitOrder(LSBFIRST);
  //delay(200);
  Serial.println("Let's Start!");
}

void loop() {
  uint32_t start_time = micros();
  digitalWrite(SS, LOW);
  digitalWrite(SCK, HIGH);
  digitalWrite(SS, HIGH);

  rec_buffer_1 = SPI.transfer(0x00);
  rec_buffer_2 = SPI.transfer(0x00);

  if (rec_buffer_1 != pre_rec_buffer_1){
    uint8_t button_1 = rec_buffer_1 ^ pre_rec_buffer_1;
    pre_rec_buffer_1 = rec_buffer_1;
    for (uint8_t i = 0; i < 8; i++){
      if (button_1 & (1 << i)) {
        Serial.print("button: ");
        Serial.print(i + 8);
        Serial.println(pre_rec_buffer_1 & (1 << i) ? " is released." : " is pressed");
      }
    }
  }
  if (rec_buffer_2 != pre_rec_buffer_2){
    uint8_t button_2 = rec_buffer_2 ^ pre_rec_buffer_2;
    pre_rec_buffer_2 = rec_buffer_2;
    for (uint8_t ii = 0; ii < 8; ii++){
      if (button_2 & (1 << ii)) {
        Serial.print("button: ");
        Serial.print(ii);
        Serial.println(pre_rec_buffer_2 & (1 << ii) ? " is released." : " is pressed");
      }
    }
  }
  delay(10);
  /*
  uint32_t end_time = micros();
  Serial.print(start_time);Serial.println(" was started.");
  Serial.print(end_time);Serial.println(" was ended.");
  Serial.println("----------------");
  */
}
74HC165
74HC165