/*
This channel For sharing Electrical knowledge. Thanks for always support
Facebook page: https://www.facebook.com/profile.php?id=100082025133151&mibextid=ZbWKwL
Telegram Channel: https://t.me/soloeletrician
*/
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
int i = 0;
int j = 0;
LiquidCrystal_I2C mylcd(0x27,16,2);
const byte rows = 4;
const byte cols = 4;
char key[rows][cols] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'#', '0', '*', 'D'} // '#' is now the clear key, '*' is the result key
};
byte rowPins[rows] = {9, 8, 7, 6};
byte colPins[cols] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(key), rowPins, colPins, rows, cols);
// Variables to store calculator input and result
String inputString = "";
float result = 0.0;
void setup() {
mylcd.init();
mylcd.clear();
mylcd.backlight();
mylcd.setCursor(0, 0);
mylcd.print("Calculator:");
mylcd.setCursor(0, 1);
}
void loop() {
char press = keypad.getKey();
if (press != NO_KEY) {
if (press == 'A') { // Addition
inputString += '+';
} else if (press == 'B') { // Subtraction
inputString += '-';
} else if (press == 'C') { // Multiplication
inputString += '*';
} else if (press == 'D') { // Division
inputString += '/';
} else if (press == '#') { // Clear the entire input
inputString = "";
} else if (press == '*') { // Calculate and display result
// Check if the input is not empty
if (inputString.length() > 0) {
result = calculateResult(inputString);
mylcd.setCursor(0, 1);
mylcd.print("Result: ");
mylcd.setCursor(8, 1);
mylcd.print(result);
delay(2000); // Delay to display the result before clearing
inputString = "";
mylcd.setCursor(0, 1);
mylcd.print(" "); // Clear the result
}
} else { // Numeric and other characters
inputString += press;
}
// Display the input string
mylcd.setCursor(0, 1);
mylcd.print(" "); // Clear the previous input
mylcd.setCursor(0, 1);
mylcd.print(inputString);
}
}
float calculateResult(String input) {
// Implement the calculation here
// This example assumes a simple calculation with one operator
int operatorPos = -1;
// Find the position of an operator character
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '+' || input.charAt(i) == '-' ||
input.charAt(i) == '*' || input.charAt(i) == '/') {
operatorPos = i;
break;
}
}
if (operatorPos == -1 || operatorPos == 0 || operatorPos == input.length() - 1) {
return 0.0; // Invalid input or no operator
}
float num1 = input.substring(0, operatorPos).toFloat();
float num2 = input.substring(operatorPos + 1).toFloat();
char op = input.charAt(operatorPos);
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 != 0.0) {
return num1 / num2;
} else {
return 0.0; // Division by zero
}
default:
return 0.0; // Invalid operator
}
}