【发布时间】:2023-01-18 05:40:56
【问题描述】:
我目前正在为带有键盘和 16x2 LCD 实现的 GUI 编写一些 arduino 代码。我的部分程序需要输入密码才能访问 Arduino 上的某些内容,但我似乎无法弄清楚如何获取我保存的密码并提供输入以正常工作。
String pswd = "0000";
char* Input(int Length, byte clmn, byte row) {
char output[Length];
int i = 0;
while (i < Length) {
char KeyPress = keypad.getKey();
lcd.setCursor(clmn,row);
if (KeyPress == '0' ||
KeyPress == '1' ||
KeyPress == '2' ||
KeyPress == '3' ||
KeyPress == '4' ||
KeyPress == '5' ||
KeyPress == '6' ||
KeyPress == '7' ||
KeyPress == '8' ||
KeyPress == '9') {
output[i] = KeyPress;
lcd.print(KeyPress);
i++;
clmn++;
lcd.setCursor(i+1,0);
lcd.cursor();}
}
delay(3000);
Serial.println(output);
return output;
}
bool Is_Psswrd() {
bool Passed = false;
char *Test;
String test;
CH2 = true;
while (CH2) {
say("Password: ",0,0);
Test = Input(4, 10, 0);
test = Test;
if (test==pswd) {
Passed = true;
CH2 = false; }
else {
for(int i = 0; i < 3; i++) {
lcd.clear();
say("Incorrect ",0,0);
delay(200); } }
}
return Passed;
}
void setup() {
Is_Psswrd();
}
void loop() {}
我已经尝试了很多不同的方法来保存、输入和检查字符,有些比其他的更笨拙。我最初的计划是将所有变量保存为 char* 变量并使用 strcmp() 函数,但这似乎不起作用(strcmp() 一直输出“144”),我了解到我需要 const char* 来创建函数好好工作。我已经提供了我认为访问该问题所需的代码,但如果您需要其余代码,我可以将其粘贴。
我对 C++ 很陌生。我的大部分代码都是用 Java 编写的。有人可以解释需要做什么才能让两个 char*/strings 以我想要的方式进行比较。我愿意完全重写我的功能我只需要实现它。
【问题讨论】:
-
OT:
test = Test这是完全不可读的。不要使用仅区分大小写的标识符 -
这里的问题似乎不是字符串比较。问题似乎是嵌入式系统异步输入。第一个问题似乎是您正在冻结
setup()等待用户输入。 -
在函数
Input(...)中,您返回一个指向自动变量的指针(当函数返回时它超出范围)。那行不通的。你可以通过将char output[Length];移动到全局范围(文件顶部)来修复此问题,并且不从Input返回任何内容。 -
char output[Length];——这不是有效的 C++。 C++ 中的数组的大小必须由编译时值而不是运行时值表示。我建议在整个代码中使用String,并尽量减少(如果不是完全放弃)显式使用char *。 -
不幸的是,这看起来像是在尝试使用最难的语言之一,C++,作为一种工具来做“很酷的事情”,而这一切都没有正确地学习 C++。这通常不会结束太好。代码中存在基本的根本性错误,这些错误不会出现在经验丰富的 C++ 程序员(或已经学习了 C++ 基础知识的程序员)身上。