#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include "Duimometer.h"

/*-----( Declare Constants )-----*/
#define  LED_OFF  1
#define  LED_ON   0

// LiquidCrystal_I2C  lcd(0x27, 2, 1, 0, 4, 5, 6, 7 );
LiquidCrystal_I2C  lcd(0x20, 4, 5, 6, 0, 1, 2, 3);

/**
 Inicializaci'on del IO
 */
void initBoard(){
  lcd.begin (20, 4);  // initialize the lcd
// Switch on the backlight
//  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklightPin(7, NEGATIVE);
  lcd.setBacklight(LED_ON);

  // Reset the display
  lcd.clear();
  // setCursor (x, y)
  lcd.setCursor(7,0);
  lcd.print("ODHNER");
  lcd.setCursor(5,1);
  lcd.print("DUIMOMETER");
  lcd.setCursor(6,3);
  lcd.print("Diego Cueva C.");
  
  lcd.backlight();  //Backlight ON if under program control

  // Set the ports
  DDRD = B00000000; // Input port D
  DDRB = B00000000; // Input port B
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  pinMode(A3, OUTPUT);
  
  delay(3000);
}
/**
 Despliegue de los registros en el LCD
 */
void displayToBoard(){
  char buff[22];
  
  lcd.setCursor(10,1);
  lcd.print("          ");
  lcd.setCursor(10,3);
  lcd.print("          ");

  regAccum2UI(buff);
  lcd.setCursor(0,0);
  lcd.print(buff);

  regEnter2UI(buff);
  lcd.setCursor(0,1);
  lcd.print(buff);

  regCount2UI(buff);  
  lcd.setCursor(0,2);
  lcd.print(buff);

  arrow2UI(buff);
  lcd.setCursor(0,3);
  lcd.print(buff);
}

/**
  Recupera una tecla de los botones
 */
int getKeyFromBoard(){

    BTN_UP  =false;
    BTN_DOWN=false;

  for(int i=0; i<=9; i++){
    if(digitalRead(i) == 1){
      return debounce2(i, i+1);
    }
  }
  
  if(digitalRead(10) == 1){
      return debounce2(10, NEGAT);
  }
  if(digitalRead(11) == 1){
      return debounce2(11, POSIT);
  }
  if(digitalRead(12) == 1){
      return debounce2(12, RIGH);
  }
  if(digitalRead(13) == 1){
      return debounce2(13, LEFT);
  }
  
  if(digitalRead(A0) == 1){
      return debounce(A0, CLR_A);
  } 
  
  if(digitalRead(A1) == 1){
      return debounce(A1, CLR_E);
  }
  
  if(digitalRead(A2) == 1){
      return debounce(A2, CLR_C);
  }   
}

int debounce(int pin, int mapped){
    delay(80);
    if(digitalRead(pin) == 1){
      do{
        delay(50);
        if(digitalRead(11)) BTN_UP   = true;
        if(digitalRead(10)) BTN_DOWN = true;
      }while(digitalRead(pin) == 1);
      return mapped;
    }
    return -1;
}

int debounce2(int pin, int mapped){
    if(digitalRead(10)) BTN_DOWN= true;
    delay(200);
    if(digitalRead(10)) BTN_DOWN= true;
    return mapped;
}
