-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencoder.cpp
77 lines (64 loc) · 1.46 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* encoder.cpp
*
* Created on: 2018/09/03
* Author: Sekiguchi Takuy
* changed on:2019/10
* changer: Satoshi Ohya
*/
#include "encoder.hpp"
Encoder::Encoder(TIM_HandleTypeDef *htim){
tim = htim;
startFlag = 0;
preRawCount = 0;
curRawCount = 0;
count = 0;
}
void Encoder::init(){
count = 0;
}
void Encoder::start(){
int16_t tmpCount = count;
if(startFlag == 0){
HAL_TIM_Encoder_Start(tim,TIM_CHANNEL_ALL);
}
__HAL_TIM_CLEAR_FLAG(tim, TIM_CHANNEL_ALL);
__HAL_TIM_SET_COUNTER(tim , 0);
startFlag = 1;
update();
count = tmpCount;
}
void Encoder::stop(){
update();
if(startFlag == 1){
HAL_TIM_Encoder_Stop(tim,TIM_CHANNEL_ALL);
}
__HAL_TIM_CLEAR_FLAG(tim, TIM_CHANNEL_ALL);
__HAL_TIM_SET_COUNTER(tim , 0);
startFlag = 0;
}
void Encoder::update() {
if(startFlag == 0) return;
preRawCount = curRawCount;
if (__HAL_TIM_GET_FLAG(tim, TIM_FLAG_UPDATE)) {
curRawCount = __HAL_TIM_GET_COUNTER(tim);
if (curRawCount > preRawCount) {
//under_flow
count += (curRawCount - __HAL_TIM_GET_AUTORELOAD(tim)) - preRawCount;
} else {
//over_flow
count += curRawCount - (preRawCount - __HAL_TIM_GET_AUTORELOAD(tim));
}
__HAL_TIM_CLEAR_FLAG(tim, TIM_FLAG_UPDATE);
} else {
curRawCount = __HAL_TIM_GET_COUNTER(tim);
count += curRawCount - preRawCount;
}
}
int32_t Encoder::getCount(){
return count;
}
void Encoder::resetCount(){
update();
count = 0;
}