Hello everyone,
I would like to know if I can simplify this part of my programm, using a "for" loop :
void fct_assign_password_4_to_EEPROM
{
EEPROM.write(31,l1p4);
EEPROM.write(32,l2p4);
EEPROM.write(33,l3p4);
EEPROM.write(34,l4p4);
EEPROM.write(35,l5p4);
EEPROM.write(36,l6p4);
EEPROM.write(37,l7p4);
EEPROM.write(38,l8p4);
EEPROM.write(39,l9p4);
EEPROM.write(40,l10p4);
}
I tried this, but I don't know if it will really work :
for (int n=1; n<=40 ; n++)
{
EEPROM.write(30+n,lnp4); // here, I don't know if the formula "lnp4" will really work
}
Thank you so much in advance !
Did you try it? What happened or why not?
It won't work. But is you change lnp4 to lp4[n] and declare an array of whatever datatype lnp4 is then it will.
Why do you want to do it? There are many instances where the use of arrays is the better solution. This does not appear to be one of them. It's not as if you'll be updating the values every pass through loop(), or if you'll be accessing indexed values in some other calculation at regular intervals. The use of EEPROM is generally for persistent data and is written to only when necessary (to avoid pre-mature death). Another thing to consider is optimization. Always a toss-up between speed and code size, but if speed is the higher priority, loops are treated exactly opposite to what you're trying to do. If the compiler sees a short loop used sparingly (and is optimized for speed) it will 'un-roll' the loop into sequential operations as it is faster at the processor level to drop through instructions than to repeatedly test loop conditions and branch back to the start label. This of course, makes the code larger but again; good, fast, cheap - pick two.
Put the data in an array and use a single EEPROM.put() to save it and EEPROM.get() to retrieve it. No need for a for loop or multiple EEPROM.write()s and read()s
adwsystems:
It won't work. But is you change lnp4 to lp4[n] and declare an array of whatever datatype lnp4 is then it will.
Thank you for this response. I had an intuition that I had to use the arrays, but I have no idea of how it works.
How this part of the program would look like if we use the arrays ?
Assuming the password is a 10 character array (note they are zero-based);
char lp4[11] = "password12";
void fct_assign_password_4_to_EEPROM
{
for(byte i = 0; i < 10; i++)
{
EEPROM.update((31 + i), lp4[i]);
}
}
Note to use update rather than write as this will only write if the contents are different. Takes a bit longer, but save undue killing write cycles.
DKWatson:
char lp4[11] = "password12";
if I understand well, this is an array with less than 11 characters. The first character is 'p', the second 'a', the third 's', etc.
So the variable lp4[3], for instance, is, in this context, equivalent to "lp4s".
I am right ?
Yes. The 11th character needs to be there as a terminator (\0). A char array of length n will hold n-1 characters.