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

Arduino code section is not repeating at proper time

我是 C++ 和 Arduino 的新手,但对于一个 class 项目,我开始研究一个简单的 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 显示器)

您的问题在这里,在 loop 的开头:

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

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

每次循环都是 运行,这些变量实际上是从头开始重新创建的 - 它们不会保留 loop 之前 运行 的值。因此,每次 loop 为 运行 时,selecting 将重置为 1

有关可变生命周期的入门读物是 this question

您可以通过设置变量 static:

来解决这个问题
void loop(){
    char key = keypad.getKey();

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

这意味着它们将通过 loop 的多个 运行 来保值。