2#include "ch32_timebase.hpp"
8constexpr uint32_t SYSTICK_ENABLE = 1U << 0U;
9constexpr uint32_t SYSTICK_CLOCK_HCLK = 1U << 2U;
10constexpr uint32_t SYSTICK_AUTO_RELOAD = 1U << 3U;
11constexpr uint32_t SYSTICK_COUNT_DOWN = 1U << 4U;
12constexpr uint64_t MICROSECONDS_PER_SECOND = 1000000ULL;
13constexpr uint64_t MILLISECONDS_PER_SECOND = 1000ULL;
15uint32_t timebase_clock_hz = 0U;
17uint64_t ReadSysTickCounter()
19 auto* count_words =
reinterpret_cast<volatile uint32_t*
>(&SysTick->CNT);
28 high_before = count_words[1];
30 high_after = count_words[1];
31 }
while (high_before != high_after);
33 return (
static_cast<uint64_t
>(high_after) << 32U) | low;
36uint64_t CyclesToUnits(uint64_t cycles, uint64_t units_per_second)
40 const uint64_t seconds = cycles / timebase_clock_hz;
41 const uint64_t remaining_cycles = cycles % timebase_clock_hz;
42 return seconds * units_per_second +
43 remaining_cycles * units_per_second / timebase_clock_hz;
49 const uint32_t control = SysTick->CTLR;
50 ASSERT((control & (SYSTICK_ENABLE | SYSTICK_CLOCK_HCLK)) ==
51 (SYSTICK_ENABLE | SYSTICK_CLOCK_HCLK) &&
52 (control & (SYSTICK_AUTO_RELOAD | SYSTICK_COUNT_DOWN)) == 0U &&
53 SystemCoreClock >= MICROSECONDS_PER_SECOND);
55 timebase_clock_hz = SystemCoreClock;
63 CyclesToUnits(ReadSysTickCounter(), MICROSECONDS_PER_SECOND));
69 CyclesToUnits(ReadSysTickCounter(), MILLISECONDS_PER_SECOND)));
CH32Timebase()
构造函数 / Constructor
微秒时间戳 / Microsecond timestamp
毫秒时间戳 / Millisecond timestamp
static void ConfigureWrapRange(uint64_t max_valid_us, uint32_t max_valid_ms) noexcept
配置时间戳回绕上界。 Configure the timestamp wraparound limits.
static void SetReady(bool ready=true) noexcept
设置时间基就绪状态。 Set the timebase ready flag.
static MicrosecondTimestamp GetMicroseconds()
获取当前时间的微秒级时间戳。 Gets the current timestamp in microseconds.
static MillisecondTimestamp GetMilliseconds()
获取当前时间的毫秒级时间戳。 Gets the current timestamp in milliseconds.
LibXR 命名空间 / LibXR namespace.