Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 281
Joe Pak Avatar asked Oct 13 '17 18:10

Joe Pak


1 Answers

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
like image 178
Howard Hinnant Avatar answered Nov 12 '22 22:11

Howard Hinnant