ESP-IDFESP32-C3 DevKitM-1Lab virtual

ESP-IDF: deep sleep, RTC memory, NVS

The C3 sleeps and wakes three times; RTC memory and NVS keep their counts through it.

ESP-IDF: deep sleep, RTC memory, NVS in Argynix Lab

The code

main.cC
/* Deep sleep: the board sleeps 2 s and starts again. A boot counter in RTC memory
   (RTC_DATA_ATTR) survives the sleep; a counter in NVS survives everything. After
   three sleeps it stays awake. */
#include <stdio.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_sleep.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "nvs.h"

static const char *TAG = "sleep";
static RTC_DATA_ATTR int boot_count = 0;

void app_main(void)
{
    boot_count++;
    ESP_ERROR_CHECK(nvs_flash_init());
    nvs_handle_t nvs;
    ESP_ERROR_CHECK(nvs_open("storage", NVS_READWRITE, &nvs));
    int32_t wakes = 0;
    esp_err_t err = nvs_get_i32(nvs, "wakes", &wakes);
    if (err == ESP_ERR_NVS_NOT_FOUND) ESP_LOGI(TAG, "first boot: no count in NVS yet");
    wakes++;
    ESP_ERROR_CHECK(nvs_set_i32(nvs, "wakes", wakes));
    ESP_ERROR_CHECK(nvs_commit(nvs));
    nvs_close(nvs);

    esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
    ESP_LOGI(TAG, "boot %d (RTC memory), start %" PRId32 " (NVS), woken by %s", boot_count, wakes,
             cause == ESP_SLEEP_WAKEUP_TIMER ? "the timer" : "power-on");

    if (wakes < 4) {
        ESP_LOGI(TAG, "deep sleep for 2 s");
        esp_sleep_enable_timer_wakeup(2 * 1000 * 1000);
        esp_deep_sleep_start();
    }
    ESP_LOGI(TAG, "staying awake");
}