gpt4 book ai didi

c++ - 如何使用 4x4 键盘将多位整数输入 Arduino?

转载 作者:行者123 更新时间:2023-11-28 05:32:07 24 4
gpt4 key购买 nike

我正在尝试使用 Arduino、键盘和伺服器制作组合锁,但我遇到了障碍。

我找不到在变量中存储 4 位数字值的方法。因为 keypad.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;
}

注意:使用计时器听起来也是可能的(并且可以与终止字符选项结合使用,它们不是唯一的)。这样做的方法是将计时器设置为您选择的持续时间,并在结束时将光标变量重置为 0。

(我从未在 arduino 上编程过,也不知道它的键盘库,但逻辑就在这里,现在由你决定)

关于c++ - 如何使用 4x4 键盘将多位整数输入 Arduino?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com