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

前提是你 提交于 2019-12-06 06:09:53

问题


Can chrono be used as a timer/counter in a bare-metal microcontroller (e.g. MSP432 running an RTOS)? Can the high_resolution_clock (and other APIs in chrono) be configured so that it increments based on the given microcontroller's actual timer tick/register?

The Real-Time C++ book (section 16.5) seems to suggest this is possible, but I haven't found any examples of this being applied, especially within bare-metal microcontrollers.

How could this be implemented? Would this be even recommended? If not, where can chrono aid in RTOS-based embedded software?


回答1:


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


来源:https://stackoverflow.com/questions/46736323/using-chrono-as-a-timer-in-bare-metal-microcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!