Creating an Arduino calculator using a 4x4 keypad and an LCD in Tinkercad is a great project to combine hardware simulation with basic coding. Here's how you can build and program it.
β οΈ Avoid D0 and D1 if you're using Serial communication. Use D A0βA5 instead.
#include <Keypad.h>
#include <LiquidCrystal.h>
// LCD setup
LiquidCrystal lcd(7,6,5,4,3,2);
// Keypad setup
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
byte rowPins[ROWS] = {11, 10, 9, 8};
byte colPins[COLS] = {A1, A2, A3, A4};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input = "";
long num1 = 0, num2 = 0;
char operation;
void setup() {
lcd.begin(16, 2);
lcd.print("Calculator:");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
input += key;
lcd.setCursor(0,1);
lcd.print(input);
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
num1 = input.toInt();
operation = key;
input = "";
lcd.clear();
lcd.setCursor(0,1);
lcd.print(operation);
} else if (key == '=') {
num2 = input.toInt();
long result = 0;
switch(operation) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = (num2 != 0) ? num1 / num2 : 0; break;
}
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Result:");
lcd.setCursor(0,1);
lcd.print(result);
input = "";
} else if (key == 'C') {
input = "";
num1 = num2 = 0;
lcd.clear();
lcd.print("Calculator:");
}
}
}