运用 作为裸机微控制器的定时器?

问题描述 投票:4回答:1

chrono可以用作裸机微控制器中的定时器/计数器(例如运行RTOS的MSP432)吗?可以配置high_resolution_clock(和chrono中的其他API),使其根据给定的微控制器的实际定时器滴答/寄存器递增吗?

Real-Time C ++书籍(第16.5节)似乎表明这是可能的,但我没有找到任何这种应用的例子,特别是在裸机微控制器中。

怎么能实现呢?这会被推荐吗?如果没有,chrono在哪里可以帮助基于RTOS的嵌入式软件?

c++11 embedded chrono
1个回答
7
投票

我会创建一个现在通过读取定时器寄存器来实现的时钟:

#include <chrono>
#include <cstdint>

struct clock
{
    using rep        = std::int64_t;
    using period     = std::milli;
    using duration   = std::chrono::duration<rep, period>;
    using time_point = std::chrono::time_point<clock>;
    static constexpr bool is_steady = true;

    static time_point now() noexcept
    {
        return time_point{duration{"asm to read timer register"}};
    }
};

将周期调整到处理器所处的速度(但它必须是编译时常量)。我将其设置为1滴/秒。以下是1 tick == 2ns的读数:

using period = std::ratio<1, 500'000'000>;

现在你可以这样说:

auto t = clock::now();  // a chrono::time_point

auto d = clock::now() - t;  // a chrono::duration
© www.soinside.com 2019 - 2024. All rights reserved.