我们目前正在使用Arduino和LCD制作一个4x3计算器。我们缺少按钮,因此每次操作不是一个按钮,所有操作只有一个按钮。到目前为止,它只是添加。你怎么做的事情,如果我按下OPERATION按钮一次,它会增加,如果两次,减法等。
#include <Keypad.h>
#include <LiquidCrystal.h> //import lcd library
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //lcd pins
//LiquidCrystal lcd(5,4,3,2,1,0);
const byte ROWS = 4; // four rows
const byte COLS = 3;
//define the keymap
char keys [ROWS] [COLS] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'+', '0', '='}
};
byte rowPins[ROWS] = {
9 ,8 ,7 ,6}; //connect keypad ROW1, ROW2, ROW3, ROW4 to these arduino pins
byte colPins[COLS] = {
13, 10, 1};
//create the keypad
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
//variables declaration
boolean valOnePresent = false;
boolean next = false;
boolean final = false;
String num1, num2;
int ans;
char op;
void setup(){
lcd.begin(16,2);
lcd.setCursor(2,0);
lcd.print("Calculator");
delay(2500);
lcd.clear(); //clears the LCD screen and positions the cursor in the upper-left corner.
}
void loop(){
char key = myKeypad.getKey();
if (key != NO_KEY && (key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0')){
if (valOnePresent != true){
num1 = num1 + key;
int numLength = num1.length();
lcd.setCursor(15 - numLength, 0); //to adjust one whitespace for operator
lcd.print(num1);
}
else {
num2 = num2 + key;
int numLength = num2.length();
lcd.setCursor(15 - numLength, 1);
lcd.print(num2);
final = true;
}
}
else if (valOnePresent == false && key != NO_KEY && (key == '/' || key == '*' || key == '-' || key == '+')){
if (valOnePresent == false){
valOnePresent = true;
op = key;
lcd.setCursor(15,0);
lcd.print(op);
}
}
else if (final == true && key != NO_KEY && key == '='){
if (op == '+')
{
ans = num1.toInt() + num2.toInt();
}
else if (op == '='){
ans = num1.toInt() + num2.toInt();
}
/* else if (op == '+')
{
answ = num1.toInt() - num2.toInt();
}
*/
lcd.clear();
lcd.setCursor(15,0);
lcd.autoscroll();
lcd.print(ans);
lcd.noAutoscroll();
}
}
答案 0 :(得分:0)
您可以使用数组来完成此操作。通过实现具有小延迟的while循环,您可以在每次按下按钮时继续遍历数组中的位置,直到数组超时。以下是一些可以用来实现它的例子。
char ops [4] = {'+','-','/','*'};
int del = 2500;
int strt = millis();
int location = 0;
while (millis() - strt < del) {
key = myKeypad.getkey();
if (key == '+') {
if (loc == 3) {
location = 0;
}
else {
location += 1;
}
strt = millis();
}
}
op = ops(location);