#include <Keypad.h>
const byte numRows = 4;
const byte numCols = 4;
byte rowPins[numCols] = {5, 4, 3, 2};
byte colPins[numRows] = {A3, A2, A1, A0};
char keys[numRows][numCols] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
// connect to the column pinouts of the keypad
char inputArray[4]; // array to store the user input
int index = 0; // array index counter
float result; // final result after calculation
void setup()
{
Serial.begin(9600);
for (int i = 0; i < numRows; i++)
{
pinMode(rowPins[i], INPUT_PULLUP);
}
for (int j = 0; j < numCols; j++)
{
pinMode(colPins[j], OUTPUT);
digitalWrite(colPins[j], LOW);
}
}
void loop()
{
char keyPress = readKeypad();
if (keyPress != NO_KEY)
{
if (keyPress == '#')
{
// if user press # key
inputArray[index] = 0; // store 0 in array
index++; // increment array index counter
if (index == 4)
{ // when all inputs are entered
result = calculateResult(); // call
calculateResult();
Serial.println("Result is : " + String(result));
resetIndex();
}
}
else
{
inputArray[index] = keyPress - 48;
Serial.println("You pressed : " + String(keyPress));
index++;
}
}
}
float calculateResult()
{
float sum = 0;
for (int i = 0; i < 4; i++)
{
sum += inputArray[i];
}
return sum * 1.5;
}
void resetIndex() { index = 0; }
char readKeypad()
{
char keypress = NO_KEY;
for (int j = 0; j < numCols; j++)
{
digitalWrite(colPins[j], HIGH);
delay(10);
for (int i = 0; i < numRows; i++)
{
if (digitalRead(rowPins[i]) == LOW)
{
keypress = keys[i][j];
delay(50);
break;
}
}
digitalWrite(colPins[j], LOW);
}
return keypress;
}