#include <Keypad.h>
#include <LiquidCrystal.h>
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(12, 11, A0, A1, A2, A3);
String input = "";
float num1 = 0;
char operation = 0;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop()
{
char customKey = customKeypad.getKey();
if (customKey)
{
Serial.print(customKey); // Print the character as it's pressed
lcd.print(customKey);
if (customKey >= '0' && customKey <= '9')
{
input += customKey;
} else if (customKey == '.' && input.indexOf('.') == -1)
{
input += customKey;
} else if (customKey == '+' || customKey == '-' || customKey == '*' || customKey == '/')
{
if (input.length() > 0)
{
num1 = input.toFloat();
operation = customKey;
input = "";
lcd.setCursor(0, 1);
}
} else if (customKey == '=')
{
if (input.length() > 0)
{
float num2 = input.toFloat();
float result = 0;
switch (operation)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
} else
{
Serial.println("Error: Division by zero");
lcd.clear();
lcd.print("Error: Division by zero");
}
break;
}
Serial.println(String(result));
lcd.clear();
lcd.print(String(result));
input = ""; // Clear the input after displaying the result
}
}
}
}