Can I retarget the chrono class to use microcontroller as tick generator?

Viewed 77

I want to use the timer in my microcontroller as tick generator of the chrono class. imagine that I have function that gets the tick from timer register in the MCU and I call it get_tcik() and this register is 32 bit unsigned integer which increments each 1 microsecond. Now to use it with chrono I've created a class like this:

class clock
{
public:
  static std::chrono::time_point<clock, std::chrono::duration<std::uint32_t, std::ratio<1, 1000000> now() {
    return std::chrono::time_point<clock, std::chrono::duration<std::uint32_t, std::ratio<1, 1000000> {std::chrono::duration<uint32_t, std::ratio<1, 1000000>> { get_tick() }};
}
};

And it doesn't work!

1 Answers

It's not working because the chrono library detects suboptimal code formatting. :-)

Just kidding.

You're missing some nested types for clock that client code might expect to be there. Also you can use std::micro in place of std::ratio<1, 1000000>. Your choice isn't wrong. This is just a stylistic suggestion.

#include <chrono>

class clock
{
public:
    using rep        = std::uint32_t;
    using period     = std::micro;
    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() {
        return time_point{duration { get_tick() }};
    }
};

Here's the official requirements: http://eel.is/c++draft/time.clock.req

Be advised that your clock will roll-over about every hour and 11 minutes.

Related