#include <MsTimer2.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(8,9,4,5,6,7);

int adc_key_val[5] ={30, 150, 360, 535, 760 };

unsigned char count;
unsigned char seconds;
unsigned char minutes;
unsigned char hours;
int read_pin = 5;
int NUM_KEYS = 5;
int adc_key_in;
int key=-1;
int oldkey=-1;
boolean ledState = 0;

void setup()
{
  
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  
  lcd.print("*Clock1*");
  
  MsTimer2::set(10, clock);
  MsTimer2::start();
}

void loop()
{
  
   
  int val = analogRead(read_pin);
  
  //Serial.println(val);
  
  int inten = map(val, 0, 1023, 0, 255);
  
  analogWrite(10, inten);
  
  adc_key_in = analogRead(0);   // read the value from the sensor
  key = get_key(adc_key_in); // convert into key press
  if (key != oldkey) // if keypress is detected
  {
     delay(50);  // wait for debounce time
     adc_key_in = analogRead(0);   // read the value from the sensor
     key = get_key(adc_key_in);    // convert into key press
     if (key != oldkey)
     {
       oldkey = key;

       lcd.setCursor(0,1);        
       
       if (key==0)
       {
         lcd.print("         ");
         lcd.setCursor(0,1);
          Serial.println("push 0 key");
          lcd.print("RIGHT!!");
       }
       else if (key==1)
       {
         lcd.print("         ");
         lcd.setCursor(0,1);
          Serial.println("push 1 key");
          hours++;
          seconds = 0;
          if(hours > 23) hours = 0;
          //lcd.print("HIGH!!");
       }
       else if (key==2)
       {
         lcd.print("         ");
         lcd.setCursor(0,1);
          Serial.println("push 2 key");
          //lcd.print("LOW!!");
          minutes++;
          seconds = 0;
          if(minutes > 59) minutes = 0;
       }
       else if (key==3)
       {
         lcd.print("         ");
         lcd.setCursor(0,1);
          Serial.println("push 3 key");
          lcd.print("LEFT!!");
       }
       else if(key==4)
       {
         lcd.print("         ");
         lcd.setCursor(0,1);
          Serial.println("push 4 key");
          lcd.print("SELECT!!");
       }
      
       lcd.setCursor(0,1);
    }
  }  
    
  lcd.setCursor(0,1);
  displayDigits(hours);
  displayDigits(minutes);
  displayDigits(seconds);
  delay(200);
}

void displayDigits(int digits)
{
  if(digits < 10) lcd.print("0");
  lcd.print(digits);
  lcd.print(":");
}

void clock()
{
  count++;
  
  if(count == 100){
    count = 0;
    seconds++;
    ledState = !ledState;
    digitalWrite(3, ledState);
  }
  
  if(seconds == 60){
    minutes++;
    seconds = 0;
    
    if(minutes == 60){
      hours++;
      minutes = 0;
      
      if(hours == 24){
        hours = 0;
      }
    }
  }
}

int get_key(unsigned int input)
{
 int k;   
 for (k = 0; k < NUM_KEYS; k++)
 {
  if (input < adc_key_val[k])
  {          
    return k;
  }
 }   
        if (k >= NUM_KEYS)
        k = -1;     // No valid key pressed
       return k;
}
  
