问题
When the Arduino is powered up it has an int array stored in the flash, for example:
int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
When the program button is pressed, it then waits for the piezo to pick up a knock and this array then changes to, for example:
int secretCode[maximumKnocks] = {25, 50, 25, 50, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
(based on http://grathio.com/assets/secret_knock_detector.pde)
How would I write and read the array to/from the EEPROM? This is completely new to me, so any help would be great.
回答1:
You would write the values using the EEPROM.Write function - loop over the array, writing each value in turn.
Assuming you don't need to store integer values > 254 ( in which case you'd have to write two bytes for each element in secretCode ), this would be:
for ( int i = 0; i < maximumKnocks; ++i )
EEPROM.write ( i, secretCode [ i ] );
Having written them, you would read them back on start-up using the read function in the setup. If the values in the EEPROM are 0xff, which they will be when you first flash the chip, don't copy them into the secret code.
if ( EEPROM.read ( 0 ) != 0xff )
for (int i = 0; i < maximumKnocks; ++i )
secretCode [ i ] = EEPROM.read ( i );
来源:https://stackoverflow.com/questions/15474272/arduino-eeprom-write-and-read-array