'For loop doesn't increment indexes properly
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
Solution 1:[1]
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:
input==NO_KEY
input!=NO_KEY
input!=NO_KEY
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:
#include "stdio.h"
#define NO_KEY 'a'
int main(){
while(1){
char arr[3];
for (int i = 0; i<3; i++){
char input;
printf("%d -> ", i);
scanf(" %c",&input);
if (input != NO_KEY){
do{
arr[i] = input;
} while(input == NO_KEY );
}
}
for (int i = 0; i <3; i++){ printf("Value %d\n",arr[i]); }
printf("\n Reset\n");
}
}
And this is the output, as expected from your code
0 -> a
1 -> b
2 -> c
Value 127
Value 98
Value 99
Reset
0 -> b
1 -> a
2 -> a
Value 98
Value 98
Value 99
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fra93 |

