【问题标题】:Using <chrono> as a timer in bare-metal microcontroller?在裸机微控制器中使用 <chrono> 作为定时器?
【发布时间】:2018-03-25 23:14:15
【问题描述】:

chrono 能否在裸机微控制器(例如运行 RTOS 的 MSP432)中用作定时器/计数器?能否配置 high_resolution_clock(以及计时中的其他 API),使其根据给定微控制器的实际计时器滴答/寄存器递增?

Real-Time C++ 书(第 16.5 节)似乎表明这是可能的,但我还没有找到任何应​​用示例,尤其是在裸机微控制器中。

如何实现?这甚至会被推荐吗?如果没有,chrono 可以在基于 RTOS 的嵌入式软件中提供哪些帮助?

【问题讨论】:

  • 什么 RTOS 还没有包含定时器服务!?无论如何,什么是“Chrono”?它可以指很多东西。如果您指的是 C++11 ,那么您可能会标记此 C++ 并明确表示。此外,时间和定时器服务是硬件依赖,所以如果你的嵌入式库支持它,你仍然必须实现底层硬件和 RTOS 的系统调用胶水——它不会靠魔法工作!

标签: c++11 embedded chrono


【解决方案1】:

我将创建一个现在通过读取您的定时器寄存器来实现的时钟:

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

将周期调整为处理器的运行速度(但它必须是编译时常量)。上面我已将其设置为 1 滴答/毫秒。以下是 1 tick == 2ns 的读取方式:

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

现在你可以这样说:

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

auto d = clock::now() - t;  // a chrono::duration

【讨论】:

  • @Jörgen:是的,谢谢。就我而言,愚蠢的想法。已更正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多