我正在尝试制作一个带有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;
}