我刚开始编程我的Arduino,我试图能够手动设置时钟。我正在使用旋转传感器选择小时数,然后使用按钮确认小时数并交换以更改分钟数。但是,目前,当我更改小时数并选择适当的分钟值时,小时值将重置为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;
}
}
}
非常感谢。
答案 0 :(得分:0)
您似乎在名为hour的if语句中有两个不同的变量。你有一个名为hour的全局int,你也有一个名为hour的本地String。本地String将影响全局int。您永远不会将名为hour的全局int变量赋予除0以外的任何值。在同一范围内具有两个具有相同名称的变量是确定混淆的方法。给出这两个不同的名字,我想你会看到这个问题。