Arduino代码部分未在适当的时间重复

时间:2019-03-04 20:51:13

标签: arduino arduino-c++

我是C ++和Arduino的新手,但是对于一个班级项目,我开始研究简单的Arduino计算器。这是我到目前为止的代码:

#include <Keypad.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(5, 4, 3, 2, A4, A5);



const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {A0, A1, 11, 10}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad
int LCDRow = 0;


Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );


void setup(){
    Serial.begin(9600);
    lcd.begin(16, 2);
    lcd.setCursor(LCDRow, 0);
    lcd.print("Enter first");
    lcd.setCursor (++LCDRow, 15);
    lcd.print("number");
}

void loop(){
    char key = keypad.getKey();


    int firstNumber = 0;
    int selecting = 1;
    int secondNumber = 0;

    if (key && selecting == 1){
        key = key - 48;
        firstNumber = key;
        lcd.setCursor(LCDRow, 0);
        lcd.clear();
        selecting = 2;
        lcd.print("Selected");
        lcd.setCursor (++LCDRow, 15);
        lcd.print(firstNumber);
        delay(2000);
        lcd.clear();
    } 
    key =  0;
    if (selecting == 2){
        lcd.print("Enter second");
        lcd.setCursor (++LCDRow, 15);
        lcd.print("number");
    }

    if (key && selecting == 2){
        key = key - 48;
        secondNumber = key;
        lcd.setCursor(LCDRow, 0);
        lcd.clear();
        selecting = 3;
        lcd.print("Selected");
        lcd.setCursor (++LCDRow, 15);
        lcd.print(secondNumber);
        delay(2000);
        lcd.clear();
    } 
    key =  0;
    if (selecting == 3){
        lcd.print("Enter");
        lcd.setCursor (++LCDRow, 15);
        lcd.print("operation");
    }
}

该代码应要求您输入一个数字,输入第二个数字,然后要求输入一个运算(加号,减号等)。我尚未完成用于实际输入操作的代码,但是我不知道这是否是导致问题的原因。

当前,在选择第二个数字后,它要求再次输入第二个数字。有人知道我做错了吗? (一切都输出到通用的16x2 LCD显示器上)

1 个答案:

答案 0 :(得分:0)

您的问题在loop的开头:

void loop(){
    char key = keypad.getKey();

    int firstNumber = 0;
    int selecting = 1;
    int secondNumber = 0;

每次运行时间循环时,都会从头开始有效地重新创建这些变量-它们不会保留loop的先前运行中的值。因此,每次运行selecting时,1将重置为loop

可变寿命的一个很好的入门书是this question

您可以通过设置变量static来解决此问题:

void loop(){
    char key = keypad.getKey();

    static int firstNumber = 0;
    static int selecting = 1;
    static int secondNumber = 0;

这意味着他们将通过多次运行loop来保持自己的价值。