Skip to content

Instantly share code, notes, and snippets.

@jerome-labidurie
Created January 29, 2019 10:22
Show Gist options
  • Save jerome-labidurie/72786494760c5aec1cd68826d2a2b75e to your computer and use it in GitHub Desktop.
Save jerome-labidurie/72786494760c5aec1cd68826d2a2b75e to your computer and use it in GitHub Desktop.
Esp8266 DeepSleep & RTC memory save example
/* Deep Sleep - Blink
*
* Blinks the onboard LED, sleeps for 10 seconds and repeats
*
* Connections:
* D0 -- RST
*
* If you cant reprogram as the ESP is sleeping, disconnect D0 - RST and try again
*/
extern "C" {
#include "user_interface.h"
extern struct rst_info resetInfo;
}
// sleep for this many seconds
#define SLEEP_SEC 5
/** program state, must keep between sleeps
*/
typedef struct {
uint32_t blinkTime; /**< delay (ms) for blinking */
uint8_t nBlink; /**< how many blinks ? */
} state_t;
state_t curState;
#define BUTTON D1
/** blink the builtin led
*
* usage:
* pinMode(BUILTIN_LED, OUTPUT);
* blink (5, 100);
*
* @param nb number of blinks
* @param wait delay (ms) between blinks
*/
void blink (uint8_t nb, uint32_t wait) {
// LED: LOW = on, HIGH = off
for (int i = 0; i < nb; i++)
{
digitalWrite(BUILTIN_LED, LOW);
delay(wait);
digitalWrite(BUILTIN_LED, HIGH);
delay(wait);
}
}
void setup() {
// struct rst_info * resetInfo = ESP.getResetInfoPtr();
// set led
pinMode(BUILTIN_LED, OUTPUT);
blink (2, 100);
delay (500);
Serial.begin(115200);
Serial.println("\n\nWake up");
Serial.println (ESP.getResetReason());
Serial.print ("reset:");
Serial.println (resetInfo.reason);
if ( resetInfo.reason == REASON_DEEP_SLEEP_AWAKE ) {
// this was a deep sleep
// get state from rtc memory
ESP.rtcUserMemoryRead (0, (uint32_t*) &curState, sizeof(curState));
blink (curState.nBlink, curState.blinkTime);
// update state for next wakeup
curState.blinkTime += 50;
curState.nBlink++;
} else {
// assume power on, init 1st state
curState.blinkTime += 250;
curState.nBlink = 1;
}
ESP.rtcUserMemoryWrite (0, (uint32_t*) &curState, sizeof(curState));
Serial.printf("Sleep for %d seconds ...\n", SLEEP_SEC);
ESP.deepSleep(SLEEP_SEC * 1000000);
}
void loop() {
// nothing to be done here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment