我可以用:
while(1==1)
{
delay(10);
f(); // <-- function to be called every 10 seconds
otherfunctions();
}但是这只需要10秒多一点,因为其他函数需要一些时间来执行。是否有一个延迟函数考虑到其他函数所花费的时间,这样我就可以精确地每10秒调用一次f()?
我听说这可以用一个聪明的函数来完成,这个函数可以在头文件中找到,但是我不记得是哪一个。我认为它可能是#include mbed.h,但是即使函数包含在这个头文件中,我也不知道它被调用了什么,也不知道如何搜索它。
有谁知道有什么功能能做我想做的事吗?
发布于 2015-03-13 20:22:49
当然,您应该从阅读磨砂手册开始。它不是一个很大的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 和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计时器
#include "mbed.h"
#include "rtos.h"
void TenSecondFunction( void const* )
{
f();
otherfunctions();
}
int main()
{
RtosTimer every_ten_seconds( TenSecondFunction, osTimerPeriodic, 0);
for(;;)
{
continuousStuff() ;
}
}发布于 2015-04-02 12:12:58
如果你想简单的话,试试这个
int delayTime = DELAY_10_SECS;
while(1==1)
{
delay(delayTime);
lastTime = getCurrTicks(); //Or start some timer with interrupt which tracks time
f(); // <-- function to be called every 10 seconds
otherfunctions();
delayTime = DELAY_10_SECS - ( getCurrTicks() - lastTime ); //Or stop timer and get the time
}发布于 2015-03-13 20:08:36
如果您有某种类型的计时器计数器,可能是由计时器驱动的中断生成的,请尝试如下所示:
volatile int *pticker; /* pointer to ticker */
tickpersecond = ... ; /* number of ticks per second */
/* ... */
tickcount = *pticker; /* get original reading of timer */
while(1){
tickcount += 10 * tickspersecond;
delaycount = tickcount-*pticker;
delay(delaycount); /* delay delaycount ticks */
/* ... */
}这假定滴答增加(而不是递减),在延迟时代码永远不会落后10秒,并且假定每秒的滴答数是一个确切的整数。由于使用原始读数作为基础,循环不会在很长一段时间内“漂移”。
https://stackoverflow.com/questions/29038475
复制相似问题