Using <chrono> as a timer in bare-metal microcontroller?

我与影子孤独终老i 提交于 2019-12-04 11:18:42

I would create a clock that implements now by reading from your timer register:

#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"}};
    }
};

Adjust period to whatever speed your processor ticks at (but it does have to be a compile-time constant). Above I've set it for 1 tick/ms. Here is how it should read for 1 tick == 2ns:

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

Now you can say things like:

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

and

auto d = clock::now() - t;  // a chrono::duration
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!