-
Notifications
You must be signed in to change notification settings - Fork 2
/
01_motor_encoder_test.ino
88 lines (79 loc) · 1.71 KB
/
01_motor_encoder_test.ino
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
float pulses;
int pulsesChanged;
int encA = 2; // blue wire
int encB = 4;
int dirPinA = 12;
int pwmPinA = 3;
float ang = 0.0;
float rev = 0.0;
int dira = 0;
int pwma = 255;
void setup() {
Serial.begin(9600);
pinMode(encA, INPUT_PULLUP);
pinMode(encB, INPUT_PULLUP);
attachInterrupt(0, A_CHANGE, CHANGE);
pinMode(dirPinA, OUTPUT);
pinMode(pwmPinA, OUTPUT);
digitalWrite(dirPinA, 0);
digitalWrite(pwmPinA, 0);
}
void loop() {
if (pulsesChanged != 0) {
// ***** TO DO (2 lines) ***** //
// calculate angle from pulses
ang = pulses;
// calculate revolution from angles
rev = ang;
// ***** END ***** //
Serial.print(pulses);
Serial.print("\t");
Serial.print(ang);
Serial.print("\t");
Serial.print(rev);
Serial.print("\n");
pulsesChanged = 0;
}
char a = Serial.read();
if (a == '1') {
m_cw();
}
else if (a == '2') {
m_ccw();
}
else if (a == '3') {
m_stop();
}
}
void A_CHANGE() {
if ( digitalRead(encB) == 0 ) {
if ( digitalRead(encA) == 0 ) {
// A fall, B is low
pulses--; // Moving CCW
} else {
// A rise, B is low
pulses++; // Moving CW
}
} else {
if ( digitalRead(encA) == 0 ) {
// A fall, B is high
pulses++; // Moving CW
} else {
// A rise, B is high
pulses--; // Moving CCW
}
}
pulsesChanged = 1;
}
void m_cw() {
digitalWrite(dirPinA, 1);
analogWrite(pwmPinA, pwma);
}
void m_ccw() {
digitalWrite(dirPinA, 0);
analogWrite(pwmPinA, pwma);
}
void m_stop() {
digitalWrite(dirPinA, 0);
digitalWrite(pwmPinA, 0);
}