Contents
Intro
My code
My goal
Actual results
Intro
I have debugged my code to this point and figured out that what I am trying to do with this piece of code seems to be the culprit, I have greatly simplified the elements in the code so that it is easier to understand, but the results are the same.
I am trying to create a function that cycles through two rows of information. The first row cycles through the elements of an array (ROW1) using a global variable (R1). The second row cycles through the elements of another array (ROW2) using another global variable (R2), but the elements in Array ROW2 are themselves arrays holding the information for the second row, and being advanced by the first global variable R1. I know the code doesn’t work, although mathematically it should to my mind; I need help understanding why it doesn’t work and how I could possibly make it work.
I have a feeling it has something to do with pointers and arrays, and have referenced several books but I’m still not sure what it is I’m missing.
My Code
int R1 = 0; //Global variable #1
int R2 = 0; // Global variable #2
int X[3] = {0, 1, 2}; //Interim array #1, holding Row2’s info
int Y[3] = {3, 4, 5}; //Interim array #2, holding Row2’s info
int Z[3] = {6, 7, 8}; //Interim array #3, holding Row2’s info
int ROW1[3] = {0, 1, 2}; //Array holding Row1’s info
int ROW2[3] = {X[R1], Y[R1], Z[R1]}; //Array pointing to the Arrays holding Row2’s info
void setup(){
Serial.begin(9600);
Serial.println(“Row1 Row2”);
for(R2 = 0; R2 <3; R2++){ // Advance Row2, 3 times
for(R1 = 0; R1 < 3; R1++){ // Advance Row1, 3 times
Serial.print(ROW1[R1]);
Serial.print(" ");
Serial.println(ROW2[R2]);
}
Serial.println();
}
}
void loop(){}
My Goal
To my mind, and I know this is wrong because it’s not doing what I want, the sketch:
enters the R2 for loop (R2 equals 0), enters the R1 for loop (R1 equals 0), prints out ROW1[0] (equal to 0), prints out ROW2[0] (equal to X[R1], equal to X[0], equal to 0);
advances the R1 for loop (R1 equals 1), prints out ROW1[1] (equal to 1), prints out ROW2[0] (equal to X[R1], equal to X[1], equal to 1);
and so on and so on until the serial monitor reads out like this:
Row1 Row2
0 0
1 1
2 2
0 3
1 4
2 5
0 6
1 7
2 8
Actual Results
The serial monitor is actually reading out like:
Row1 Row2
0 0
1 0
2 0
0 3
1 3
2 3
0 6
1 6
2 6