1

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.

user2119971
  • 71
  • 2
  • 3
  • 5

1 Answers1

2

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 );
Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
  • So would the write function be on the lines of: EEPROM.write(addr, secretCode[1]); addr = addr + 1; How could I increment the secretCode without having to write it 20 times? – user2119971 Mar 18 '13 at 11:07
  • @user2119971 use a for loop as in the examples, or the (untested) code I've added to the answer – Pete Kirkham Mar 18 '13 at 11:20
  • how would i save signed ints? the value i read back is incorrect for negative ints. – FlavorScape Mar 27 '17 at 00:08
  • @FlavorScape read enough bytes in and convert the value to a signed int. e.g http://stackoverflow.com/questions/12240299/convert-bytes-to-int-uint-in-c or http://stackoverflow.com/questions/11819658/byte-to-signed-int-in-c – Pete Kirkham Mar 27 '17 at 10:17
  • haha signed char is useful. i had already implemented it by just storing an additional sign byte at (n-1) I'll have to revisit. – FlavorScape Mar 27 '17 at 17:56