在 'if' 中编辑全局变量并在 'else if' 中重置回初始值

Global Variable edited in 'if' and reset back to initial in 'else if'

我是 Arduino 编程的新手,我正在尝试能够手动设置时钟。我正在使用旋转传感器 select 小时数,然后使用按钮确认小时数并交换以更改分钟数。但是,目前,当我更改小时和 select 适当的分钟值时,小时值将重置回 00。

我使用的是 Genuino Uno 板,带有 Grove 旋转传感器、LCD 显示屏和按钮,以及底座防护罩。

我希望有人能澄清我的错误并提出为什么我的变量在编辑小时和分钟之间重置。

#include <rgb_lcd.h>

rgb_lcd lcd;

const int colorR = 255;
const int colorG = 20;
const int colorB = 147;

const int analogInPin = 0;  // Analog input pin that the rotary sensor is attached to

int sensorValue = 0;        // value read from the rotary sensor
int outputValue = 0;
int button = 2;
int hour = 00;
int minute = 00;
int button_state = 0;
int minute_temp = 0;
int hour_temp = 0;

void setup() {
  // set up the LCD's number of columns and rows:
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(button, INPUT);

  lcd.setRGB(colorR, colorG, colorB);
  Serial.println("HELLO");

}
void loop() {
  int confirm = 0;
  confirm = digitalRead(button);
  if (button_state == 0) {
    // read the analog in value:
    sensorValue = analogRead(analogInPin);
    // map it to the range of the analog out:
    outputValue = map(sensorValue, 0, 1023, 0, 23);
    // change the analog out value:
    lcd.clear();
    lcd.setCursor(0, 0);

    String hour = String(outputValue);
    if (outputValue < 10) {
      hour = ("0" + hour);
    }

    minute_temp = minute;
    String minute = String(minute_temp);
    if (minute_temp < 10) {
      minute = ("0" + minute);
    }

    lcd.print(hour);
    lcd.print(":");
    lcd.print(minute);

    // wait 10 milliseconds before the next loop
    // for the analog-to-digital converter to settle
    // after the last reading:
    delay(10);
    if (confirm == HIGH){
      button_state = 1;
      delay(1000);
    }
  }
  else if (button_state == 1){
    // read the analog in value:
    sensorValue = analogRead(analogInPin);
    // map it to the range of the analog out:
    outputValue = map(sensorValue, 0, 1023, 0, 59);
    // change the analog out value:
    lcd.clear();
    lcd.setCursor(0, 0);

    String minute = String(outputValue);
    if (outputValue < 10) {
      minute = ("0" + minute);
    }

    hour_temp = hour;
    String hour = String(hour_temp);
    if (hour_temp < 10) {
      hour = ("0" + hour);
    }

    lcd.print(hour);
    lcd.print(":");
    lcd.print(minute);

    // wait 10 milliseconds before the next loop
    // for the analog-to-digital converter to settle
    // after the last reading:
    delay(10);
    if (confirm == HIGH){
      button_state = 5;
    }
  }
}

非常感谢。

您似乎在名为 hour 的 if 语句中有两个不同的变量。您有一个名为 hour 的全局 int,还有一个名为 hour 的本地字符串。本地 String 将隐藏全局 int。永远不要给名为 hour 的全局 int 变量赋予除 0 以外的任何值。在同一作用域内具有相同名称的两个变量肯定会造成混淆。给这两个不同的名字,我想你会看到问题所在。