在 C-mbed 平台中每 10 秒调用一个函数

标签 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 但即使该函数包含在此头文件中,我也不知道它叫什么或如何搜索它。

有人知道可以实现我所追求的功能吗?

最佳答案

您当然应该先阅读 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/

相关文章:

c - 我无法用c语言读取另一个结构

ios - 如何在 armv7 (Cortex A5) iOS 中使用 VFMA 指令?

c - ARM汇编中的矩阵乘法

c - C 嵌入式软件中的查找表与开关

c - 寻找带有源代码的嵌入式项目

c - 关于SSR切换的问题

c - 位摆弄 : which bit is set?

c - 在 C 中初始化一个结构

c - snprintf() 使用 newlib nano 打印垃圾 float

memory-management - 适用于无需动态内存分配的开发的语言