-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStepperMotor.cpp
65 lines (51 loc) · 1.22 KB
/
StepperMotor.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
#include "StepperMotor.h"
StepperMotor::StepperMotor(float stride, int c1, int c2, int c3, int c4) {
phase = 0;
stepsPerRevolution = 360.0 / stride;
coils = new uint8_t[4]{c1, c2, c3, c4};
stateLut = new uint8_t[8] {
0b0001,
0b0011,
0b0010,
0b0110,
0b0100,
0b1100,
0b1000,
0b1001
};
for (int i = 0; i < 4; i++) {
pinMode(coils[i], OUTPUT);
digitalWrite(coils[i], LOW);
}
}
StepperMotor::~StepperMotor() {
delete stateLut;
for (int i=0 ; i<4; i++) {
digitalWrite(coils[i], LOW);
}
delete coils;
}
void StepperMotor::setRpm(float rpm) {
singleStepDelay = 1000000 * 60.0 / stepsPerRevolution / rpm;
}
void StepperMotor::step(float angles) {
float steps = abs(stepsPerRevolution * angles / 360.0);
for (float i = 0; i < steps; i++) {
iteration(angles >= 0.0);
}
for (int i = 0; i < 4; i++) {
digitalWrite(coils[i], LOW);
}
}
void StepperMotor::iteration(bool cw) {
long phaseBeganAt = micros();
uint8_t state = cw ? phase : 7-phase;
for (int coil = 0; coil < 4; coil++) {
digitalWrite(coils[coil], stateLut[state] & (1<<coil));
}
phase++;
if (phase >= 8) {
phase = 0;
}
while (micros() - phaseBeganAt < singleStepDelay);
}