2548 |
jacho |
1 |
#include <SPI.h> |
|
|
2 |
|
|
|
3 |
void command(char* buffer, unsigned int len) |
|
|
4 |
{ |
|
|
5 |
for (int i = 0; i < len; i++) { |
|
|
6 |
delay(10); |
|
|
7 |
digitalWrite(SS, 0); |
|
|
8 |
SPI.transfer(buffer[i]); |
|
|
9 |
digitalWrite(SS, 1); |
|
|
10 |
} |
|
|
11 |
} |
|
|
12 |
|
|
|
13 |
void goTo(unsigned int pos) |
|
|
14 |
{ |
|
|
15 |
char buffer[4]; |
|
|
16 |
buffer[0] = 0x60; |
|
|
17 |
buffer[1] = pos >> 16; |
|
|
18 |
buffer[2] = (pos >> 8) & 0xff; |
|
|
19 |
buffer[3] = pos & 0xff; |
|
|
20 |
command(buffer, 4); |
|
|
21 |
} |
|
|
22 |
|
|
|
23 |
void setParam(unsigned int reg, unsigned int val, unsigned int len) |
|
|
24 |
{ |
|
|
25 |
char buffer[4]; |
|
|
26 |
buffer[0] = reg; |
|
|
27 |
|
|
|
28 |
/* BUG: reg? */ |
|
|
29 |
for (int i = 0; i < len; i++) |
|
|
30 |
buffer[i + 1] = (reg >> (8 * ((len - 1) - i))) & 0xff; |
|
|
31 |
|
|
|
32 |
command(buffer, 1 + len); |
|
|
33 |
} |
|
|
34 |
|
|
|
35 |
void setup() |
|
|
36 |
{ |
|
|
37 |
Serial.begin(9600); |
|
|
38 |
SPI.begin(SPI_MASTER, MSBFIRST, SPI_MODE3, SPI_CLOCK_DIV32); |
|
|
39 |
|
|
|
40 |
setParam(5, 0xd0, 2); // ACC |
|
|
41 |
setParam(6, 0xd0, 2); // DEC |
|
|
42 |
setParam(7, 0, 2); // MAX_SPEED |
|
|
43 |
} |
|
|
44 |
|
|
|
45 |
int readInt() |
|
|
46 |
{ |
|
|
47 |
char line[100]; |
|
|
48 |
int i = 0; |
|
|
49 |
|
|
|
50 |
while (true) { |
|
|
51 |
if (Serial.available()) { |
|
|
52 |
byte c = Serial.read(); |
|
|
53 |
|
|
|
54 |
if (c == '\n' || c == '\r') { |
|
|
55 |
Serial.println(); |
|
|
56 |
line[i] = '\0'; |
|
|
57 |
return atoi(line); |
|
|
58 |
} |
|
|
59 |
|
|
|
60 |
Serial.write(c); |
|
|
61 |
line[i++] = c; |
|
|
62 |
} |
|
|
63 |
} |
|
|
64 |
} |
|
|
65 |
|
|
|
66 |
void loop() |
|
|
67 |
{ |
|
|
68 |
int speed = readInt(); |
|
|
69 |
|
|
|
70 |
int dir = speed > 0; |
|
|
71 |
if (!dir) |
|
|
72 |
speed = -speed; |
|
|
73 |
|
|
|
74 |
char buffer[4]; |
|
|
75 |
buffer[0] = 0x50 | dir; |
|
|
76 |
buffer[1] = (speed >> 16) & 0xff; |
|
|
77 |
buffer[2] = (speed >> 8) & 0xff; |
|
|
78 |
buffer[3] = speed & 0xff; |
|
|
79 |
|
|
|
80 |
command(buffer, 4); |
|
|
81 |
} |