我可以使用:
while(1==1)
{
delay(10);
f(); // <-- function to be called every 10 seconds
otherfunctions();
}
但这只需要 10 多秒,因为其他函数需要一些时间才能执行。是否有考虑到其他函数所用时间的延迟函数,以便我可以每 10 秒准确调用一次 f()
?
我听说这可以通过一个可以在头文件中找到的巧妙函数来完成,但我记不起是哪一个了。我认为它可能是 #include mbed.h
但即使该函数包含在此头文件中,我也不知道它叫什么或如何搜索它。
有人知道可以实现我所追求的功能吗?
最佳答案
您当然应该先阅读 mbed handbook .它不是一个大型 API,您可以非常快速地了解它。
mbed 平台是一个 C++ API,因此您需要使用 C++ 编译。
有几种方法可以实现你所需要的,一些例子:
使用 Ticker
类:
#include "mbed.h"
Ticker TenSecondStuff ;
void TenSecondFunction()
{
f();
otherfunctions();
}
int main()
{
TenSecondStuff.attach( TenSecondFunction, 10.0f ) ;
// spin in a main loop.
for(;;)
{
continuousStuff() ;
}
}
使用 wait_us()
和 Timer
类:
#include "mbed.h"
int main()
{
Timer t ;
for(;;)
{
t.start() ;
f() ;
otherfunctions() ;
t.stop() ;
wait_us( 10.0f - t.read_us() ) ;
}
}
使用 Ticker
类,另一种方法:
#include "mbed.h"
Ticker ticksec ;
volatile static unsigned seconds_tick = 0 ;
void tick_sec()
{
seconds_tick++ ;
}
int main()
{
ticksec.attach( tick_sec, 1.0f ) ;
unsigned next_ten_sec = seconds_tick + 10 ;
for(;;)
{
if( (seconds_tick - next_ten_sec) >= 0 )
{
next_ten_sec += 10 ;
f() ;
otherfunctions() ;
}
continuousStuff() ;
}
}
使用 mbed RTOS 定时器
#include "mbed.h"
#include "rtos.h"
void TenSecondFunction( void const* )
{
f();
otherfunctions();
}
int main()
{
RtosTimer every_ten_seconds( TenSecondFunction, osTimerPeriodic, 0);
for(;;)
{
continuousStuff() ;
}
}
关于在 C-mbed 平台中每 10 秒调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038475/