下面的程序使用键盘和 arduino 来测试输入是否等于密码。每当按下“#”时,都会检查输入,然后存储输入的变量将重置为空字符串(char input[257] = "")。然后程序循环回到 void loop() 代码块的开头。当我的程序循环回到“void loop()”代码块的开头时,我遇到了问题。当我将输入重置为空字符串时,输入将重置为空字符串。但是,当程序循环时,输入的值会更改为之前的值。因此,如果我最初输入“123abc”并点击“#”,程序会告诉我输入不正确,然后程序会将变量重置为空字符串,但是当程序循环时,存储空字符串的变量会变回“123abc”。发生了什么?为什么变量不保持为空字符串?
#include <Keypad.h>
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] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad
char password[9] = "3994A", input[257]="";
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int x;
void setup(){
Serial.begin(9600);
}
void loop(){
x = 0;
Serial.println(input);
while (1)
{
char key = keypad.getKey();
if (key)
{
if (key == '#')
{
break;
}
input[x] = key;
x+=1;
}
}
if (strcmp(password,input) == 0)
{Serial.println("Access Granted");
}
else
{Serial.println("Access Denied");
}
char input[257] = "";
Serial.println(input);
}