//PROYEK #28:Kalkulator 
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set alamat LCD  0x27, Lcd 16 kolom dan 2 baris
const byte JmlBaris = 4; // 4 baris
const byte JmlKolom = 4; // 4 kolom
//definsikan keymap
char keys[JmlBaris][JmlKolom] = {
  {'1', '2', '3', '/'},
  {'4', '5', '6', 'x'},
  {'7', '8', '9', '-'},
  {'C', '0', '=', '+'}
};
//hubungkan pin baris keypad dengan pin esp32
  byte PinBaris[JmlBaris] = {13, 12, 14, 27 }; // Pins terhubung ke R1, R2, R3, R4
// hubungkan pin kolom keypad dengan pin esp32
byte PinKolom[JmlKolom] = {26, 25, 33, 32 }; // Pin terhubung ke C1, C2, C3, C4
//buat obyek keypad
Keypad myKeypad = Keypad(makeKeymap(keys), PinBaris, PinKolom, JmlBaris, JmlKolom );
//deklarasikan variabel
boolean valOnePresent = false;
boolean final = false;
String num1, num2;
long ans;
char op;

void setup(){
  lcd.init();        // inialisasi lcd
  lcd.backlight(); //nyalakan baclight
  lcd.setCursor(2,0);	
  lcd.print("Kalkulator MILEON !");
  delay(1000);
  lcd.clear(); //lcd clear 
}

void loop(){
  char key = myKeypad.getKey();
  if(key!=NO_KEY && key=='1'||key=='2'||key=='3'
||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'){
  if (valOnePresent != true){
      num1 = num1 + key;
      int numLength = num1.length();
      lcd.setCursor(15-numLength, 0);//print operator
      lcd.print(num1);
    }
    else {
      num2 = num2 + key;
      int numLength = num2.length();
      lcd.setCursor(15 - numLength, 1);
      lcd.print(num2);
      final = true;
    }
  }

  else if (valOnePresent == false && key != NO_KEY && (key  
       == '/' || key == 'x' || key == '-' || key == '+')){
   
   if (valOnePresent == false){
       valOnePresent = true;
       op = key;
       lcd.setCursor(15,0); 
       lcd.print(op);
    }
  }

  else if (final == true && key != NO_KEY && key == '='){
    if (op == '+'){
      ans = num1.toInt() + num2.toInt();
    }
    else if (op == '-'){
      ans = num1.toInt() - num2.toInt();
    }
    else if (op == 'x'){
      ans = num1.toInt() * num2.toInt();
    }
    else if (op == '/'){
      ans = num1.toInt() / num2.toInt();
    }    
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.autoscroll();
      lcd.print(ans);
      lcd.noAutoscroll();
  }
  else if (key != NO_KEY && key == 'C'){
    lcd.clear();
    valOnePresent = false;
    final = false;
    num1 = "";
    num2 = "";
    ans = 0;
    op = ' ';
  }
}