Building a calculator on a microcontroller with a touchscreen involves more than arithmetic. The sketch has to draw every button on the screen and determine which key each touch lands on. It also has to keep track of the numbers and operators entered between presses.
This project uses an Arduino Mega 2560 and a 3.5-inch ILI9486 thin-film transistor (TFT) touchscreen shield. The shield plugs directly onto Arduino, so the build doesn’t require a keypad matrix, a breadboard, or jumper wires.
The finished calculator displays a two-line readout above a 20-key keypad. It performs addition, subtraction, multiplication, and division, and it evaluates chained operations from left to right, as a standard desk calculator does. Additional keys handle percentages, sign changes, decimal points, backspace, and clear. Dividing by zero displays “Error” rather than an invalid result.
Components required
- Arduino Uno/Mega x1
- 5-inch TFT touchscreen shield (ILI9486 driver) x1
- Stylus (optional) x1
- USB A-to-B cable for uploading the sketch and powering the board x1
Circuit connections
The project requires no wiring. Plug the TFT touchscreen shield onto Arduino, and the hardware is ready. You can power the board through its USB port or from a dc adapter connected to the barrel jack. The only other connection is a USB cable to your computer for uploading the sketch.
The display communicates with Arduino over an 8-bit parallel bus, which uses eight data lines to transfer a full byte at once. Five additional control lines tell the display controller how to handle that data.
The table below lists the typical pin assignments for this type of shield. The MCUFRIEND_kbv library handles Arduino’s port mapping automatically.
The touch panel doesn’t have dedicated pins. Its four electrodes share pins with the display, and the sketch switches those pins between display control and touch sensing many times per second.
XM and YP must connect to analog pins, because the touch position is measured with an analog-to-digital converter (ADC). Touch pin assignments can vary between shield batches, and incorrect assignments don’t produce an error message. The touchscreen simply won’t respond correctly. If you’re unsure which touch pins your shield uses, run the TouchScreen_Calibr_native example included with the MCUFRIEND_kbv library, which identifies them automatically.
The software requires three libraries, all available through the Library Manager in Arduino’s integrated development environment (IDE).
How it works
The sketch runs in a continuous cycle. When it detects a touch, it identifies the key that was pressed and updates the calculation. It then redraws the readout and waits for the touch to be released before starting the next cycle.
Screen layout
In portrait mode, the screen measures 320 x 480 px. The top 120 px are reserved for the readout, and the remaining 360 px form a keypad grid of five rows and four columns. Each key occupies an 80 x 72-px cell, with a rounded button inset 3 px from each edge.
The readout has two lines. The upper line, in small gray text, shows the expression in progress, such as 200 + 10 =. The lower line, in large white text, shows the number you’re entering or the latest result. Both lines are right-aligned, as on a standard calculator.
Each key’s color indicates its function. Digit keys and the decimal point are dark gray, and the function keys (C, +/-, %, and backspace) are light gray. Operator keys are orange, and the equals key is green.
Reading the resistive touch panel
A 4-wire resistive touch panel consists of two transparent resistive layers separated by small spacer dots. Pressing the panel brings the layers into contact at a single point.
Each layer works like a potentiometer. To read the X position, the library applies 5 V to XP and connects XM to ground, creating a voltage gradient across the X layer. The Y layer then acts as the wiper, and YP picks up a voltage proportional to the horizontal position of the touch. The ADC converts that voltage to a digital value. Reversing the roles of the two layers gives the Y position. A third measurement across the layers estimates the contact resistance, which the library reports as pressure, or z.
Because XM and YP also serve as the display’s LCD_RS and LCD_WR lines, each touch reading leaves them configured as inputs. The sketch must switch them back to outputs immediately. Otherwise, the next draw command corrupts the screen.
Converting touch readings to key presses
The ADC returns raw values from roughly 100 to 1000 rather than pixel coordinates. The sketch converts these values to screen positions with Arduino’s map() function and four calibration constants, which define the raw value at each edge of the screen.
To filter out noise when nothing is touching the panel, the sketch only accepts readings with a pressure value between 10 and 1000.
Once a touch is mapped to a point below the readout, the sketch identifies the key with simple arithmetic. The column is x / 80, and the row is (y – 120) / 72. These two values index a 5 x 4 table of key labels.
Calculator behavior
The calculator follows desk calculator logic rather than scientific calculator logic. Entering 2 + 3 * 4 = gives 20, not 14, because each operator completes the previous calculation before the next one begins.
The number you’re entering is stored as a text string rather than a numeric value. This approach simplifies the digit, decimal point, and backspace keys, since each one only edits the string. The sketch converts the string to a number only when an operator, equals, or percent key requires the value.
Arduino sketch
Number formatting
On AVR boards, double is the same 32-bit type as float, which limits results to about seven significant digits. AVR’s sprintf function also can’t format floating-point values with %f, so formatValue() uses the AVR libc functions dtostrf() and dtostre() instead.
Values of 1e9 and above, or below 1e-5, are displayed in scientific notation. For all other values, the function counts the digits before the decimal point and allows 7 – intDigits decimal places, within a range of 0 to 6. This prevents the display from showing more precision than the hardware can provide. The function then removes trailing zeros, so 2.500000 appears as 2.5, and it converts “-0” to “0.”
Drawing
buttonColor() selects each key’s color based on its label, and drawButton() draws a rounded rectangle with the label centered inside it.
The default GFX font uses a 6 x 8-px cell for each character, scaled by the text size. At size 3, each character is 18 px wide, so a label measures strlen(k) * 18 px across. The sketch uses these dimensions to center the text. When a key is pressed, drawButton() redraws it in white with black text to confirm the press.
drawDisplay() clears the readout and redraws both lines, right-aligned 10 px from the edge of the screen. Longer numbers are drawn at smaller sizes to fit. Entries of up to 10 characters use size 5, entries of up to 13 characters use size 4, and longer entries use size 3. Error messages appear in orange.
Calculator logic
handleKey() processes each key press. If an error is displayed, any key press clears it first. The function then responds according to the key.
- Digit keys start a new number if startNew is set, replace a lone “0,” or append to the current entry, up to 12 characters.
- The decimal point key adds a decimal point only if the entry doesn’t already contain one.
- Backspace deletes the last character but doesn’t change a computed result.
- The +/- key adds or removes a leading minus sign using memmove().
- Operator keys store the entry in acc if no operation is pending. If an operation is already pending and a new number has been entered, compute() completes that operation first, which produces left-to-right chaining. Pressing two operators in a row replaces the first operator with the second.
- The equals key runs compute() and displays the full expression, such as 12 + 3 =, on the upper line.
compute() applies pendingOp to acc and the new number. If the operation divides by zero or produces a NaN (not a number) or infinite result, compute() calls setError().
The percent key follows standard desk calculator behavior. With no operation pending, it divides the entry by 100, so 50 % gives 0.5. With an operation pending, it calculates the operand with the following line and completes the calculation immediately.
double operand = (op == ‘+’ || op == ‘-‘) ? acc * cur / 100.0 : cur / 100.0;
For addition and subtraction, the percentage is calculated from the first number, so 200 + 10 % gives 220, and 200 – 10 % gives 180. For multiplication and division, the sketch uses the percentage as a fraction, so 200 * 10 % gives 20, and 200 / 10 % gives 2000.
Touch handling
readTouch() calls ts.getPoint() and immediately sets XM and YP back to outputs so the display bus continues to work. If the pressure falls within the valid range, the function maps the raw values to screen coordinates and returns true.
Setup and loop
setup() opens the serial port at 9600 baud and reads the display controller’s ID. Some write-only shields can’t report an ID and return 0xD3D3, 0x0000, or 0xFFFF instead. In that case, the sketch defaults to 0x9486. setup() then starts the display in portrait mode (rotation 0), resets the calculator, and draws the interface.
loop() waits until it detects a touch. When a valid press lands on the keypad, it calculates the row and column, highlights the key, calls handleKey(), and redraws the readout. It then continues checking the panel until no touch has been detected for 60 ms, and only then redraws the key in its normal color. This release check debounces the input, which prevents a single press from registering as multiple presses.
Results
Video:
You may also like:
Filed Under: Tutorials, Video











Log in to leave a comment:
Lost your password?
Don't have an account? Register here