Search code examples
arraysarduinokey-value-store

Arduino: Strange values from a int two dimensional array?


This should be pretty straight forward. I'm simply trying to call a two dimensional array in Arduino C*.

I'm used to using nested dictionaries and array in Python. I get it. But I don't get the expected value here. For instance, when I call the index say array[0][0], which is set to 2. I'm getting a value of like 5!

#include "SoftPWM.h"

int pins[5][3] = {
  { 0, 1, 2 },
  { 3, 4, 5 },
  { 6, 7, 8 },
  { 9, 10, 11 },
  { 12, 13, 13 }
};

void setup()
{
  Serial.begin(9600);
  SoftPWMBegin();
  for (int l = 0; l < 5; l++) {
    for (int p = 0; p < 3; p++) {
      SoftPWMSet(pins[1][p], 255);
    }
  }
  SoftPWMSetFadeTime(ALL, 100, 100);
}

void loop()
{
  for (int l = 0; l < 5; l++) {
    Serial.print("l =");
    Serial.println(l);
    for (int p = 0; p < 3; p++) {
      Serial.print("p =");
      Serial.println(p);
      Serial.print("pin =");
      Serial.println(pins[1][p]);

      SoftPWMSetPercent(pins[1][p], 100);
      delay(500);
      SoftPWMSetPercent(pins[1][p], 0);
      delay(500);
    }
  }
}

Output:

l =0
p =0
pin =3 //<-- [0][0] should be 0
p =1
pin =4
p =2
pin =5   //<-- [0][2] should be 2
l =1
p =0
pin =3
p =1
pin =4
p =2
pin =5
l =2
p =0
pin =3   //<-- [2][0] should be 6
p =1
pin =4
p =2
pin =5

Solution

  • That is because you are printing pins[1][p]. Not pins[l][p].

    pins[1][0] is 3. pins[1][2] is 5.