-
Notifications
You must be signed in to change notification settings - Fork 0
/
arduino-stepper-sketch.ino
147 lines (118 loc) · 2.49 KB
/
arduino-stepper-sketch.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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// Coil pins
#define coilA 9
#define coilB 10
#define coilC 11
#define coilD 12
// NOTES:
// 8-states per motor cycle
// 512 cycles for a full turn
// 4096 total states/rev, this defines
// maxSteps
byte rxByte;
String inStr = "";
bool rxComplete = false;
const byte numChars = 12;
char rcvChars[numChars];
unsigned int stepsCounter = 0;
unsigned int maxSteps = 4095;
// Coil states
int enCoil[8][4] = {
{1, 0, 0, 0},
{1, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1},
{1, 0, 0, 1},
};
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(coilA, OUTPUT);
pinMode(coilB, OUTPUT);
pinMode(coilC, OUTPUT);
pinMode(coilD, OUTPUT);
coilsOff();
Serial.begin(9600);
}
void coilsOff() {
digitalWrite(coilA, 0);
digitalWrite(coilB, 0);
digitalWrite(coilC, 0);
digitalWrite(coilD, 0);
}
void coilsWrite(int state){
digitalWrite(coilA, enCoil[state & 0x07][0]);
digitalWrite(coilB, enCoil[state & 0x07][1]);
digitalWrite(coilC, enCoil[state & 0x07][2]);
digitalWrite(coilD, enCoil[state & 0x07][3]);
}
void rxWithEnd() {
static byte ndx = 0;
char endChar = '\r';
char rc;
while (Serial.available() > 0 ) {
rc = Serial.read();
rcvChars[ndx] = rc;
// If endChar or more than numChars complete reception
if ( ( rc == endChar ) || ( ndx == (numChars-1)) ){
rxComplete=true;
ndx=0;
}
else{
ndx++;
}
}
}
void reset() {
stepsCounter = 0;
Serial.println("SET:STEP:0");
}
void counterRead() {
Serial.print("READ:STEP:");
Serial.println(stepsCounter);
}
void goStep() {
unsigned int k,c,d,u=0;
unsigned int requested;
k=1000 * (rcvChars[1]-48);
c= 100 * (rcvChars[2]-48);
d= 10 * (rcvChars[3]-48);
u= (rcvChars[4]-48);
requested = k+c+d+u;
if (requested > maxSteps){
requested = maxSteps;
}
while (requested != stepsCounter){
if (requested > stepsCounter){
stepsCounter++;
}
if (requested < stepsCounter){
stepsCounter--;
}
coilsWrite(stepsCounter);
delay(5);
}
Serial.print("MOV:DONE:");
Serial.println(requested);
}
void printNew() {
if (rxComplete == true) {
switch(rcvChars[0]) {
case 'R' : reset();
break;
case 'c' : counterRead();
break;
case 'g' : goStep();
break;
default: Serial.println("???");
}
rxComplete=false;
}
}
void loop() {
while(true){
rxWithEnd();
printNew();
}
}