#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
int cnt = 0;
int numbers[3] = {0};
int sum = 0;
float average = 0.0;
bool inputStarted = false;
bool resultDisplayed = false;
#define ROW_NUM 4
#define COLUMN_NUM 4
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3', 'A'},
{'4','5','6', 'B'},
{'7','8','9', 'C'},
{'*','0','#', 'D'}
};
byte pin_rows[ROW_NUM] = {12, 14, 27, 26};
byte pin_column[COLUMN_NUM] = {25, 33, 32, 35};
const int startButtonPin = 18;
const int lcdColumns = 16;
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );
LiquidCrystal_I2C lcd(0x27, 16, 2);
void getInput() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter 3 numbers:");
inputStarted = true;
resultDisplayed = false;
cnt = 0;
for (int i = 0; i < 3; i++) {
numbers[i] = 0;
}
}
void calculateAndDisplay() {
sum = numbers[0] + numbers[1] + numbers[2];
average = sum / 3.0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Sum:");
lcd.setCursor(5, 0);
lcd.print(sum);
lcd.setCursor(0, 1);
lcd.print("Average:");
lcd.setCursor(9, 1);
lcd.print(average);
}
void setup() {
Serial.begin(9600);
pinMode(startButtonPin, INPUT_PULLUP);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Press START");
}
void loop() {
if (!inputStarted && digitalRead(startButtonPin) == LOW) {
getInput();
}
if (inputStarted) {
char keypressed = keypad.getKey();
if (keypressed && keypressed >= '0' && keypressed <= '9' && cnt < 3) {
numbers[cnt] = numbers[cnt] * 10 + (keypressed - '0');
lcd.setCursor(cnt, 1);
lcd.print(keypressed);
cnt++;
}
// Check for delete/backspace key ('*')
if (keypressed == '*') {
if (cnt > 0) {
// Clear the last entered digit
cnt--;
numbers[cnt] = 0;
lcd.setCursor(cnt, 1);
lcd.print(" "); // Clear the digit on the LCD
}
}
// Check for enter/submit key ('#')
if (keypressed == '#') {
if (cnt == 3) {
calculateAndDisplay();
resultDisplayed = true;
inputStarted = false;
}
}
}
// Check if it's time to return to input process
if (resultDisplayed && digitalRead(startButtonPin) == LOW) {
getInput(); // Reset input process
}
}