Home > database >  How to process array data in chunks where last chunk may be a partial size
How to process array data in chunks where last chunk may be a partial size

Time:06-23

I have array of integer and I am trying to send this array as a sub block from esp32 to another one. According this code I get on output like this:

output: 1 2 3 4 5

6 7 8 9 10

11 12 0 0 0

the expected output:

1 2 3 4 5

6 7 8 9 10

11 12

How can I update on esp_now_send to get like the expected output? how can I deal with the last sub block if it is less than 5 numbers?

int data={1,2,3,4,5,6,7,8,9,10,11,12};
int ind =0;
int siz=18;
int rang=5;
for (int i = 1; i <= siz; i  ){
  if(ind < siz){   
    esp_now_send(broadcastAddress, (uint8_t *) &data[ind], rang * sizeof(unsigned char));
    Serial.println();
    delay(100);
  }
  ind =rang;
}

CodePudding user response:

The code needs to send up to only the available data. To do that the general approach would be to send full sub-blocks until the last sub-block which may be a partial one. That can be determined by simple maths logic to work out how much the current iteration should send based on how much data is left.

The code changes would be:

  1. Change siz to be the real number of entries in the array: siz = sizeof(data)/sizeof(data[0]).
  2. Change rang in the function call to `(ind rang <= size ? rang : size - ind)``. That is, the size passed to the function call depends on how much data is left.
  • Related