如何使用4x4键盘将多位数整数输入Arduino
How to input a multi-digit integer into an Arduino using a 4x4 keypad?
我正试图使用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。
相关文章:
- 正在验证c++中用户的整数输入
- 如何用字符终止整数输入循环?
- 以C++为单位将已知数量的整数输入正确读取到向量中
- C++ - 重复 std::getline() 作为用户整数输入?
- C++程序,将整数输入转换为字符的问题
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- 程序终止,而不是继续整数输入验证循环
- 如何在C 中输入未知数的整数输入
- 在C 中遇到了如何从用户输入直到输入的整数输入
- C++ 通过 range for 循环将整数输入到矢量中;随机 0
- 如何在 C++ 中包含整数输入的前面的 0
- 仅接受整数输入
- 拒绝用户整数输入 c++ 中的某个值
- 我想通过scanf将字符和整数输入到结构中
- 此代码段如何验证整数输入
- 验证整数输入C++?
- 循环直到整数输入在所需范围内无法处理非数字字符输入
- 整数输入 拒绝非整数输入并在C++中请求另一个输入
- 如何保存用户的整数输入,并返回字符串值?
- 除 "6" 作为最右边数字的整数输入外,任何整数输入都可以使用,但任何数字(如 ...6.导致分段错误,为什么?