eeprom3.cpp

Normally, when writing to EEPROM, you can just make the eepromWrite call, and then go on about your business, but there is one possible 'gotcha'. EEPROM write operations actually take a fair bit of time -- on the order of several milliseconds -- and the eepromWrite function will return before the write operations have completely finished!

Usually that's a good thing, but, if the board is about to power itself down somehow, it can be a trap. In such a case, one needs to wait until the write actually completes before powering down, and the eepromWait() function will do that.

Given that standard IXM boards have no way to power themselves down deliberately, it's hard to show a simple example of this risk. In this example, a sketch writes to EEPROM and then reenters the bootloader to 'reboot'. Since reenterBootloader() doesn't actually power down the board, the eepromWait() isn't strictly needed here -- the EEPROM will finish its write cycle even while the rest of the system is rebooting -- but it's cautionary and comforting, and harmless given that an extra few milliseconds before rebooting won't bother anybody.

// Eeprom sketch 3: Reboot on 'b' packet and count those reboots

#define DATA_ADDR 2001   // Any number in 0..eepromSize()-4 (since sizeof(n) is 4)

u32 readCount() {
  u32 n;
  eepromRead(DATA_ADDR, (u8*) &n, sizeof(n));  // Read count from EEPROM
  return n;
}

void writeCount(u32 n) {
  eepromWrite(DATA_ADDR, (u8*) &n, sizeof(n)); // Write given value
  eepromWait();                                // Let write finish - just to be safe
}

void doReboot(u8 * packet) {
  writeCount(readCount()+1);                   // Increment count
  reenterBootloader();                         // And die
}

void setup() {
  Body.reflex('b',doReboot);                   // Create the reflex
}

void loop() { 
  if (buttonDown()) {
    println(readCount());                      // Print current count
    while (buttonDown()) delay(1);             // Wait for button up
  }
}

Generated on Fri Apr 22 06:54:10 2011 for SFB by doxygen 1.5.9