#include <Keypad.h>
// Define the dimensions of the keypad
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
// Define the keymap
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'*', '0', '#', '/'}
};
// Define the row and column pins
byte rowPins[ROWS] = {2, 3, 4, 5}; // Connect to the row pins of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; // Connect to the column pins of the keypad
// Create the keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
// Start the Serial communication
Serial.begin(9600);
}
void loop() {
int num1 = -1;
int num2 = -1;
char operation = 0;
int result = 0;
bool validOperation = true;
// Start the operation cycle
Serial.println("Press '*' to start a new operation.");
// Wait for the user to press '@'
int flag = 1;
while (true) {
char startKey = keypad.getKey();
if (startKey == '*') {
Serial.println("Starting new operation...");
break;
}
}
// Get the first number
Serial.print("ENTER THE FIRST NUMBER: ");
while (num1 == -1) {
char key = keypad.getKey();
if (key >= '0' && key <= '9') {
num1 = key - '0'; // Convert character to integer
Serial.println(num1);
}
}
// Get the second number
Serial.print("ENTER THE SECOND NUMBER: ");
while (num2 == -1) {
char key = keypad.getKey();
if (key >= '0' && key <= '9') {
num2 = key - '0'; // Convert character to integer
Serial.println(num2);
}
}
// Get the operation
Serial.println("Operations: + = addition, - = subtraction, * = multiplication, / = division");
Serial.print("ENTER THE OPERATION: ");
while (operation == 0) {
operation = keypad.getKey();
if (operation == '+' || operation == '-' || operation == '*' || operation == '/') {
Serial.println(operation);
}
}
// Perform the operation
if (operation == '+') {
result = num1 + num2;
} else if (operation == '-') {
result = num1 - num2;
} else if (operation == '*') {
result = num1 * num2;
} else if (operation == '/') {
if (num2 != 0) {
result = num1 / num2;
} else {
Serial.println("Error: Division by zero!");
validOperation = false;
}
} else {
validOperation = false;
Serial.println("Invalid operation!");
}
// Output the result if the operation was valid
if (validOperation) {
Serial.print("Result: ");
Serial.print(num1);
Serial.print(" ");
Serial.print(operation);
Serial.print(" ");
Serial.print(num2);
Serial.print(" = ");
Serial.println(result);
}
// Wait for the user to press '#' before starting a new operation
Serial.println("Operation complete. Press '#' to start again.");
while (true) {
char endKey = keypad.getKey();
if (endKey == '#') {
Serial.println("Restarting...");
break;
}
}
}