Clarification of the use of structures with Arduino and preservation of structures in PROGMEM

(Due to the limited memory available on most Arduino boards, I sometimes run into problems using valid C / C ++ code, so this question specifically concerns any problems with using Arduino structures.)

I saw an example of code for using structures in Arduino , but does not discuss memory issues.

  • Is the size of the structure just the sum of the data types of its fields?
  • Is saving structures in PROGMEM an option? Are there any problems with access speed?
  • Are the structure fields writable (for example, the example below s1.LED1.state = 0; ) (although not saved in PROGMEM, of course).
  • Is it possible to define the structure field as a structure of another type (of another type)?
  • Is it possible to iterate through a structure to use for..in or by index?

My use case is that I have 64 LEDs controlled by a MAX7219 chip. Due to the requirements of the physical wiring layout, it would be more convenient to arrange the order of the LEDs in a more logical way using structures in order to simplify / more harmonize programming.


  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; 
+7
source share
1 answer
  • When using colon syntax, the size of the structure will be the sum of all its fields.
  • I think it is possible to use this syntax: ( http://www.arduino.cc/en/Reference/PROGMEM )

     LED leds PROGMEM; 
  • Yes, they are syntax, as you wrote in your question.

  • Yes, you can:

    typedef struct {struct otherStruct; };

  • Yes, you can do this with masks. For example:

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

As for your last comment on this answer, let me suggest the following solution:

Organize the LEDs so that their addressing does not take up memory (for example, in the question - the LED structure accepts memory for addressing). Instead, you can access the LEDs using their position in the array and in a structure 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 can consider placing the array in different ways, with 256 elements in the structure and 8 elements of the array, so the strings will be referenced by [] and cols after the point, for example:

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

All Articles