Build an Arduino Mega 2560 calculator with a 4×4 keypad and three extra buttons for clear, delete and shift functions, a 16×2 I2C LCD that shows the sum and the result, and a key-click buzzer.
Need it ready-made? Buy Ready Project
A pocket calculator is a familiar tool, and building one yourself is a clear way to learn how a microcontroller reads a keypad, keeps a running total and drives a display. This Arduino Mega 2560 calculator uses a 4×4 membrane keypad for the digits and the four basic operations, a 16×2 I2C LCD to show the expression and the result, and three extra buttons for clear, backspace and a shift layer with square root, square, percent and sign change. A short beep from a buzzer follows every key press, so the unit feels like a real calculator.
The Mega 2560 is a good board for this project because it has plenty of 5 V-tolerant pins. The keypad takes eight pins on the double-row header (D22 to D36), the LCD uses the hardware I2C pins D20 and D21, and the three extra buttons plus the buzzer use D2, D3, D4 and D8. You can power the whole build from the USB cable, or from a 7–12 V adapter on the barrel jack.

How It Works
- Keypad scanning: the Keypad library drives one row LOW at a time and reads the four columns. The 4×4 layout in the code is 1–9 and 0 for digits,
*for the decimal point,#for equals, and A / B / C / D for + / − / × / ÷. - Running total: the first number is stored in an accumulator. When you press an operator, that number is kept and the next number is typed. Pressing equals, or pressing another operator, applies the pending operation. You can chain sums such as 12 + 7 − 3.
- Shift functions: the FUNC button toggles a shift layer (the on-board LED on D13 lights when it is on, and a small F appears on the LCD). Then A takes the square root, B squares the number, C converts it to a percentage, and D changes the sign. Percent after + or − means “this percent of the running total” (200 + 10% = 220).
- Display: line 1 shows the expression you have typed so far (it scrolls to the last 15 characters if it gets long). Line 2 shows the number being entered, or the result, right-aligned like a pocket calculator. Very large or very small values switch to scientific notation.
- Errors: divide by zero, the square root of a negative number, or an overflow puts the calculator into an error state. A long beep sounds, the LCD shows Error, and the next key press clears everything.
- Serial log: each completed sum is also printed on the Serial Monitor at 9600 baud, which is useful when you are checking the firmware.
Components Required
- Arduino Mega 2560 board – 1
- 4×4 membrane keypad – 1
- 16×2 LCD with I2C backpack (address 0x27 or 0x3F) – 1
- 12 mm tactile push buttons (CLR, DEL, FUNC) – 3
- Active 5 V buzzer – 1
- 100 Ω resistor (series with the buzzer) – 1
- Breadboard and jumper wires – 1 set
- USB-A to USB-B cable (or 7–12 V DC adapter for the barrel jack) – 1
Wiring Table
| Part / pin | Mega 2560 pin | Notes |
|---|---|---|
| Keypad row 1, 2, 3, 4 | D22, D24, D26, D28 | Ribbon pins 1–4 on a typical 4×4 keypad |
| Keypad column 1, 2, 3, 4 | D30, D32, D34, D36 | Ribbon pins 5–8 |
| LCD I2C SDA | D20 (SDA) | Hardware I2C; do not use A4 |
| LCD I2C SCL | D21 (SCL) | Hardware I2C; do not use A5 |
| LCD VCC / GND | 5 V / GND | The backpack is a 5 V module |
| CLR button | D2 | Other leg to GND; internal pull-up, no resistor |
| DEL button | D3 | Other leg to GND; internal pull-up |
| FUNC (shift) button | D4 | Other leg to GND; internal pull-up |
| Active buzzer (+) | D8 through 100 Ω | Buzzer (−) to GND |
| FUNC indicator | D13 (on-board LED) | Already on the Mega, no extra wiring needed |
| Power | USB or barrel jack | USB 5 V, or 7–12 V DC on the jack |
The Mega’s hardware I2C pins are D20 (SDA) and D21 (SCL). A4 and A5, which you may know from the Arduino Uno, are ordinary analog pins on the Mega and will not talk to the LCD. If your keypad keys come out shuffled, swap the row and column wires, or count the ribbon from pin 1 (usually the far left pin when the letters face you). The three extra buttons only need a ground connection; the code turns on the internal pull-up resistors.
Connection Diagram
The photo above shows the Mega, the keypad, the LCD, the three buttons and the buzzer together. The drawing below lists every pin exactly as used in the code, so you can check your wiring before you upload the sketch.
Code
The sketch is written in Arduino C++. It needs two libraries from the Library Manager: Keypad by Mark Stanley and Alexander Brevig, and LiquidCrystal I2C by Frank de Brabander. It was compile-checked for the Arduino Mega 2560 (arduino:avr:mega): about 13.0 KB of flash (5 %) and 720 bytes of RAM (8 %). In the Arduino IDE choose Tools → Board → Arduino AVR Boards → Arduino Mega or Mega 2560 and set the processor to ATmega2560, then upload.
/*
Arduino Mega 2560 Calculator with 4x4 Keypad, 16x2 I2C LCD & Buzzer
Arduino Project Hub - https://ardiunoprojecthub.online
Keys on the 4x4 keypad:
0-9 = digits * = decimal point # = equals
A = + B = - C = x D = /
Extra push buttons (to GND, internal pull-ups):
CLR (pin 2) = clear everything (AC)
DEL (pin 3) = delete the last typed digit
FUNC (pin 4) = shift key. Press FUNC, then:
A = square root, B = square, C = percent, D = +/- sign
LCD line 1 shows the expression, line 2 shows the number / result.
Libraries: Keypad (Mark Stanley, Alexander Brevig)
LiquidCrystal I2C (Frank de Brabander)
*/
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// ---------- Hardware ----------
const byte ROWS = 4, COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {22, 24, 26, 28}; // keypad R1-R4
byte colPins[COLS] = {30, 32, 34, 36}; // keypad C1-C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2); // try 0x3F if the screen stays blank
const byte PIN_CLR = 2;
const byte PIN_DEL = 3;
const byte PIN_FUNC = 4;
const byte PIN_BUZZ = 8; // active buzzer (+) through 100 ohm
const byte PIN_LED = 13; // on-board LED = FUNC (shift) active
// ---------- Calculator state ----------
char entry[13] = ""; // number being typed (max 12 characters)
double accumulator = 0; // result so far
char pendingOp = 0; // '+', '-', 'x', '/' or 0
bool justEvaluated = false;
bool errorState = false;
bool shiftOn = false;
char expr[40] = ""; // text for LCD line 1
// ---------- Small helpers ----------
void beep(int ms) {
digitalWrite(PIN_BUZZ, HIGH);
delay(ms);
digitalWrite(PIN_BUZZ, LOW);
}
// Format a number into text that fits in 'width' characters
void formatNumber(double v, char *out, byte width) {
if (isnan(v) || isinf(v)) { strcpy(out, "Error"); return; }
double a = fabs(v);
if (a >= 1e9 || (a > 0 && a < 0.0001)) {
dtostre(v, out, 3, 0); // scientific, e.g. 1.235e+10
return;
}
// AVR double has ~7 significant digits, so choose decimals to match
byte decimals = 6;
if (a >= 10) decimals = 5;
if (a >= 100) decimals = 4;
if (a >= 1000) decimals = 3;
if (a >= 10000) decimals = 2;
if (a >= 100000) decimals = 1;
if (a >= 1000000) decimals = 0;
dtostrf(v, 1, decimals, out);
// remove trailing zeros and a trailing decimal point
if (strchr(out, '.')) {
int n = strlen(out) - 1;
while (n > 0 && out[n] == '0') out[n--] = '\0';
if (out[n] == '.') out[n] = '\0';
}
if (strcmp(out, "-0") == 0) strcpy(out, "0");
if (strlen(out) > width) dtostre(v, out, 3, 0);
}
void showScreen() {
char line2[17];
lcd.clear();
// Line 1: last 16 characters of the expression (+ shift marker)
int len = strlen(expr);
const char *start = (len > 15) ? expr + (len - 15) : expr;
lcd.setCursor(0, 0);
lcd.print(shiftOn ? 'F' : ' ');
lcd.print(start);
// Line 2: the number being typed, or the current result
if (errorState) strcpy(line2, "Error");
else if (entry[0] != '\0') strncpy(line2, entry, 16);
else formatNumber(accumulator, line2, 16);
line2[16] = '\0';
lcd.setCursor(16 - strlen(line2), 1); // right-aligned like a real calculator
lcd.print(line2);
}
void clearAll() {
entry[0] = '\0';
expr[0] = '\0';
accumulator = 0;
pendingOp = 0;
justEvaluated = false;
errorState = false;
shiftOn = false;
digitalWrite(PIN_LED, LOW);
}
double entryValue() { return entry[0] ? atof(entry) : accumulator; }
// Apply the pending operation to the accumulator and the typed number
void applyPending() {
double b = entryValue();
switch (pendingOp) {
case '+': accumulator += b; break;
case '-': accumulator -= b; break;
case 'x': accumulator *= b; break;
case '/':
if (b == 0) { errorState = true; return; } // divide by zero
accumulator /= b;
break;
default: accumulator = b; break;
}
if (isnan(accumulator) || isinf(accumulator)) errorState = true;
}
void appendExpr(const char *s) {
if (strlen(expr) + strlen(s) < sizeof(expr) - 1) strcat(expr, s);
else { // keep only the end if it gets long
memmove(expr, expr + strlen(s), strlen(expr) - strlen(s) + 1);
strcat(expr, s);
}
}
// ---------- Key handlers ----------
void digitKey(char k) {
if (justEvaluated) { clearAll(); } // new calculation after '='
byte n = strlen(entry);
if (n >= 12) { beep(80); return; } // too many digits
if (k == '.') {
if (strchr(entry, '.')) return; // only one decimal point
if (n == 0) { strcpy(entry, "0"); n = 1; }
}
if (n == 1 && entry[0] == '0' && k != '.') n = 0; // no leading zeros
entry[n] = k;
entry[n + 1] = '\0';
}
void operatorKey(char op) {
char buf[17];
if (justEvaluated) { // keep using the last answer
formatNumber(accumulator, buf, 12);
strcpy(expr, buf);
justEvaluated = false;
} else if (entry[0] != '\0') {
appendExpr(entry);
applyPending();
} else if (pendingOp != 0) { // change operator, e.g. + then -
expr[strlen(expr) - 1] = '\0';
} else {
formatNumber(accumulator, buf, 12);
strcpy(expr, buf);
}
pendingOp = op;
char s[2] = {op, '\0'};
appendExpr(s);
entry[0] = '\0';
}
void equalsKey() {
if (pendingOp == 0 && entry[0] == '\0') return;
if (entry[0] != '\0') appendExpr(entry);
applyPending();
appendExpr("=");
pendingOp = 0;
entry[0] = '\0';
justEvaluated = true;
if (!errorState) {
char buf[17];
formatNumber(accumulator, buf, 16);
Serial.print(expr); // log each sum to Serial Monitor
Serial.println(buf);
}
}
void functionKey(char k) {
double v = entryValue();
const char *name = "";
switch (k) {
case 'A': if (v < 0) { errorState = true; return; } v = sqrt(v); name = "sqrt"; break;
case 'B': v = v * v; name = "sqr"; break;
case 'C': // percent: 200 + 10% = 220, 50 x 20% = 10
v = (pendingOp == '+' || pendingOp == '-') ? accumulator * v / 100.0 : v / 100.0;
name = "%"; break;
case 'D': v = -v; name = "+/-"; break;
default: return;
}
if (isnan(v) || isinf(v)) { errorState = true; return; }
if (justEvaluated) { accumulator = v; strcpy(expr, name); return; }
dtostrf(v, 1, 6, entry); // put the result back as the entry
if (strchr(entry, '.')) { // trim trailing zeros
int n = strlen(entry) - 1;
while (n > 0 && entry[n] == '0') entry[n--] = '\0';
if (entry[n] == '.') entry[n] = '\0';
}
entry[12] = '\0';
}
void deleteKey() {
if (justEvaluated || errorState) { clearAll(); return; }
byte n = strlen(entry);
if (n > 0) entry[n - 1] = '\0';
}
// Simple debounced read for the three extra buttons
bool buttonPressed(byte pin) {
static unsigned long lastPress[5] = {0};
if (digitalRead(pin) == LOW && millis() - lastPress[pin] > 250) {
lastPress[pin] = millis();
return true;
}
return false;
}
void setup() {
pinMode(PIN_CLR, INPUT_PULLUP);
pinMode(PIN_DEL, INPUT_PULLUP);
pinMode(PIN_FUNC, INPUT_PULLUP);
pinMode(PIN_BUZZ, OUTPUT);
pinMode(PIN_LED, OUTPUT);
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0); lcd.print(" Mega Calculator");
lcd.setCursor(0, 1); lcd.print(" Project Hub");
beep(60);
delay(1500);
clearAll();
showScreen();
}
void loop() {
bool changed = false;
if (buttonPressed(PIN_CLR)) { clearAll(); beep(40); changed = true; }
if (buttonPressed(PIN_DEL)) { deleteKey(); beep(20); changed = true; }
if (buttonPressed(PIN_FUNC)) {
shiftOn = !shiftOn;
digitalWrite(PIN_LED, shiftOn);
beep(20); changed = true;
}
char k = keypad.getKey();
if (k) {
beep(15); // key click
changed = true;
if (errorState) clearAll(); // any key clears an error
if (shiftOn && k >= 'A' && k <= 'D') {
functionKey(k);
shiftOn = false;
digitalWrite(PIN_LED, LOW);
} else if (k >= '0' && k <= '9') digitKey(k);
else if (k == '*') digitKey('.');
else if (k == '#') equalsKey();
else if (k == 'A') operatorKey('+');
else if (k == 'B') operatorKey('-');
else if (k == 'C') operatorKey('x');
else if (k == 'D') operatorKey('/');
if (errorState) beep(300); // long beep on error
}
if (changed) showScreen();
}
Using the Calculator
- Basic sums: type a number, press A for +, B for −, C for × or D for ÷, type the next number and press # for equals. The * key is the decimal point.
- Chain sums: after a result, press another operator to keep using that answer, for example 8 + 2 × 5 (this calculator applies each operator as you enter it, left to right, so that example gives 50, not 18).
- Clear and delete: CLR wipes the whole sum. DEL deletes the last digit you typed.
- Shift functions: press FUNC (the D13 LED turns on), then A for square root, B for square, C for percent or D to change the sign. Press FUNC again to cancel shift.
- After an error: press any key, or CLR, and start again.
Troubleshooting
| Problem | Fix |
|---|---|
| LCD stays blank or only shows boxes | On the Mega, SDA and SCL are D20 and D21, not A4 and A5. If the wiring is correct, change the address in the code from 0x27 to 0x3F. Also turn the backpack contrast pot until the text appears. |
| Keys print the wrong character | The row and column wires are swapped, or the ribbon is counted from the wrong end. Check the wiring table and the rowPins / colPins arrays in the sketch. |
| Some keys do nothing | A membrane keypad pin is loose. With a jumper, briefly short one row pin to one column pin; the matching key should register. Replace the keypad if only one row or column is dead. |
| CLR, DEL or FUNC do nothing | Each button must go between its Mega pin and GND. There is no external pull-up. A normally closed switch, or a button wired to 5 V, will not work with this code. |
| No beep | Use an active 5 V buzzer (it has a built-in oscillator) on D8, with the 100 Ω resistor on the + lead. A passive piezo needs a tone signal and will stay quiet here. |
| Compile error: Keypad.h or LiquidCrystal_I2C.h not found | In the Arduino IDE open Tools → Manage Libraries and install Keypad (Stanley / Brevig) and LiquidCrystal I2C (de Brabander). |
| Result shows Error | You divided by zero, took the square root of a negative number, or the value overflowed. Press CLR and try again. |
| Display shows 0.000000 or a long string of digits | This should not happen with the bundled sketch, which trims trailing zeros. Make sure you uploaded the full file and did not change formatNumber(). |
Ideas to Extend
- Save the last result in the Mega’s EEPROM so it comes back after power-off.
- Add a fourth button for a memory store / recall (M+ and MR).
- Replace the 16×2 LCD with a 20×4 LCD, or an SSD1306 OLED, to show a longer history of sums.