在裸机微控制器中使用<chrono>作为定时器?

Joe*_*Pak 4 embedded c++11 c++-chrono

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

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

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

How*_*ant 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"}};
    }
};
Run Code Online (Sandbox Code Playgroud)

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

using period = std::ratio<1, 500'000'000>;
Run Code Online (Sandbox Code Playgroud)

现在你可以这样说:

auto t = clock::now();  // a chrono::time_point
Run Code Online (Sandbox Code Playgroud)

auto d = clock::now() - t;  // a chrono::duration
Run Code Online (Sandbox Code Playgroud)