Arduino 定时器库和 void 指针

Arduino Timer Library and void pointer

我使用这个定时器库:https://github.com/JChristensen/Timer/tree/v2.1

代码示例:

int afterEvent = t.after(10000, doAfter, (void*)0);

void doAfter(void *context)
{
    Serial.println("stop the led event");
    t.stop(MyledEvent);
}

文档:

The context is a void pointer, so it can be cast to any other data type. Its use is optional, if you don't need it, just code (void*)0 as in the above examples, but be sure that the callback function definitions have it in their argument list

int8_t after(unsigned long duration, void (callback)(void), void* 上下文);

我需要在 "afterEvent" 中添加一个参数(以便将来在 "doAfter" 中使用),我不明白该怎么做。你能解释一下如何在这个 "doAfter" 以及如何将参数放在 "t.after" 上?

我的测试:

int afterEvent = t.after(10000, doAfter(5), (void*)0);

void doAfter(int x, void *context)     { ..code... }

错误:

error: declaration of ‘int type’ shadows a parameter

error: arguments to function ‘void doAfter(int, void*)’error: too few

谢谢

如果您的函数需要任何参数,那么它们需要通过上下文指针传入,这就是它的用途。所以一个简单的例子可能如下:

void doAfter(void *my_param) {
     int x = *(int *)my_param;

     ..... your code here ...

}

然后调用它就可以了

const int input_param = 5;
int afterEvent = t.after(10000, doAfter, (void *)&input_param);

如果您需要传递多个参数,那么可以使用结构来完成:

struct param_list {
     int param1;
     double param2;
};

void doAfter2(void *context)
{
      struct param_list *params = context;

      .... code here can access params with params-> ..

}

struct param_list p = {1, 2.0};
int afterEvent = t.after(10000, doAfter2, (void *)&p);