Making a single integer correspond to two arrays in nested for loop

I have a 4x4 grid button grid and I want to print the coordinates of the button pressed in accordance to their x and y axis without making the original value of the grid itself ("whichButtonPressed" in this case) into a 2D array. The coordinates are roughly represented in the two arrays below:

int whichButtonPressed; // the button between 0 - 15 that is pressed
int xAxis[] = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};
int yAxis[] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};

Serial.println(xAxis[whichButtonPressed]);
Serial.println(yAxis[whichButtonPressed]);

This works, but I feel as though it can be simplified in a way to where xAxis and yAxis are only arrays of 4 values each. I would also like to keep xAxis and yAxis as separate arrays instead of one 2D array.
For instance, if I press button 7 (the buttons read from top left to bottom right), I would like it to be something like:

xAxis[3];
yAxis[1];

If I've made my issue clear, how would I accomplish something like this?

coryoryoh:
..... but I feel as though it can be simplified....

depends what you mean by simplified....

your solution while might use the bit more memory is actually probably the simplest one from a processing point of view as it merely a lookup action.

below is another solution which while its doesn't use any arrays (and possibly less memory) is may actually more processing intensive...

void setup() {
  Serial.begin(115200);
}

void loop() {
  int whichButtonPressed = map(analogRead(A0), 0, 1023, 0, 15); // the button between 0 - 15 that is pressed

  //int xAxis[] = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};
  //int yAxis[] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};

  Serial.print("coordinates: (");
  Serial.print(whichButtonPressed%4, DEC); //xAxis
  Serial.print(",");
  Serial.print(whichButtonPressed/4, DEC); //yAxis
  Serial.print(")");

  delay(500); //arbitrary delay
}

hope that helps....

Thank you for your help. I will use the less processor-intensive method.

At least change the array type to byte (or uint8_t) so it uses twice less memory :slight_smile:

sherzaad's solution may be "more processing intensive" but everything is relative, can you as human notice a difference between 10 microseconds and 100 microseconds..? And dividing is "slow", but dividing by 4 is probably optimized as a right shift by 2, and modulo by 4 may be optimized as well, so you shouldn't worry about it.. :slight_smile:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.