我正试图使用Arduino,键盘和伺服器制作密码锁,但我遇到了一个障碍。
我找不到在变量中存储4位数值的方法。因为键盘。getKey只允许存储一个数字。
在网上浏览了一些后,我在一个论坛上找到了一个解决我的问题的方法,但答案不包括代码样本,我在网上找不到任何其他的东西。
答案说,要么对用户输入数字使用一个时间限制,要么使用一个终止字符(根据他们的说法,这是更好的选择)。
我想知道更多关于这些终止字符以及如何实现它们,或者如果有人能提出一个更好的解决方案,我将不胜感激。
提前感谢,
要存储4位值,最简单和简单的方法可能是使用大小为4的数组。假设keypad.getKey
返回一个int,你可以这样做:int input[4] = {0};
.
您需要一个游标变量,以便在按下一个键时知道需要写入数组的哪个槽,因此您可以执行类似这样的循环:
int input[4] = {0};
for (unsigned cursor = 0; cursor < 4; ++cursor) {
input[cursor] = keypad.getKey();
}
如果你想使用一个终止字符(假设你的键盘有0-9和a -F键,我们可以说F是终止键),代码会改变为:
bool checkPassword() {
static const int expected[4] = {4,8,6,7}; // our password
int input[4] = {0};
// Get the next 4 key presses
for (unsigned cursor = 0; cursor < 4; ++cursor) {
int key = keypad.getKey();
// if F is pressed too early, then it fails
if (key == 15) {
return false;
}
// store the keypress value in our input array
input[cursor] = key;
}
// If the key pressed here isn't F (terminating key), it fails
if (keypad.getKey() != 15)
return false;
// Check if input equals expected
for (unsigned i = 0; i < 4; ++i) {
// If it doesn't, it fails
if (expected[i] != input[i]) {
return false;
}
}
// If we manage to get here the password is right :)
return true;
}
现在你可以在你的主函数中使用checkPassword函数,像这样:
int main() {
while (true) {
if (checkPassword())
//unlock the thing
}
return 0;
}
NB:使用计时器听起来也可能(并且可以与终止字符选项组合,它们不是排他的)。要做到这一点,方法是将计时器设置为您选择的持续时间,并在它结束时将光标变量重置为0。
(我从未在arduino上编程,不知道它的键盘库,但逻辑在这里,现在由你决定)
在注释OP中表示需要单个数字。典型的算法是,对于输入的每个数字,将累加器乘以10,然后将输入的数字相加。这假定键项是ASCII,因此从中减去'0'得到数字0..9
而不是'0'..'9'
。
#define MAXVAL 9999
int value = 0; // the number accumulator
int keyval; // the key press
int isnum; // set if a digit was entered
do {
keyval = getkey(); // input the key
isnum = (keyval >= '0' && keyval <= '9'); // is it a digit?
if(isnum) { // if so...
value = value * 10 + keyval - '0'; // accumulate the input number
}
} while(isnum && value <= MAXVAL); // until not a digit
如果您有退格键,您只需将累加器value
除以10。