Devices & Components
Arduino Uno Rev3
male to female jumper wires
Membrane Keypad
I2C LCD display
Male/Male Jumper Wires
Hardware & Tools
Breadboard, 830 Tie Points
Software & Tools
Arduino IDE
Project description
Code
Code for Keypad Calculator
1#include <Wire.h> 2#include <LiquidCrystal_I2C.h> 3#include <Keypad.h> 4 5LiquidCrystal_I2C lcd(0x27, 16, 2); 6 7// Keypad config 8const byte ROWS = 4; 9const byte COLS = 4; 10char keys[ROWS][COLS] = { 11 {'1','2','3','+'}, 12 {'4','5','6','-'}, 13 {'7','8','9','*'}, 14 {'C','0','=','/'} 15}; 16 17byte rowPins[ROWS] = {9, 8, 7, 6}; 18byte colPins[COLS] = {5, 4, 3, 2}; 19 20Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); 21 22String expression = ""; 23 24void setup() { 25 lcd.begin(16, 2, LCD_5x8DOTS); 26 lcd.backlight(); 27 lcd.clear(); 28 lcd.print("Calculator Ready"); 29 delay(1500); 30 lcd.clear(); 31} 32 33void loop() { 34 char key = keypad.getKey(); 35 36 if (key != NO_KEY) { 37 if ((key >= '0' && key <= '9') || key == '+' || key == '-' || key == '*' || key == '/') { 38 if (expression.length() < 16) { 39 expression += key; 40 lcd.setCursor(0, 0); 41 lcd.print(expression); 42 } 43 } else if (key == '=') { 44 float result = evaluateWithPrecedence(expression); 45 lcd.setCursor(0, 1); 46 lcd.print("= "); 47 lcd.print(result); 48 expression = ""; 49 } else if (key == 'C') { 50 expression = ""; 51 lcd.clear(); 52 } 53 } 54} 55 56// Evaluates an expression with operator precedence 57float evaluateWithPrecedence(String expr) { 58 float numbers[10]; // supports max 10 numbers 59 char operators[10]; // supports max 9 operators 60 int numIndex = 0, opIndex = 0; 61 String temp = ""; 62 63 // Parse numbers and operators 64 for (int i = 0; i < expr.length(); i++) { 65 char c = expr.charAt(i); 66 if (c >= '0' && c <= '9') { 67 temp += c; 68 } else { 69 numbers[numIndex++] = temp.toFloat(); 70 temp = ""; 71 operators[opIndex++] = c; 72 } 73 } 74 numbers[numIndex] = temp.toFloat(); 75 76 // First pass: *, / 77 for (int i = 0; i < opIndex; i++) { 78 if (operators[i] == '*' || operators[i] == '/') { 79 float a = numbers[i]; 80 float b = numbers[i+1]; 81 float result = (operators[i] == '*') ? a * b : (b != 0 ? a / b : 0); 82 83 numbers[i] = result; 84 for (int j = i + 1; j < numIndex; j++) { 85 numbers[j] = numbers[j + 1]; 86 } 87 for (int j = i; j < opIndex - 1; j++) { 88 operators[j] = operators[j + 1]; 89 } 90 numIndex--; 91 opIndex--; 92 i--; // re-check this position 93 } 94 } 95 96 // Second pass: +, - 97 float total = numbers[0]; 98 for (int i = 0; i < opIndex; i++) { 99 if (operators[i] == '+') total += numbers[i + 1]; 100 else if (operators[i] == '-') total -= numbers[i + 1]; 101 } 102 103 return total; 104}
Downloadable files
Keypad circuit diagram
Epic Hillar-Turing (1).png

Comments
Only logged in users can leave comments