libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
stm32_watchdog.cpp
1#include "stm32_watchdog.hpp"
2
3#if defined(HAL_IWDG_MODULE_ENABLED)
4
5using namespace LibXR;
6
7STM32Watchdog::STM32Watchdog(IWDG_HandleTypeDef* hiwdg, uint32_t timeout_ms,
8 uint32_t feed_ms, uint32_t clock)
9 : hiwdg_(hiwdg), clock_(clock)
10{
11 ASSERT(hiwdg);
12 SetConfig({timeout_ms, feed_ms});
13 Start();
14}
15
17{
18 if (config.feed_ms == 0 || config.timeout_ms == 0 || config.feed_ms > config.timeout_ms)
19 {
20 ASSERT(false);
21 return ErrorCode::ARG_ERR;
22 }
23
24 /* 分频与重载自动计算 / Prescaler & reload auto calculation */
25 static const struct
26 {
27 uint8_t pr;
28 uint16_t div;
29 } TABLE[] = {{0, 4}, {1, 8}, {2, 16}, {3, 32}, {4, 64}, {5, 128}, {6, 256}};
30 uint32_t lsi = clock_;
31 uint8_t best_pr = 6;
32 uint16_t best_rlr = 0xFFF;
33 bool found = false;
34
35 for (const auto& item : TABLE)
36 {
37 uint32_t prescaler = item.div;
38 uint32_t reload = (config.timeout_ms * lsi) / (1000 * prescaler);
39 if (reload == 0)
40 {
41 reload = 1;
42 }
43 if (reload > 1)
44 {
45 reload--;
46 }
47 if (reload <= 0xFFF)
48 {
49 best_pr = item.pr;
50 best_rlr = static_cast<uint16_t>(reload);
51 found = true;
52 break;
53 }
54 }
55 if (!found)
56 {
57 return ErrorCode::NOT_SUPPORT;
58 }
59
60 timeout_ms_ = config.timeout_ms;
62
63 hiwdg_->Init.Prescaler = best_pr;
64 hiwdg_->Init.Reload = best_rlr;
65#if defined(IWDG)
66 hiwdg_->Instance = IWDG; // NOLINT
67#elif defined(IWDG1)
68 hiwdg_->Instance = IWDG1; // NOLINT
69#endif
70
71 return ErrorCode::OK;
72}
73
75{
76 return HAL_IWDG_Refresh(hiwdg_) == HAL_OK ? ErrorCode::OK : ErrorCode::FAILED;
77}
78
80{
81 auto_feed_ = true;
82 if (HAL_IWDG_Init(hiwdg_) != HAL_OK)
83 {
84 return ErrorCode::FAILED;
85 }
86 return ErrorCode::OK;
87}
88
90{
91 /* STM32 IWDG 不支持关闭 */
92 auto_feed_ = false;
93 return ErrorCode::NOT_SUPPORT;
94}
95
96#endif
uint32_t clock_
LSI clock in Hz.
ErrorCode Stop() override
停止看门狗 / Stop the watchdog
ErrorCode Start() override
启动看门狗 / Start the watchdog
IWDG_HandleTypeDef * hiwdg_
STM32 HAL IWDG handle.
ErrorCode Feed() override
立即手动喂狗 Feed the watchdog immediately
ErrorCode SetConfig(const Configuration &config) override
初始化硬件并设置超时时间 Initialize hardware and set overflow time
uint32_t auto_feed_interval_ms
自动喂狗间隔
Definition watchdog.hpp:110
bool auto_feed_
是否自动喂狗
Definition watchdog.hpp:111
uint32_t timeout_ms_
溢出时间
Definition watchdog.hpp:109
LibXR 命名空间
Definition ch32_gpio.hpp:9
看门狗配置结构体 Configuration for the watchdog
Definition watchdog.hpp:27
uint32_t feed_ms
自动喂狗周期 Auto feed interval (ms, < timeout_ms)
Definition watchdog.hpp:29
uint32_t timeout_ms
看门狗溢出时间 Watchdog overflow time (ms)
Definition watchdog.hpp:28