1

I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:

//sender

char mystr[6] = "hello";

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

void loop() {
  Serial.write(mystr);
  delay(1000);
}

And receive it:

//receiver

char mystr[6];

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

void loop() {
  Serial.readBytes(mystr,5);

  if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

    for(int i = 0;i < sizeof(mystr);i++){

      Serial.print(mystr[i]);

      if(i == sizeof(mystr) - 1){
        Serial.print("\r\n");
      }
    }
  }
  delay(1000);
}

That worked fine! But I need to send and receive something like this:

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

How can I do that?

1
  • CSV seems to match your needs. Commented Jan 26, 2018 at 6:29

1 Answer 1

2

Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.

Sending:

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

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      Serial.print(a[x][y]);
   }
}

Receiving

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      a[x][y] = Serial.read(); // Not sure about the exact prototype
   }
}

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.

And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.

If you need dynamic sizes, first send the number of rows and columns and than the values.

In that case instead of 3 and 4 define two constants and use them:

#define NR_ROWS 3
#define NR_COLUMNS 4

int a[NR_ROWS][NR_COLUMNS] = {  
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < NR_ROWS; x++)
{
   for (int y = 0; y < NR_COLUMNS; y++)
   {
      Serial.print(a[x][y]);
   }
}
3
  • 1
    This doesn't work. Serial.print sends the integer as a string and Serial.read() then reads the ASCII value of a single digit. This makes it impossible to receive numbers with multiple digits like 10 and 11. Commented Jan 26, 2018 at 3:05
  • 1
    The code also never checks if Serial.read() returns -1. Which happens because it gets desynced from the previous problem. Or it could happen during the array transmission, because nothing guarantees that the array gets transmitted in a single chunk. Commented Jan 26, 2018 at 3:06
  • And the array consists of int elements, so it should send and receive two bytes per element. Commented Jan 26, 2018 at 3:08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.