对于循环,不正确地索引索引
我想在数组中存储键盘的输入,但是我的循环似乎无法正常工作。该程序没有从键盘读取键盘的输入,而是将其添加到数组中,然后递增索引,而是继续打印奇怪的索引。
代码
void loop(){
char arr[3];
for (int i = 0; i<3; i++){
char input = customKeypad.getKey();
if (input != NO_KEY){
do{
arr[i] = input;
Serial.println("Index");
Serial.println(i);
Serial.println("Value");
Serial.println(arr[i]);
} while(input == NO_KEY);
}
}
}
控制台输出
Index
2
Value
1
Index
1
Value
2
Index
1
Value
3
Index
1
Value
4
Index
2
Value
5
Index
2
Value
6
I'd like to store input from keypad in array, but my for loop doesn't seem to work properly. Instead of reading an input from keypad, adding it to the array, and then incrementing the index, the program keep printing weird indexes.
Code
void loop(){
char arr[3];
for (int i = 0; i<3; i++){
char input = customKeypad.getKey();
if (input != NO_KEY){
do{
arr[i] = input;
Serial.println("Index");
Serial.println(i);
Serial.println("Value");
Serial.println(arr[i]);
} while(input == NO_KEY);
}
}
}
Console output
Index
2
Value
1
Index
1
Value
2
Index
1
Value
3
Index
1
Value
4
Index
2
Value
5
Index
2
Value
6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您程序的数据流。这可能是一个评论,但我需要可视化以使其更容易理解。目前尚不清楚您要做什么:
“ alt =”“在此处
net/ nu9vp.png 可以覆盖数组的值。这是你想要的吗?
另请注意,While循环永远不会重复,这从数据流中很明显。
我已经重写了您的程序要在Arduino之外进行测试:
这就是输出,如您的代码所预期
This is the dataflow of your program. This probably could be a comment but I needed the visualization to make it more understandable. It is not really clear what you want to do:
For instance, if you enter, in this order:
You update the indexes #1 and #2, then the iteration (arduino loop) restarts and you can overwrite the values of the array. Is this what you want?
Also notice that the while loop never gets repeated, this is very clear from the dataflow.
I have rewritten you program to be tested outside of Arduino:
And this is the output, as expected from your code