-
Notifications
You must be signed in to change notification settings - Fork 0
/
motor.c
52 lines (50 loc) · 1.29 KB
/
motor.c
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
#include "motor.h"
void update_encoder(encoder_instance *encoder_value, TIM_HandleTypeDef *htim)
{
uint32_t temp_counter = __HAL_TIM_GET_COUNTER(htim);
uint8_t first_time = 0;
if(!first_time)
{
encoder_value ->velocity = 0;
first_time = 1;
}
else
{
if(temp_counter == encoder_value ->last_counter_value)
{
encoder_value ->velocity = 0;
}
else if(temp_counter > encoder_value ->last_counter_value)
{
if (__HAL_TIM_IS_TIM_COUNTING_DOWN(htim))
{
encoder_value ->velocity = -encoder_value ->last_counter_value -
(__HAL_TIM_GET_AUTORELOAD(htim)-temp_counter);
}
else
{
encoder_value ->velocity = temp_counter - encoder_value ->last_counter_value;
}
}
else
{
if (__HAL_TIM_IS_TIM_COUNTING_DOWN(htim))
{
encoder_value ->velocity = temp_counter - encoder_value ->last_counter_value;
}
else
{
encoder_value ->velocity = temp_counter +
(__HAL_TIM_GET_AUTORELOAD(htim) - encoder_value ->last_counter_value);
}
}
}
encoder_value ->position += encoder_value ->velocity;
encoder_value ->last_counter_value = temp_counter;
}
void reset_encoder(encoder_instance *encoder_value)
{
encoder_value ->velocity = 0;
encoder_value ->position = 0;
encoder_value ->last_counter_value = 0;
}