Search code examples
arduinokeypad

Keypad calculator (multi-function button)


I am trying to make a calculator with a 3x4 keypad, an LCD, and an Arduino. I want to make a multi-function button that makes the 4 basic operations in that sequence:

When I press:

* this will be (+)
** this will be (-)
*** this will be(*)
**** this will be (/)

I made a switch case but it only works with the first case. It doesn't in the rest of the cases. Here is the part of the code that I have a problem with:

customKey = keypad.getKey();
switch (customKey) {
  case '0'...'9': // This keeps collecting the first value until a operator 
    is pressed "+-*/"
    lcd.setCursor(0, 0);
    first = first * 10 + (customKey - '0');
    lcd.print(first);
    break;

  case '*':
    first = (total != 0 ? total : first);
    lcd.setCursor(8, 0);
    lcd.print("+");
    second = SecondNumber(); // get the collected the second number
    total = first + second;
    lcd.setCursor(0, 1);
    lcd.print(total);
    first = 0, second = 0; // reset values back to zero for next use
    break;

  case '**':

    first = (total != 0 ? total : first);
    lcd.setCursor(8, 0);
    lcd.print("-");
    second = SecondNumber();
    total = first - second;
    lcd.setCursor(0, 1);
    lcd.print(total);
    first = 0, second = 0;
    break;
  case '***':
    first = (total != 0 ? total : first);
    lcd.setCursor(0, 1);
    lcd.print("*");
    second = SecondNumber();
    total = first * second;
    lcd.setCursor(1, 0);
    lcd.print(total);
    first = 0, second = 0;
    break;
  case '****':
    first = (total != 0 ? total : first);
    lcd.setCursor(0, 1);
    lcd.print("/");
    second = SecondNumber();
    lcd.setCursor(1, 0);
    second == 0 ? lcd.print("Invalid") : total = (float) first / (float) second;
    lcd.print(total);
    first = 0, second = 0;
    break;
  case '#':
    keypad.setDebounceTime(100);
    total = 0;
    lcd.clear();
    break;

  }
}

long SecondNumber() {
  while (1) {
    customKey = keypad.getKey();
    if (customKey >= '0' && customKey <= '9') {
      second = second * 10 + (customKey - '0');
      lcd.setCursor(9, 0);
      lcd.print(second);
    }
    if (customKey == '#') break; //return second;
  }
  return second;
}

Solution

  • Here the problem is every time you press the operator, not a set of operators goes into the switch case. Each and every time only '*'goes into the switch case, since getkey function takes in the keypad values one at a time and not as '***'.

    So for the above case you will have to use a 4x4 keypad which will have other distinct characters that you can use.

    Hope this helps.