Hello,
I'm trying to save RAM for a sketch, and on top of trying to code more efficiently (use less variables, or variables that use a smallest footprint, be careful about variable scope), I looked into other methods to put into Flash (or program) memory variables that are constant.
So far it seems there is 4 methods to achieve this:
-
using simply a number in the code, as in:
digitalRead(8);
-
using #define, as in:
#define SENSORPIN 8
...
digitalRead(SENSORPIN);
- using const, as in:
const int sensorPin = 8;
...
digitalRead(sensorPin);
- using PROGMEM feature, as in:
#include<avr/pgmspace.h>
...
prog_uchar sensorPin PROGMEM = 8;
digitalRead(pgm_read_byte(&sensorPin));
from what I understand, simply writing explicitely the value is good, exept if you want to use that value in several places, and maybe need to change it later, where #define or const can be better (const being prefered because it allows the compiler to know the type of the variable)
Then I wonder what would really be the use of the last method: PROGMEM
it seems to need more code, is more complicated, so what is the point?
It is advertised for storing arrays of data, such as arrays of strings for instance, but is there a bigger memory use if I use:
Serial.println("text to be displayed");
instead of:
#include<avr/pgmspace.h>
...
prog_char string[] PROGMEM = "text to be displayed";
char buffer[30];
strcpy_P(buffer, (char*)pgm_read_word(&(string)));
Serial.println(buffer);
I would tend to think eventually that the second method is worst, because of the use of the buffer variable.
Am I right, or wrong? or does it allow also to modify variables?
Or maybe is it only desirable for array usage?
is const a problem in that case?
const int numbers[10] = {0,1,2,3,4,5,6,7,8,9};
//then use number[i] in some way