-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncoder.cpp
More file actions
107 lines (83 loc) · 2.51 KB
/
Encoder.cpp
File metadata and controls
107 lines (83 loc) · 2.51 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
/*
--Arduino_Rotary_Encoder by Mehmet Yusuf Dal--
This is a simple Arduino library for minimizing the code while using rotary encoder modules like Ky-040.
*/
#ifndef _ENCODER_
#define _ENCODER_
#include "Encoder.h"
Encoder::Encoder(int A, int B, int c_start, int c_step, int c_min, int c_max){
if(c_min > c_max){
c_min = N_INF;
c_max = P_INF;
}
Encoder::c_min = c_min;
Encoder::c_max = c_max;
Encoder::c_step = c_step;
if(c_min <= c_start){
if(c_max >= c_start){
Encoder::counter = c_start;
Encoder::c_start = c_start;
}
else{
Encoder::counter = c_max;
Encoder::c_start = c_max;
}
}
else{
Encoder::counter = c_min;
Encoder::c_start = c_min;
}
Encoder::last_count = Encoder::counter;
Encoder::A = A;
Encoder::B = B;
pinMode(A, INPUT);
pinMode(B, INPUT);
Encoder::A_last_state = digitalRead(A);
}
bool Encoder::stateControl(){
Encoder::A_state = digitalRead(Encoder::A);
bool stateChng = false;
if(Encoder::A_state != Encoder::A_last_state){
if(digitalRead(Encoder::B) != Encoder::A_state){
if(Encoder::counter < Encoder::c_max) Encoder::counter += Encoder::c_step;
}
else{
if(Encoder::counter > Encoder::c_min) Encoder::counter -= Encoder::c_step;
}
Encoder::A_last_state = Encoder::A_state;
}
if(Encoder::counter != Encoder:: last_count){
stateChng = true;
Encoder::last_count = Encoder::counter;
}
return stateChng;
}
void Encoder::setMin(int c_min){
if(c_min < Encoder::c_max ){
Encoder::c_min = c_min;
if(Encoder::counter < c_min) Encoder::counter = c_min;
}
}
void Encoder::setMax(int c_max){
if(c_max > Encoder::c_min){
Encoder::c_max = c_max;
if(Encoder::counter > c_max) Encoder::counter = c_max;
}
}
void Encoder::setStart(int c_start){
if(Encoder::c_min <= c_start){
if(Encoder::c_max >= c_start){
Encoder::c_start = c_start;
}
else{
Encoder::c_start = Encoder::c_max;
}
}
else{
Encoder::c_start = Encoder::c_min;
}
}
void Encoder::setStep(int c_step){ Encoder::c_step = c_step; }
void Encoder::resetCounter(){ Encoder::counter = Encoder::c_start; }
int Encoder::getState(){ return Encoder::counter; }
#endif