-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathencoder.c
More file actions
120 lines (95 loc) · 2.54 KB
/
encoder.c
File metadata and controls
120 lines (95 loc) · 2.54 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
* Copyright (c) 2019, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-08-26 sogwms The first version
* 2019-11-14 Soil_L motified for the need of can encoder
*/
#include <rtdevice.h>
#include <encoder.h>
#define DBG_SECTION_NAME "encoder"
#define DBG_LEVEL DBG_LOG
#include <rtdbg.h>
encoder_t encoder_create(rt_size_t size, rt_uint16_t sample_time)
{
// Malloc memory and initialize
encoder_t new_encoder = (encoder_t)rt_malloc(size);
if(new_encoder == RT_NULL)
{
LOG_E("Failed to malloc memory for new encoder\n");
return RT_NULL;
}
new_encoder->pulse_count = 0;
new_encoder->last_count = 0;
new_encoder->sample_time = sample_time;
return new_encoder;
}
rt_err_t encoder_destroy(encoder_t enc)
{
LOG_D("Free Encoder");
RT_ASSERT(enc != RT_NULL);
return enc->destroy(enc);
}
rt_err_t encoder_enable(encoder_t enc)
{
LOG_D("Enabling encoder");
RT_ASSERT(enc != RT_NULL);
return enc->enable(enc);
}
rt_err_t encoder_disable(encoder_t enc)
{
LOG_D("Diabling encoder");
RT_ASSERT(enc != RT_NULL);
return enc->disable(enc);
}
rt_int32_t encoder_read(encoder_t enc)
{
RT_ASSERT(enc != RT_NULL);
return enc->pulse_count;
}
rt_err_t encoder_reset(encoder_t enc)
{
RT_ASSERT(enc != RT_NULL);
enc->pulse_count = 0;
enc->last_count = 0;
return RT_EOK;
}
rt_int16_t encoder_measure_cps(encoder_t enc)
{
RT_ASSERT(enc != RT_NULL);
// return count per second
if((rt_tick_get() - enc->last_time) < rt_tick_from_millisecond(enc->sample_time))
{
LOG_D("Encoder waiting ... ");
return enc->cps;
}
rt_int32_t diff_count = enc->pulse_count - enc->last_count;
enc->cps = diff_count * 1000 / enc->sample_time;
enc->last_count = enc->pulse_count;
enc->last_time = rt_tick_get();
return enc->cps;
}
rt_int16_t encoder_measure_rpm(encoder_t enc)
{
RT_ASSERT(enc != RT_NULL);
rt_int16_t res_rpm;
if(enc->sample_time == 0)
{
res_rpm = enc->pulse_count;
}
else
{
// return resolution per minute
res_rpm = encoder_measure_cps(enc) * 60 / enc->pulse_revol;
}
return res_rpm;
}
rt_err_t encoder_set_sample_time(encoder_t enc, rt_uint16_t sample_time)
{
RT_ASSERT(enc != RT_NULL);
enc->sample_time = sample_time;
return RT_EOK;
}