0

I'm new to C++ and Arduino, but for a class project, I started working on a simple Arduino calculator. This is the code I have so far:

#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");
    }
}

The code is supposed to ask you to input a number, input a second number, then ask to input an operation (plus, minus, etc.). I have not completed the code for actually inputting an operation yet, but I don't know if that is causing the issue.

Currently, after selecting the second number, it asks to input the second number again. Does anyone know what I've done wrong? (Everything's being outputted to a generic 16x2 LCD display)

4

1 回答 1

0

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

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

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

每次运行循环时,这些变量都会从头开始有效地重新创建 - 它们不会保留以前运行的loop. 所以每次运行selecting都会被重置。1loop

关于变量寿命的一个很好的入门是这个问题

您可以通过制作变量来解决此问题static

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

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

这意味着它们将通过多次运行来保持其价值loop

于 2019-03-05T13:47:57.477 回答