我的数字代码锁项目代码出现问题。我设法让它的大部分工作,但有一个部分令我感到困惑。有一组6个开关,2个按钮,一个绿色LED和红色LED。可以按任何顺序打开或关闭开关。使用第一个按钮(使用引脚8)设置订单后,它将存储为一系列6个变量。这部分工作正常。
下一部分是当按下第二个按钮(引脚12)时检查每个变量是否等于其相应开关的部分。如果全部都是,则绿色LED亮起。否则,用户再次尝试2次。如果用户输入错误的一系列开关3次,则它们将被锁定10秒钟。这是我在正确使用for循环时遇到问题的地方。我使用的是Tinkercad的块编码系统,我不知道如何关闭循环。到目前为止,这是完整的代码:
int switch0 = 0;
int switch1 = 0;
int switch2 = 0;
int switch3 = 0;
int switch4 = 0;
int switch5 = 0;
int switchChecker = 0;
int i = 0;
void setup()
{
pinMode(8, INPUT);
pinMode(A5, INPUT);
Serial.begin(9600);
pinMode(A4, INPUT);
pinMode(A3, INPUT);
pinMode(A2, INPUT);
pinMode(A1, INPUT);
pinMode(A0, INPUT);
pinMode(12, INPUT);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
}
void loop()
{
// this records the values of all 6 switches on 1st
// button press
if (digitalRead(8) == HIGH) {
switch0 = digitalRead(A5);
Serial.println(switch0);
switch1 = digitalRead(A4);
Serial.println(switch1);
switch2 = digitalRead(A3);
Serial.println(switch2);
switch3 = digitalRead(A2);
Serial.println(switch3);
switch4 = digitalRead(A1);
Serial.println(switch4);
switch5 = digitalRead(A0);
Serial.println(switch5);
}
// when the 2nd button is pressed, a for loop is
// started to check if the switches are the same
// order
if (digitalRead(12) == HIGH) {
for (i = 1; i <= 3; i += 1) {
if (digitalRead(A5) == switch0 && (digitalRead(A4) == switch1 && (digitalRead(A3) == switch2 && (digitalRead(A2) == switch3 && (digitalRead(A1) == switch4 && digitalRead(A0) == switch5))))) {
i = 3;
}
}
}
// if the conditions are met, the for loop closes
// and the green LED turns on
if (i == 3) {
digitalWrite(2, HIGH);
digitalWrite(4, LOW);
} else {
delay(10000); // Wait for 10000 millisecond(s)
}
}
最后,如果我想在初始锁定后3次不正确的尝试之后锁定用户,并将该延迟设置为一定的时间,我将如何进行此操作?
答案 0 :(得分:0)
您可以创建一个计算错误尝试次数的全局变量,而不是for循环。然后,如果它等于3,则调用延迟:
char wrongAttemps = 0;
void loop()
{
// this records the values of all 6 switches on 1st
// button press
if (digitalRead(8) == HIGH) {
switch0 = digitalRead(A5);
Serial.println(switch0);
switch1 = digitalRead(A4);
Serial.println(switch1);
switch2 = digitalRead(A3);
Serial.println(switch2);
switch3 = digitalRead(A2);
Serial.println(switch3);
switch4 = digitalRead(A1);
Serial.println(switch4);
switch5 = digitalRead(A0);
Serial.println(switch5);
}
// when the 2nd button is pressed,
// check if the switches are the same order
if (digitalRead(12) == HIGH) {
if (digitalRead(A5) == switch0 && digitalRead(A4) == switch1
&& digitalRead(A3) == switch2 && digitalRead(A2) == switch3
&& (digitalRead(A1) == switch4 && digitalRead(A0) == switch5
) {
// right combination
digitalWrite(2, HIGH);
digitalWrite(4, LOW);
} else {
// wrong combination
digitalWrite(2, LOW);
digitalWrite(4, HIGH);
wrongAttemps++;
if (wrongAttemps == 3) {
delay(10000);
wrongAttemps = 0; // reset attemps
}
}
}
}