Clarification of use of structs with Arduino and storing structs in PROGMEM

arduino, c

Solution

- When using the semi-colon syntax, the size of the struct will be the sum of all its fields.

I think its possible using this syntax: (http://www.arduino.cc/en/Reference/PROGMEM)

LED leds PROGMEM;

Yes they are, the syntax is as you wrote in your question.

Yes you may:

typedef struct { struct otherStruct; };

Yes you can do that using masks. For example:

for (int i = 0, byte cur = s1 & 1; ; i < numOfFieldsInStruct; i++, cur = (s1<<i)&1) {
    ....
}

Regarding your last comment to this answer, let me propose the following solution:

Organize the leds in a way that addressing them won't take up memory (like in the question - the LED struct takes memory for addressing). Instead, you can address the leds using their position in an array and in the struct like this:

typedef struct {
    byte LED1 : 1;
    byte LED2 : 1;
    byte LED3 : 1;
    byte LED4 : 1;
    byte LED5 : 1;
    byte LED6 : 1;
    byte LED7 : 1;
    byte LED8 : 1;
} LED_ROW;

LED_ROW leds[256];

leds[0].LED1 = 1; // turn led at row 0, col 0 to 1
leds[0].LED5 = 1; // turn led at row 4, col 0 to 1
led[100].LED3 = 1; // turn led at row 2, col 100 to 1
...
// and so on

You may consider arranging the array differently, with 256 items in the struct and 8 items in the array so the rows will be refered to by [] and the cols after the dot, like so:

leds[0].LED3 = 1; // turn on led at row 0, col 2 to 1

Problem

(Because of the limited memory available on most Arduino boards, I've sometimes run into problems using valid C/C++ code, so this question is specifically about any issues on using structs on Arduino.) I've seen example code of using structs in Arduino but no discussion of memory reqs. - Is the size of a struct simply the sum of the data types of its fields? - Is storing structs in PROGMEM an option? Are there access speed issues? - Are the fields of a struct writable (e.g. example below `s1.LED1.state = 0;`) (though not if stored in PROGMEM, of course). - Can I define a field of a struct as another (different type) struct? - Is it possible to iterate through a struct using `for..in` or by index? My use case is that I have 64 LEDs driven by a MAX7219 chip. Because of the requirements of the physical wiring layout, it would be convenient to organize the LED order in a more logical way using structs in order to make the programming easier/more coherent. ``` typedef struct { byte row : 6; byte col : 128; byte state : 1; } LED; ``` ``` typedef struct { LED LED1 : {1,1,1}; LED LED2 : {1,2,1}; LED LED3 : {1,4,1}; LED LED4 : {1,8,1}; LED LED5 : {1,16,1}; LED LED6 : {1,32,1}; LED LED7 : {1,64,1}; LED LED8 : {1,128,1}; } LED_SECTION; ``` ``` LED_SECTION s1; s1.LED1.row = 1; ``` ``` s1.LED1.state = 0; ```

Original source

Related problems