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

How to input a multi-digit integer into an Arduino using a 4x4 keypad?

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

我找不到在变量中存储 4 位数值的方法。因为 keypad.getKey 只允许存储一个数字。

在互联网上浏览了一番之后,我在论坛上找到了解决我的问题的方法,但答案不包括代码示例,而且我在互联网上找不到任何其他信息。

答案说要么使用用户输入数字的时间限制,要么使用终止字符(根据他们的说法,这将是更好的选择)。

我想知道更多关于这些终止字符的信息以及如何实现它们,或者是否有人可以提出更好的解决方案,我将不胜感激。

提前谢谢你,

存储 4 个数字值,最简单和天真的方法可能是使用大小为 4 的数组。假设 keypad.getKey returns一个整数,你可以这样做: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。