键盘计算器(多功能按钮)

Keypad calculator (multi-function button)

我正在尝试制作一个带有 3x4 键盘、LCD 和 Arduino 的计算器。我想做一个多功能按钮,按顺序进行4个基本操作:

当我按下:

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

我做了一个开关盒,但它只适用于第一种情况。在其余情况下不会。这是我遇到问题的代码部分:

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;
}

这里的问题是每次你按下运算符,而不是一组运算符进入开关盒。每次都只有'*'goes into the switch case, since getkey function takes in the keypad values one at a time and not as '***'。

因此对于上述情况,您将不得不使用 4x4 键盘,该键盘将具有您可以使用的其他不同字符。

希望对您有所帮助。