在C-mbed平台上每10秒调用一次函数

时间:2015-03-13 17:29:53

标签: c arm embedded microcontroller mbed

我可以使用:

while(1==1) 
{

    delay(10);

    f();     // <-- function to be called every 10 seconds

    otherfunctions();

}

但这需要10秒以上,因为其他功能需要一些时间才能执行。是否有延迟功能考虑到其他功能所花费的时间,因此我可以每隔10秒调用f()

我听说过这可以通过一个可以在头文件中找到的聪明功能来完成,但我不记得哪一个。我认为它可能是#include mbed.h,但即使该函数包含在此头文件中,我也不知道它的名称或搜索方式。

是否有人知道可以完成我所追求的功能?

3 个答案:

答案 0 :(得分:4)

您当然应该先阅读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() ;
    }
}

答案 1 :(得分:1)

如果您想要简单,请尝试这个

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
}

答案 2 :(得分:0)

假设您有某种类型的定时器计数器,可能是由定时器驱动的中断产生的,请尝试以下方法:

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秒,并假设每秒的滴答数是精确整数。由于原始读数被用作基础,因此循环不会在很长一段时间内“漂移”。