2016-09-30 207 views
0

我们目前正在使用Arduino和LCD制作4x3计算器。我们缺少按钮,所以每个操作只有一个按钮,而不是每个操作一个按钮。到目前为止,它只是添加。你怎么办,其中,如果我按下操作按钮一次的东西,它此外,如果两次,减等Arduino计算器(多按钮按)

#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

你可以使用一个数组,以实现这一目标。通过实现具有小延迟的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);