libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
stm32_timebase.cpp
1#include "stm32_timebase.hpp"
2
3using namespace LibXR;
4
6 : Timebase(static_cast<uint64_t>(UINT32_MAX) * 1000 + 999, UINT32_MAX)
7{
8}
9
11{
12 do
13 {
14 uint32_t tick_old = HAL_GetTick();
15 uint32_t cnt_old = SysTick->VAL;
16 uint32_t tick_new = HAL_GetTick();
17 uint32_t cnt_new = SysTick->VAL;
18
19 auto time_diff = tick_new - tick_old;
20 uint32_t tick_load = SysTick->LOAD + 1;
21 switch (time_diff)
22 {
23 case 0:
24 return MicrosecondTimestamp(static_cast<uint64_t>(tick_new) * 1000 + 1000 -
25 static_cast<uint64_t>(cnt_old) * 1000 / tick_load);
26 case 1:
27 /* 中断发生在两次读取之间 / Interrupt happened between two reads */
28 return MicrosecondTimestamp(static_cast<uint64_t>(tick_new) * 1000 + 1000 -
29 static_cast<uint64_t>(cnt_new) * 1000 / tick_load);
30 default:
31 /* 中断耗时过长(超过1ms),程序异常 / Indicates that interrupt took more than
32 * 1ms, an error case */
33 continue;
34 }
35 } while (true);
36}
37
39
40#ifdef HAL_TIM_MODULE_ENABLED
41
42TIM_HandleTypeDef* STM32TimerTimebase::htim = nullptr;
43
45 : Timebase(static_cast<uint64_t>(UINT32_MAX) * 1000 + 999, UINT32_MAX)
46{
47 htim = timer;
48}
49
51{
52 do
53 {
54 uint32_t tick_old = HAL_GetTick();
55 uint32_t cnt_old = __HAL_TIM_GET_COUNTER(htim);
56 uint32_t tick_new = HAL_GetTick();
57 uint32_t cnt_new = __HAL_TIM_GET_COUNTER(htim);
58
59 uint32_t autoreload = __HAL_TIM_GET_AUTORELOAD(htim) + 1;
60
61 uint32_t delta_ms = tick_new - tick_old;
62 switch (delta_ms)
63 {
64 case 0:
65 return MicrosecondTimestamp(static_cast<uint64_t>(tick_new) * 1000 +
66 static_cast<uint64_t>(cnt_old) * 1000 / autoreload);
67 case 1:
68 /* 中断发生在两次读取之间 / Interrupt happened between two reads */
69 return MicrosecondTimestamp(static_cast<uint64_t>(tick_new) * 1000 +
70 static_cast<uint64_t>(cnt_new) * 1000 / autoreload);
71 default:
72 /* 中断耗时过长(超过1ms),程序异常 / Indicates that interrupt took more than
73 * 1ms, an error case */
74 continue;
75 }
76 } while (true);
77}
78
80
81#endif
表示微秒级时间戳的类。Class representing a timestamp in microseconds.
表示毫秒级时间戳的类。Class representing a timestamp in milliseconds.
MillisecondTimestamp _get_milliseconds()
获取当前时间(毫秒级) / Get current time in milliseconds
STM32Timebase()
默认构造函数 / Default constructor
MicrosecondTimestamp _get_microseconds()
获取当前时间(微秒级) / Get current time in microseconds
STM32TimerTimebase(TIM_HandleTypeDef *timer)
构造函数 / Constructor
MillisecondTimestamp _get_milliseconds()
获取当前时间(毫秒级) / Get current time in milliseconds
static TIM_HandleTypeDef * htim
硬件定时器句柄指针 / Static pointer to hardware timer handle
MicrosecondTimestamp _get_microseconds()
获取当前时间(微秒级) / Get current time in microseconds
时间基类,用于提供高精度时间戳。 Timebase class for providing high-precision timestamps.
Definition timebase.hpp:18
LibXR 命名空间