user3742604 user3742604 - 1 year ago 61
C++ Question

Elegant and efficient way to store default values at compile time?

Edit: I understand now what's happening. I was getting the idea that the class and its instantiation were being duplicated in RAM from the fact that when I added one character (one byte) to one of the labels (changing "White Oyster Incubation" to "White Oyster IncubationX"), the Arduino IDE told me that 2 more bytes were being used by the dynamic memory, so I was assuming that one was for the class, and another for the instatiation.

Turns out that for some reason strings from String.h seem to allocate 2 bytes at a time, so the size of a one character string is 2, two character string is 2, three character string is 3, and so forth. The size grows in even numbers.

Of course, now I realize that the class is being stored in the Arduino PROGMEM (EPROM), and the instantiation is in RAM, so the data is not really being duplicating in RAM.

Original question follows:
I'm making a program for an Arduino (atmega328), in which a mushroom greenhouse is to be controlled. There should exist several profiles for temperature and humidity parameters, for different stages in the mushroom development.
I want to have these profiles saved at compile time, and then have the Arduino change between profiles, to act accordingly.
I thought of this:

class GrowingProfile
int idealTemp;

int idealHumi;

String label;

GrowingProfile(int idealTemp,int idealHumi, String label)
this->idealTemp = idealTemp;
this->idealHumi = idealHumi;
this->label = label;
//general methods

class mushroomSpecies1Profiles
GrowingProfile incubationProfile;
GrowingProfile fruitingProfile;

incubationProfile (100, 95, "White Oyster Incubation"),
fruitingProfile (20, 4, "White Oyster Fruiting"){}


And then, in the main code, have an instance of mushroomSpecies1Profiles pass its members as arguments to the methods that determine if the envioronment conditions (set in the profiles) are good or not.

However, this is, in my view, bloated, as effectively the data is duplicated, in the class definition, and then in the instantiation. And given that the microcontroller in question only has 2K of memory...
What would be a good way to not have the data duplicated in the final executable? As if it was a static class in C#?

Answer Source

Assuming your class GrowingProfile is truly constant and unchanging, I would recommend something along these lines:

static const GrowingProfile incubationProfile (100, 95, "White Oyster Incubation");
static const GrowingProfile fruitingProfile (20, 4, "White Oyster Fruiting");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download