-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.cpp
48 lines (39 loc) · 1.29 KB
/
encoder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*!
* @file encoder.cpp v1.0
* @Copyright © 2019 Kazushi Kurasawa
* @date 2019.10.23
*
* Released under the MIT license.
* see https://opensource.org/licenses/MIT
*/
#include "encoder.h"
mslh::Encoder::Encoder(TIM_HandleTypeDef &htim_x, int32_t one_rotation_pulse, bool cw)
: _delta_pulse(0)
, _total_pulse(0)
, _htim_x(htim_x)
, _offset_pulse(__HAL_TIM_GET_AUTORELOAD(&_htim_x) / 2 - 1)
, _one_rotation_pulse(one_rotation_pulse) //< 計算高速化のため.
, _forward_wise(cw)
{
}
void mslh::Encoder::start() const {
HAL_TIM_Encoder_Start(&_htim_x, TIM_CHANNEL_ALL);
}
void mslh::Encoder::stop() const {
HAL_TIM_Encoder_Stop(&_htim_x, TIM_CHANNEL_ALL);
}
void mslh::Encoder::reset() {
_delta_pulse = 0;
_total_pulse = 0;
__HAL_TIM_SET_COUNTER(&_htim_x, _offset_pulse); // まだ動作未確認 元:_htim_x.Instance->CNT = _offset_pulse;
}
void mslh::Encoder::update() {
uint32_t pulse_count = __HAL_TIM_GET_COUNTER(&_htim_x);
__HAL_TIM_SET_COUNTER(&_htim_x, _offset_pulse);
/// _delta_pulse を更新
_delta_pulse = static_cast<int32_t>(pulse_count - _offset_pulse);
/// _forward_wise が true の時にカウントアップとする
if (!_forward_wise) _delta_pulse *= -1;
/// _total_pulse を更新
_total_pulse += _delta_pulse;
}