gpt4 book ai didi

c - Arduino 定时器库和 void 指针

转载 作者:行者123 更新时间:2023-11-30 15:16:34 24 4
gpt4 key购买 nike

我使用这个计时器库: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(无符号长持续时间,void (回调)(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);

关于c - Arduino 定时器库和 void 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com