ThisCalculator

Everyday

Arduino Calculator Code: How to Build One

Updated · Standard formula, shown below

The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.

Arduino Calculator Code: How to Build One

To build an Arduino calculator, you write code that reads numeric keypad presses, stores the entered numbers and operator, and performs the calculation when the equals key is pressed. The core logic involves detecting button presses, parsing multi-digit numbers, and using a switch or if-else chain to apply the selected arithmetic operation. This article explains the code structure, keypad wiring, and common pitfalls so you can create a working calculator with an Arduino Uno, a 4×4 keypad, and an LCD display.

How an Arduino Calculator Code Works

An Arduino calculator is a finite state machine. The code continuously scans the keypad for a pressed key. When a digit (0-9) is pressed, it appends that digit to a character buffer that holds the current number. When an operator (+, -, *, /) is pressed, the code stores the first number and the operator, then resets the buffer for the second number. When the equals sign is pressed, the code converts both number buffers to floating-point values, performs the operation, and displays the result on the LCD. The result is then kept as the first number for chained calculations if the user presses another operator.

Key components of the code:

  • Keypad library: Simplifies reading a matrix keypad. The Keypad library by Mark Stanley and Alexander Brevig is the most common.
  • LiquidCrystal library: Controls the 16×2 character LCD. It is included with the Arduino IDE.
  • Global variables: Store the first number, the operator, and a flag indicating whether the current entry is the first or second number.
  • State machine logic: Tracks whether you are entering the first number, the operator, or the second number.

Writing the Basic Code Structure

Here is a minimal skeleton of Arduino calculator code. It assumes a 4×4 keypad with keys 0-9, A-D for operators (A=+, B=-, C=*, D=/), and * for clear, # for equals.

#include <Keypad.h>
#include <LiquidCrystal.h>

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {9,8,7,6};
byte colPins[COLS] = {5,4,3,2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(13,12,11,10,1,0);

float num1 = 0;
float num2 = 0;
char op = 0;
String currentInput = "";
bool secondNumber = false;

void setup() {
  lcd.begin(16,2);
  lcd.print("Calculator");
  delay(2000);
  lcd.clear();
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    if (key >= '0' && key <= '9') {
      currentInput += key;
      lcd.print(key);
    } else if (key == 'A' || key == 'B' || key == 'C' || key == 'D') {
      num1 = currentInput.toFloat();
      op = key;
      currentInput = "";
      secondNumber = true;
      lcd.clear();
      lcd.print(num1);
      lcd.print(" ");
      lcd.print(op);
    } else if (key == '#') {
      num2 = currentInput.toFloat();
      float result = 0;
      switch(op) {
        case 'A': result = num1 + num2; break;
        case 'B': result = num1 - num2; break;
        case 'C': result = num1 * num2; break;
        case 'D': result = num1 / num2; break;
      }
      lcd.clear();
      lcd.print(result);
      num1 = result;
      currentInput = "";
      secondNumber = false;
    } else if (key == '*') {
      lcd.clear();
      num1 = 0; num2 = 0; currentInput = ""; op = 0;
    }
  }
}

This code handles basic operations but lacks decimal point support, backspace, and error handling. For a more polished calculator, you would add a decimal key and check for division by zero.

Choosing the Right Components

Most Arduino calculator projects use:

  • Arduino Uno or Nano: Both have enough digital pins for a keypad and LCD.
  • 4×4 matrix keypad: Gives 16 keys, enough for digits 0-9, four operators, equals, and clear.
  • 16×2 LCD with I2C module: The I2C version uses only two data pins (SDA and SCL) plus power, saving many digital pins. Without I2C, a standard 16×2 LCD needs 6 or 7 pins.
  • Potentiometer (10kΩ): For adjusting LCD contrast.
  • Breadboard and jumper wires: For prototyping.

If you use an I2C LCD, you need the LiquidCrystal_I2C library. The wiring is simpler: connect VCC to 5V, GND to GND, SDA to A4 (on Uno), and SCL to A5 (on Uno).

Common Problems and How to Fix Them

Several issues frequently appear in Arduino calculator builds:

  • Keypad not responding: Check that the row and column pins match your wiring. Swap the rowPins and colPins arrays if needed. Also, ensure the keypad library is installed.
  • LCD shows blocks or nothing: Adjust the contrast potentiometer. If you see solid rectangles, the contrast is too high or too low. Also verify the I2C address (often 0x27 or 0x3F) using an I2C scanner sketch.
  • Numbers concatenate incorrectly: This happens when you don’t clear the currentInput string after an operation. Use currentInput = "" after storing the first number.
  • Division by zero causes ‘inf’ or ‘nan’: Add a check: if the divisor is 0, display “Error” instead of performing the division.
  • Result is always 0: This usually means the keypad is returning the wrong character, or the toFloat() conversion fails because the string is empty. Add debug prints to the serial monitor to see what keys are being read.

Enhancing the Code: Decimal Point and Backspace

A basic calculator without a decimal point is limiting. To add a decimal, include a ‘.’ key on the keypad (you can repurpose the ‘*’ key for decimal and use a separate key for clear). In the digit handling section, check if the key is ‘.’ and if the currentInput does not already contain a dot, then append it. For backspace, you would need an extra key; a common approach is to use the ‘D’ key for backspace instead of an operator, but then you lose division. A better solution is to use a 4×4 keypad with dedicated keys: 0-9, +, -, *, /, =, C, and . — but that is 17 keys, so you’d need a 4×5 keypad or combine functions with a shift key.

Comparing Code Approaches: Blocking vs. Event-Driven

There are two main ways to write the loop:

  • Blocking (using keypad.getKey()): This waits for a key press. It is simple but prevents the Arduino from doing anything else while waiting. For a dedicated calculator, this is fine.
  • Event-driven (using keypad.getKeys() with a state machine): This checks for key events in each loop iteration without blocking. It allows the Arduino to also update a display or read sensors. The code is more complex but more scalable.

For a beginner, the blocking approach is easier to understand. For a project that also needs to respond to other inputs, use the event-driven method.

Safety and Accuracy Considerations

When building an Arduino calculator, accuracy is limited by the floating-point format on the Arduino. The Uno uses 32-bit floats, which have about 7 significant digits. For most everyday calculations, this is sufficient. However, for financial or scientific calculations requiring high precision, you would need to use a different data type (like long for integers) or a library for arbitrary precision numbers. Also, be aware that division by zero will produce inf or nan, which can crash the display. Always check for zero before dividing. In terms of electrical safety, the Arduino operates at 5V and is safe to handle, but avoid shorting pins and always double-check your wiring before powering on.

Alternatives to a Keypad and LCD

If you don’t have a keypad or LCD, you can build a calculator using a different interface:

  • Serial monitor: Use the Arduino’s serial port to send numbers and operators from a computer. The code reads characters from the serial buffer and processes them the same way.
  • Smartphone app via Bluetooth: Use an HC-05 Bluetooth module and a terminal app to send commands wirelessly.
  • Touchscreen TFT display: Use a TFT touchscreen shield to draw buttons on the screen and detect touches. This requires the Adafruit_TFTLCD and TouchScreen libraries.
  • Rotary encoder: Use a rotary encoder to select numbers and operators, and a small OLED display to show the result.

Each alternative changes the input method but the core calculation logic remains the same.

Frequently Asked Questions

Can I use an Arduino Uno for a calculator?

Yes, the Arduino Uno is the most common board for this project. It has enough digital pins for a 4×4 keypad (8 pins) and an I2C LCD (2 pins), leaving plenty of room for other features.

How do I add a decimal point to my Arduino calculator?

You need a key for the decimal point. If your keypad has a spare key, assign it as ‘.’. In the code, when that key is pressed, check that the current input string does not already contain a dot, then append ‘.’. If you don’t have a spare key, you can use a long press of a digit to insert a dot, but that is more complex.

Why does my calculator show ‘inf’ when I divide by zero?

Because floating-point division by zero returns infinity. To avoid this, add a check before performing the division: if the second number is 0, display an error message like “Error” or “Div by 0” instead of doing the calculation.

How do I clear the LCD when starting a new calculation?

Use lcd.clear() before printing new content. In the code, call lcd.clear() when an operator is pressed and when the equals sign is pressed, to show the result on a fresh screen.

Can I use a 4×3 keypad instead of 4×4?

Yes, a 4×3 keypad has 12 keys, which is enough for digits 0-9, #, and *. You can map # to equals and * to clear, but you won’t have dedicated operator keys. You would need to use a combination, like pressing a digit then a letter, which is not intuitive. A 4×4 keypad is recommended.

What is the best library for the keypad?

The Keypad library by Mark Stanley and Alexander Brevig is the most widely used and well-documented. It is available in the Arduino Library Manager. For the LCD, if you use I2C, the LiquidCrystal_I2C library by Frank de Brabander is popular.

Related

Formula used

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.