Code an array of structures

rin67630
Posts: 139
Joined: Sun Mar 11, 2018 5:13 pm

Code an array of structures

Postby rin67630 » Sat Dec 23, 2023 10:12 pm

Hi for my project https://github.com/rin67630/Victron_VE_on_Steroids/ I have coded an UDP transmission between modules that works pretty well:

The information is grouped in a single structure payload[]

Code: Select all

struct payload {
  //***Operating Values from Victron/SmartShunt***
  float BatV;  // V   Battery voltage, V
  float BatV1; // V   Battery voltage, V  (Double or half Voltage)
  float BatI;  // I   Battery current, A
  float BatW;  //  BatV*BatI

  float PanV;  // VPV Panel voltage,   V
  float PanI;  // PanW/PanV
  float PanW;  // PPV Panel power,     W

  float LodI;  // IL  Load Current     A
  float LodW;  //  LodI*BatV
  float IOhm;  //  dV / dI

  int ChSt;       // CS  Charge state, 0 to 9
  int Err;        // ERR Error code, 0 to 119
  boolean LodOn;  // LOAD ON Load output state, ON/OFF
} payload;
The structure is copied byte-by-byte to a char array, transmitted over UDP, and at the destination the char array is replicated back into the same structure.

Now I would like to have n copies of that structure in the destination ESP32: an array of n instances of that structure, so the ESP32 could keep track of several senders, indexed by the array.

Has someone an idea on how to code that?
Thank you for your help...

lbernstone
Posts: 826
Joined: Mon Jul 22, 2019 3:20 pm

Re: Code an array of structures

Postby lbernstone » Sun Dec 24, 2023 2:15 am

https://github.com/espressif/arduino-es ... no#L29-L33
Note that the way I am allocating there is not safe. You should malloc (or realloc) the variable to the correct size, as a multiple of sizeof(structure), and then free it when done.
Here's an example of the fill and free of an array, although a char* rather than a struct*
https://github.com/lbernstone/rrdtool_E ... #L122-L141

Who is online

Users browsing this forum: No registered users and 68 guests