#include <LiquidCrystal.h>
#include <Keypad.h>
#include <math.h>
LiquidCrystal screen(12, 11, 10, 9, 8, 7);
const byte NUM_ROWS = 4;
const byte NUM_COLS = 4;
byte rowPins[NUM_ROWS] = {5, 4, 3, 2};
byte colPins[NUM_COLS] = {A3, A2, A1, A0};
char keypadKeys[NUM_ROWS][NUM_COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'^', '0', '=', '/'}
};
Keypad myKeypad = Keypad(makeKeymap(keypadKeys), rowPins, colPins, NUM_ROWS, NUM_COLS);
uint64_t displayValue = 0;
void showWelcomeScreen() {
screen.print("Welcome");
screen.setCursor(3, 1);
String welcomeMsg = "Calculator";
for (byte i = 0; i < welcomeMsg.length(); i++) {
screen.print(welcomeMsg[i]);
delay(50);
}
delay(500);
}
void blinkCursor() {
if (millis() / 250 % 2 == 0) {
screen.cursor();
} else {
screen.noCursor();
}
}
char currentOperation = 0;
String storedValue = "";
String inputValue = "";
uint64_t inputDecimal;
bool hasDecimal = false;
double performCalculation(char op, double left, double right) {
switch (op) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
case '^': return pow(left, right); // Add power calculation
}
}
void handleInput(char key) {
if ('-' == key && inputValue == "") {
inputValue = "-";
screen.print("-");
return;
}
switch (key) {
case '+':
case '-':
case '*':
case '/':
case '^': // Handle ^ operator
if (!currentOperation) {
storedValue = inputValue;
inputValue = "";
}
currentOperation = key;
screen.setCursor(0, 1);
screen.print(key);
screen.setCursor(inputValue.length() + 1, 1);
return;
case '=':
float leftOperand = storedValue.toDouble();
float rightOperand = inputValue.toDouble();
storedValue = String(performCalculation(currentOperation, leftOperand, rightOperand));
inputValue = "";
// screen.clear();
screen.setCursor(5, 5);
screen.print(storedValue);
// screen.setCursor(0, 1);
// screen.print(currentOperation);
return;
}
if ('.' == key && inputValue.indexOf('.') >= 0) {
return;
}
if ('.' != key && inputValue == "0") {
inputValue = String(key);
} else if (key) {
inputValue += String(key);
}
screen.print(key);
}
void setup() {
Serial.begin(115200);
screen.begin(16, 2);
showWelcomeScreen();
screen.clear();
screen.cursor();
screen.setCursor(1, 0);
}
void loop() {
blinkCursor();
char key = myKeypad.getKey();
if (key) {
handleInput(key);
}
}