/*
Project: Calculator
Name: Kevin Hessel
Date: 20.10.2023
Libraries:
- LiquidCrystal.h
- Keypad.h
-----------------------------
*/
#include <Keypad.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(5, 4, 3, 2, 1, 0);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', '+' },
{ '4', '5', '6', '-' },
{ '7', '8', '9', '*' },
{ 'C', '0', '=', '/' }
};
byte rowPins[ROWS] = { 13, 12, 11, 10 };
byte colPins[COLS] = { 9, 8, 7, 6 };
Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
boolean keepCalculating = false;
boolean presentValue = false;
boolean next = false;
boolean final = false;
String num1, num2;
int answer;
char op;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print(" Calculator");
delay(3000);
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 (presentValue != true && keepCalculating != true) {
num1 = num1 + key;
int numLength = num1.length();
lcd.setCursor(15 - numLength, 0);
lcd.print(num1);
} else if (presentValue != true && keepCalculating == true) {
lcd.setCursor(0, 1);
presentValue = true;
op = '+';
lcd.print(op);
num2 = num2 + key;
lcd.print(num2);
}
else if (presentValue == true && keepCalculating != true) {
num2 = num2 + key;
int numLength = num2.length();
lcd.setCursor(15 - numLength, 1);
lcd.print(num2);
final = true;
} else {
num2 = num2 + key;
lcd.setCursor(1, 1);
lcd.print(num2);
final = true;
}
}
else if (presentValue == false && key != NO_KEY && (key == '/' || key == '*' || key == '-' || key == '+')) {
if (presentValue == false && keepCalculating != true) {
presentValue = true;
op = key;
lcd.setCursor(15, 0);
lcd.print(op);
} else if (presentValue == false && keepCalculating == true) {
num2 = "";
presentValue = true;
op = key;
lcd.setCursor(0, 1);
lcd.print(op);
}
}
else if (final == true && keepCalculating != true && key != NO_KEY && key == '=') {
if (op == '+') {
answer = num1.toInt() + num2.toInt();
} else if (op == '-') {
answer = num1.toInt() - num2.toInt();
} else if (op == '*') {
answer = num1.toInt() * num2.toInt();
} else if (op == '/') {
answer = num1.toInt() / num2.toInt();
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(answer);
keepCalculating = true;
presentValue = false;
num1 = "";
num2 = "";
} else if (final == true && keepCalculating == true && key != NO_KEY && key == '=') {
if (op == '+') {
answer = answer + num2.toInt();
} else if (op == '-') {
answer = answer - num2.toInt();
} else if (op == '*') {
answer = answer * num2.toInt();
} else if (op == '/') {
answer = answer / num2.toInt();
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(answer);
keepCalculating = true;
presentValue = false;
num1 = "";
num2 = "";
} else if (key != NO_KEY && key == 'C') {
lcd.clear();
keepCalculating = false;
presentValue = false;
final = false;
num1 = "";
num2 = "";
answer = 0;
op = ' ';
}
}