Using as a timer in bare-metal microcontr

2020-07-17 15:42发布

问题:

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