ESP32开发(二)—— lambda捕获函数&std::function (附代码)

目录

一、问题引入

二、lambda函数简要介绍

基础语法:

Lambda的特点

三、关于lambda函数的详细介绍:

四、示例代码


一、问题引入

        考虑到这样一个场景,你需要在ESP32软件定时器的回调函数中输出一些值,比如说是闹钟播报具体内容或者是输出一些日志,但是你在交互中添加闹钟时所输入的变量作为参数如果在回调函数响应之前就有更新,那应该怎么办,我想要的输入参数值就有可能会被更改/覆盖?
        有人说,那就一个回调函数就单独使用一个变量,这样固然是可以的,但是当回调函数一多起来就很麻烦了。这个时候我们就可以使用Lambda的上下文捕获功能+赋值给std::function,这样就可以在添加闹钟(回调函数未响应)的时候就已经把这个瞬间的变量值捕获进去;这样的话,即使变量值有更新也不会影响当前回调函数所捕获的参数值。

二、lambda函数简要介绍

        Lambda 函数是 C++11 引入的一种轻量级函数对象,常用于简洁地定义匿名函数,可作为回调传入算法、线程、定时器等功能中。


  • 基础语法:

[capture](parameter_list) -> return_type {
    // function body
};

其中:

  • capture:捕获外部变量的方式(重点,见下文)

  • parameter_list:传入参数列表(可省略)

  • return_type:返回类型(可省略,编译器推导)

  • {}:函数体


  • Lambda的特点

  1. 可以内联定义函数逻辑,无需单独命名函数。

  2. 支持捕获外部变量,形成闭包(Closure)。

  3. 可赋值给 std::function 或自动推导变量。

  4. 可以像普通函数一样调用。

三、关于lambda函数的详细介绍:

https://www.runoob.com/cplusplus/cpp-functions.htmlhttps://www.runoob.com/cplusplus/cpp-functions.html

四、示例代码

  • 注意:
// std::function需要引用#include 

#include 
#include 
#include 
#include "esp_timer.h"

// Context struct for passing lambda to timer
struct TimerCallbackContext {
    std::function func;
};

// Function to print alarm message
void PrintMessage(const char* output_text) {
    printf("%s\n", output_text);
}

// Set up a one-shot timer to trigger a message after delay
void SetupTimerWithMessage(std::string message_text, int64_t delay_seconds) {
    // Allocate context with lambda callback
    TimerCallbackContext* ctx = new TimerCallbackContext{
        .func = [message_text]() {
            PrintMessage(message_text.c_str());
        }
    };

    // Define timer arguments
    esp_timer_handle_t timer;
    esp_timer_create_args_t timer_args = {
        .callback = [](void* arg) {
            auto* ctx = static_cast(arg);
            if (ctx && ctx->func) {
                ctx->func();         // Invoke callback
                delete ctx;          // Free memory
            }
        },
        .arg = ctx,
        .name = "message_timer"
    };

    // Create and start one-shot timer
    esp_timer_create(&timer_args, &timer);
    esp_timer_start_once(timer, delay_seconds * 1000000); // Convert seconds to microseconds
}

你可能感兴趣的:(ESP32,ESP32,嵌入式开发,智能硬件,单片机,物联网)