//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <LiquidCrystal_I2C.h>

byte currentButtonState = 0;
byte prevButtonState = 99; // set to diffretn number then curren to trigger update on load

// set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,4);  

void setup()
{
   // initialize the LCD
  lcd.init();

  // set pull ups
  for (int i = 0; i < 8; i++) {
    pinMode(i, INPUT_PULLUP);
  } //end for


  // Turn on the blacklight.
  lcd.backlight();


  //startTimer();
  //  DDRD = B00000000; // input
  //  PORTD = B11111111; // pullup
  //endTimerAndPrint();
  
}


void loop()
{
  // reset
  currentButtonState = 0;

  //collect state
  for (int i = 0; i < 8; i++) {
    currentButtonState |= (!digitalRead(i)) << i;
  } //end for

  //currentButtonState = ~PIND ; //read state

  // if state chnaged
  if (prevButtonState != currentButtonState) {
    //clear screen
    lcd.clear();

    // print hex
    lcd.setCursor(0, 0);
    lcd.print("0x");
    if (currentButtonState < 16) {
      lcd.print("0"); // in case we got single digit hex
    }//end if
    lcd.print(currentButtonState, HEX);

    // print binnary
    for (int i = 0; i < 8; i++) {
      lcd.setCursor((7 - i), 1);
      if (bitRead(currentButtonState, i)) {
        lcd.print("1");
      } else {
        lcd.print("0");
      } //end if
    } //end for

    // special key combination
    switch (currentButtonState) {
      case B10000001:
        lcd.noBacklight();
        break;
      case B01000010:
        lcd.backlight();
        break;

    } // end switch

  } //end if

  // set prev to current for change
  prevButtonState = currentButtonState;



  //startTimer();
  //currentButtonState = ~PIND ; //read state
  //endTimerAndPrint();
  //delay(1000);
}


void startTimer() {
  TCCR1A = 0;
  TCCR1B = bit(CS10);
  TCNT1 = 0;
}

void endTimerAndPrint() {
  unsigned int cycles = TCNT1;
  //clear screen
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Cyc: ");
  lcd.print(cycles - 1);
  lcd.setCursor(0, 1);
  lcd.print("Mic: ");
  lcd.print((float)(cycles - 1) / 16);

}