Bosch Sensortec Community

    Showing results for 
    Search instead for 
    Did you mean: 

    ESP32 Deep Sleep example is sub-optimal, in principle wrong

    ESP32 Deep Sleep example is sub-optimal, in principle wrong



    i might be wrong and if so i apologize but here's my understanding about the deep sleep example reported here

    The assumption here is that:

    1. nextCall represent a future point in time when BSEC run() function shall be called
    2. esp_timer_get_time() is the time since the board woke up
    Said that, the constraint shall be that run() is called as close as possible to the selected sample rate.
    Theoretically the sleep calculation shall be as follow:
    1. Fetch the latest point in time before esp32 goes to deep sleep --> this is done via GetTimestamp()
    2. Calculate how far in time it is the nextCall --> (nextCall - GetTimestamp()) * 1000
    3. Subtract the theoretical amount of time the device would take to wake up and reach the run() function (including bootloader and setup() function)

    The example error is in the last point where the code subtracts esp_timer_get_time() by doing so you are taking into account all the "do other stuff" that are happening in between


    My solution is than



    void loop() {
        int64_t since_start = esp_timer_get_time(); // this is the amount of time the "setup" function takes to run
        if ( {
        // do other stuff
        uint64_t time_us = ((sensor.nextCall - GetTimestamp()) * 1000) - since_start;



    This is also supported by the fact that if ones add


    int64_t calltime = GetTimestamp();


    right before the run() call the delta is not 3s but 2.796s which is roughly 200ms of "//do other stuff" which is erroneously subtracted on the deep sleep time (it wakes up earlier)
    With the change proposed i instead see 3.064ms (not sure why alway 65ms error is there).

    Let me know if i got it wrong, especially in the assumption part

    1 REPLY 1

    Community Moderator
    Community Moderator

    Hi itsmaxdd,

    Your assumption is right, the real misunderstanding is about the function esp_timer_get_time().

    This function is to get time in microseconds since boot, returns number of microseconds since underlying timer has been started.

    Your misunderstood it as getting time stamp.