halx
読み取り中…
検索中…
一致する文字列を見つけられません
tim.hpp
[詳解]
1#pragma once
2
3#include <functional>
4
5#include "halx/core.hpp"
6
7namespace halx::peripheral {
8
9class TimBase {
10public:
11 virtual ~TimBase() {}
12 virtual bool start() = 0;
13 virtual bool stop() = 0;
14 virtual uint32_t get_counter() const = 0;
15 virtual void set_counter(uint32_t count) = 0;
16 virtual bool attach_callback(void (*callback)(void *context),
17 void *context) = 0;
18 virtual bool detach_callback() = 0;
19
20 bool attach_callback(std::function<void()> &&callback) {
21 callback_ = std::move(callback);
22 return attach_callback(
23 [](void *context) {
24 auto callback = reinterpret_cast<std::function<void()> *>(context);
25 (*callback)();
26 },
27 &callback_);
28 }
29
30private:
31 std::function<void()> callback_;
32};
33
34#ifdef HAL_TIM_MODULE_ENABLED
35
36template <TIM_HandleTypeDef *Handle> class Tim : public TimBase {
37public:
38 using TimBase::attach_callback;
39
40 Tim() {
41 stm32cubemx_helper::set_context<Handle, Tim>(this);
42 HAL_TIM_RegisterCallback(
43 Handle, HAL_TIM_PERIOD_ELAPSED_CB_ID, [](TIM_HandleTypeDef *) {
44 auto tim = stm32cubemx_helper::get_context<Handle, Tim>();
45 if (tim->callback_) {
46 tim->callback_(tim->context_);
47 }
48 });
49 }
50
51 ~Tim() override {
52 HAL_TIM_UnRegisterCallback(Handle, HAL_TIM_PERIOD_ELAPSED_CB_ID);
53 stm32cubemx_helper::set_context<Handle, Tim>(nullptr);
54 }
55
56 bool start() override { return HAL_TIM_Base_Start_IT(Handle) == HAL_OK; }
57
58 bool stop() override { return HAL_TIM_Base_Stop_IT(Handle) == HAL_OK; }
59
60 uint32_t get_counter() const override {
61 return __HAL_TIM_GET_COUNTER(Handle);
62 }
63
64 void set_counter(uint32_t count) override {
65 __HAL_TIM_SET_COUNTER(Handle, count);
66 }
67
68 bool attach_callback(void (*callback)(void *context),
69 void *context) override {
70 if (callback_) {
71 return false;
72 }
73 callback_ = callback;
74 context_ = context;
75 return true;
76 }
77
78 bool detach_callback() override {
79 if (!callback_) {
80 return false;
81 }
82 callback_ = nullptr;
83 return true;
84 }
85
86private:
87 void (*callback_)(void *context) = nullptr;
88 void *context_ = nullptr;
89};
90
91#endif
92
93} // namespace halx::peripheral
Definition tim.hpp:9
virtual bool stop()=0
virtual bool attach_callback(void(*callback)(void *context), void *context)=0
virtual ~TimBase()
Definition tim.hpp:11
virtual uint32_t get_counter() const =0
virtual void set_counter(uint32_t count)=0
virtual bool detach_callback()=0
bool attach_callback(std::function< void()> &&callback)
Definition tim.hpp:20
virtual bool start()=0
Definition can.hpp:13