// 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
  }
}
