create-rulecad 0.3.25 → 0.3.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- // Sends a step file (rulecad.steps/1, from cad plot: an arm's drawing or a leg's gait) to the Uno, line by line, each after
3
- // the last was answered.
2
+ // Sends a step file (rulecad.steps/1, from cad plot: an arm's drawing or a leg's gait) to the streamer, line by line, each
3
+ // after the last was answered. The streamer runs on an Uno under a CNC Shield V3 (three axes) or a Mega 2560 (eight): the
4
+ // machine description's controller says which.
4
5
  // node send.mjs <file.steps.json> --port /dev/tty.usbmodem101 [--machine arm.machine.json] [--no-home]
5
6
  // node send.mjs <file.steps.json> --dry-run [--machine arm.machine.json] [--quiet]
6
7
  // echoes each line it would send with the answer the streamer would give,
@@ -14,6 +15,17 @@ import { fileURLToPath } from 'node:url';
14
15
  /** The fastest block the streamer takes, steps/s on its major axis: arm.ino's RATE_LIMIT (a test holds the two equal). */
15
16
  export const MAX_RATE = 8000;
16
17
 
18
+ /** The boards the streamer is built for: its axes (a block line has a signed step count for each) and the longest line it
19
+ * reads (its LINE_MAX), as arm.ino has them. */
20
+ export const STREAMERS = { uno: { board: 'Uno under a CNC Shield V3', axes: 3, lineMax: 95 }, mega: { board: 'Mega 2560', axes: 8, lineMax: 127 } };
21
+ /** The streamer a machine's files go to: its controller's board (cad machine writes it), the Uno where it names none.
22
+ * @param {object} [machine] @returns {{ name: string, board: string, axes: number, lineMax: number }} */
23
+ export function streamerOf(machine) {
24
+ const name = machine?.controller?.board ?? 'uno';
25
+ if (!STREAMERS[name]) throw new Error(`the machine's controller.board is "${name}", and the streamer runs on ${Object.keys(STREAMERS).join(' or ')}`);
26
+ return { name, ...STREAMERS[name] };
27
+ }
28
+
17
29
  /** The serial line's time for one byte, s: 115200 baud, 10 bits a byte (a start bit, 8 data bits, a stop bit). */
18
30
  export const BYTE_TIME = 10 / 115200;
19
31
  /** The bytes of the streamer's answer to a block: "ok", then CR and LF (Serial.println). */
@@ -34,16 +46,21 @@ export function leastBlockTime(line, { turnaround = TURNAROUND } = {}) {
34
46
  return (line.length + 1 + ANSWER_BYTES) * BYTE_TIME + turnaround;
35
47
  }
36
48
 
37
- /** One step file as the protocol's lines, in order. @param {object} file @param {{ pen?: { up: number, down: number }, axes?: number }} [o] */
38
- export function linesOf(file, { pen = { up: 90, down: 30 }, axes = 3 } = {}) {
49
+ /** One step file as the protocol's lines, in order. @param {object} file
50
+ * @param {{ pen?: { up: number, down: number }, axes?: number, names?: string[] }} [o] axes: the streamer's (3 on the Uno,
51
+ * 8 on the Mega), a number for each in a block's line; names: the machine's axes in order (cad machine's description),
52
+ * which the file's must match, so a file written for one machine never drives another's motors */
53
+ export function linesOf(file, { pen = { up: 90, down: 30 }, axes = 3, names } = {}) {
39
54
  if (file?.format !== 'rulecad.steps/1') throw new Error(`not a step file (format is ${JSON.stringify(file?.format)}, wanted rulecad.steps/1)`);
40
- if (file.axes.length > axes) throw new Error(`${file.axes.length} axes in the file, and the streamer has ${axes}`);
55
+ const own = (file.axes || []).map((a) => a?.name);
56
+ if (names && own.every(Boolean) && (own.length > names.length || own.some((n, k) => n !== names[k]))) throw new Error(`the file's axes are ${own.join(', ')}, and the machine's are ${names.join(', ')}: this file was written for another machine (cad plot it for this one)`);
57
+ if (file.axes.length > axes) throw new Error(`${file.axes.length} axes in the file, and the streamer has ${axes}${axes < STREAMERS.mega.axes ? ` (on an Uno; give --machine with a Mega 2560 as its controller for up to ${STREAMERS.mega.axes})` : ''}`);
41
58
  const lines = [];
42
59
  for (const b of file.blocks) {
43
60
  if (b.type === 'pen') lines.push(`p ${b.state === 'down' ? pen.down : pen.up} ${Math.round(b.dwell * 1000)}`);
44
61
  else if (b.type === 'dwell') lines.push(`w ${Math.round(b.time * 1000)}`);
45
62
  else if (b.type === 'move') {
46
- const s = [0, 1, 2].map((k) => b.steps[k] ?? 0), r = b.rate;
63
+ const s = Array.from({ length: axes }, (_, k) => b.steps[k] ?? 0), r = b.rate;
47
64
  lines.push(`m ${s.join(' ')} ${Math.round(r.entry)} ${Math.max(1, Math.round(r.peak))} ${Math.round(r.exit)} ${Math.max(1, Math.round(r.accel))} ${b.accelSteps} ${b.decelSteps}`);
48
65
  } else throw new Error(`a block of type ${JSON.stringify(b.type)}`);
49
66
  }
@@ -57,28 +74,31 @@ export function homeLines(machine) {
57
74
 
58
75
  /** What the streamer would answer to each line, so the protocol can be tested with no board. Throws at the first line it
59
76
  * would refuse, naming it, and at a block too short for the streamer to keep up with (leastBlockTime). With a machine
60
- * (cad machine's description), each axis's share of a block's rate is held to that axis's maxRate too. A dry run has no clock, so it takes each block as finished before the next line: `?` answers the
61
- * positions summed from the blocks so far (a home sets its axis to 0) with 0 blocks queued, and `!` answers `ok`.
77
+ * (cad machine's description), each axis's share of a block's rate is held to that axis's maxRate too, and the streamer is
78
+ * its controller's (streamerOf: the Uno's three axes where it names none). A dry run has no clock, so it takes each block as
79
+ * finished before the next line: `?` answers the positions summed from the blocks so far (a home sets its axis to 0) with
80
+ * 0 blocks queued, and `!` answers `ok`.
62
81
  * @param {string[]} lines @param {{ machine?: object, turnaround?: number }} [o] turnaround as leastBlockTime takes it
63
82
  * @returns {{ lines: number, m: number, p: number, w: number, h: number, e: number, d: number, '?': number, '!': number, peakRate: number, axisPeaks: number[], position: number[], said: string[] }} */
64
83
  export function dryRun(lines, { machine, turnaround = TURNAROUND } = {}) {
65
- const seen = { m: 0, p: 0, w: 0, h: 0, e: 0, d: 0, '?': 0, '!': 0 }, axisPeaks = [0, 0, 0], position = [0, 0, 0], said = [];
84
+ const st = streamerOf(machine), n = st.axes, all = Array.from({ length: n }, (_, k) => k);
85
+ const seen = { m: 0, p: 0, w: 0, h: 0, e: 0, d: 0, '?': 0, '!': 0 }, axisPeaks = all.map(() => 0), position = all.map(() => 0), said = [];
66
86
  let peak = 0;
67
87
  for (const [i, l] of lines.entries()) {
68
- const [c, ...args] = l.split(' '), n = args.map(Number), at = `line ${i + 1} ("${l}")`;
69
- if (l.length > 95) throw new Error(`${at}: longer than the streamer's 95 characters`);
88
+ const [c, ...args] = l.split(' '), x = args.map(Number), at = `line ${i + 1} ("${l}")`;
89
+ if (l.length > st.lineMax) throw new Error(`${at}: longer than the streamer's ${st.lineMax} characters`);
70
90
  if (!(c in seen)) throw new Error(`${at}: no such command (the streamer takes e, d, h, p, w, m, ? and !)`);
71
- if (n.some((x) => !Number.isInteger(x))) throw new Error(`${at}: its numbers are whole`);
72
- if (c === 'h' && (n.length !== 4 || n[0] < 0 || n[0] > 2 || n[2] <= 0)) throw new Error(`${at}: a home is an axis 0, 1 or 2, a direction, a rate over 0 and the steps back`);
91
+ if (x.some((v) => !Number.isInteger(v))) throw new Error(`${at}: its numbers are whole`);
92
+ if (c === 'h' && (x.length !== 4 || x[0] < 0 || x[0] >= n || x[2] <= 0)) throw new Error(`${at}: a home is an axis ${n === 3 ? '0, 1 or 2' : `0 to ${n - 1}`}, a direction, a rate over 0 and the steps back`);
73
93
  if (c === 'm') {
74
- if (n.length !== 9) throw new Error(`${at}: a block is 9 numbers`);
75
- const major = Math.max(...n.slice(0, 3).map(Math.abs));
94
+ if (x.length !== n + 6) throw new Error(`${at}: a block is ${n + 6} numbers (a step count for each of the streamer's ${n} axes, then six rates and counts)`);
95
+ const major = Math.max(...x.slice(0, n).map(Math.abs)), [entry, top, exit, accel] = x.slice(n, n + 4);
76
96
  if (!major) throw new Error(`${at}: a block that moves nothing`);
77
- if (n[4] <= 0 || n[6] <= 0) throw new Error(`${at}: a block's peak rate and acceleration are over 0`);
78
- const fastest = Math.max(n[3], n[4], n[5]);
97
+ if (top <= 0 || accel <= 0) throw new Error(`${at}: a block's peak rate and acceleration are over 0`);
98
+ const fastest = Math.max(entry, top, exit);
79
99
  if (fastest > MAX_RATE) throw new Error(`${at}: ${fastest} steps/s is past the streamer's MAX_RATE of ${MAX_RATE} (it would answer "error: rate")`);
80
- for (const k of [0, 1, 2]) {
81
- const r = (fastest * Math.abs(n[k])) / major, axis = machine?.axes?.[k];
100
+ for (const k of all) {
101
+ const r = (fastest * Math.abs(x[k])) / major, axis = machine?.axes?.[k];
82
102
  axisPeaks[k] = Math.max(axisPeaks[k], r);
83
103
  if (axis?.maxRate && r > axis.maxRate * (1 + 1e-6) + 0.5) throw new Error(`${at}: axis ${axis.name ?? k} at ${Math.round(r)} steps/s, past the machine's ${axis.maxRate} for it`);
84
104
  }
@@ -86,9 +106,9 @@ export function dryRun(lines, { machine, turnaround = TURNAROUND } = {}) {
86
106
  const least = leastBlockTime(l, { turnaround });
87
107
  if (major / fastest < least) throw new Error(`${at}: ${major} steps at up to ${fastest} steps/s can be over in ${(major / fastest * 1000).toFixed(2)} ms, and the streamer needs ${(least * 1000).toFixed(2)} ms for each block's line and answer: it would fall behind and stop between blocks (plan with a least block time, task.blockTime for cad plot, or a lower speed)`);
88
108
  peak = Math.max(peak, fastest);
89
- for (const k of [0, 1, 2]) position[k] += n[k];
109
+ for (const k of all) position[k] += x[k];
90
110
  }
91
- if (c === 'h') position[n[0]] = 0;
111
+ if (c === 'h') position[x[0]] = 0;
92
112
  seen[c]++;
93
113
  said.push(`${l} ${c === '?' ? `q ${position.join(' ')} 0` : 'ok'}`);
94
114
  }
@@ -98,13 +118,16 @@ export function dryRun(lines, { machine, turnaround = TURNAROUND } = {}) {
98
118
  /** What a gait's step file is, for the summary: its cycles, time and start pose (nothing for a drawing). @param {object} file */
99
119
  export const gait = (file) => (file?.kind === 'gait' ? `, ${file.cycles} cycle${file.cycles === 1 ? '' : 's'} of a gait, ${Number(file.time).toFixed(1)} s${file.pose ? ` from the pose "${file.pose}" and back` : ''}` : '');
100
120
 
101
- async function send(port, lines, say) {
121
+ async function send(port, lines, say, axes = 3) {
102
122
  const r = spawnSync('stty', [process.platform === 'darwin' ? '-f' : '-F', port, '115200', 'raw', '-echo', '-hupcl'], { encoding: 'utf8' });
103
123
  if (r.status) throw new Error(`stty ${port}: ${r.stderr}`);
104
124
  const rd = fs.createReadStream(port), wr = fs.createWriteStream(port);
105
125
  let buffer = '', answer = null;
106
- rd.on('data', (d) => { buffer += d; let i; while ((i = buffer.indexOf('\n')) >= 0) { const l = buffer.slice(0, i).trim(); buffer = buffer.slice(i + 1); if (answer && /^(ok|error)/.test(l)) { const a = answer; answer = null; a(l); } else if (l) say(l); } });
107
- await new Promise((res) => setTimeout(res, 2500)); // the Uno resets when the port opens
126
+ let greeting = null;
127
+ rd.on('data', (d) => { buffer += d; let i; while ((i = buffer.indexOf('\n')) >= 0) { const l = buffer.slice(0, i).trim(); buffer = buffer.slice(i + 1); if (answer && /^(ok|error)/.test(l)) { const a = answer; answer = null; a(l); } else if (l) { greeting = /^streamer ready, (\d+) axes$/.exec(l)?.[1] ?? greeting; say(l); } } });
128
+ await new Promise((res) => setTimeout(res, 2500)); // the board resets when the port opens
129
+ // the streamer says how many axes it was built for: lines written for another board would be misread
130
+ if (greeting != null && +greeting !== axes) { rd.destroy(); wr.end(); throw new Error(`the board's streamer has ${greeting} axes, and the lines are written for ${axes}: flash the streamer built for this machine's controller`); }
108
131
  for (const [i, l] of lines.entries()) {
109
132
  const reply = await new Promise((res) => { answer = res; wr.write(`${l}\n`); });
110
133
  if (reply !== 'ok') { wr.write('!\n'); throw new Error(`line ${i + 1} ("${l}"): ${reply}`); }
@@ -118,17 +141,17 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
118
141
  const fileName = args.find((a, i) => !a.startsWith('--') && !['--port', '--machine'].includes(args[i - 1]));
119
142
  if (!fileName) { console.error('usage: node send.mjs <file.steps.json> --port <device> [--machine <file>] [--no-home] | --dry-run'); process.exit(2); }
120
143
  const file = JSON.parse(fs.readFileSync(fileName, 'utf8')), machine = opt('machine') ? JSON.parse(fs.readFileSync(opt('machine'), 'utf8')) : null;
121
- const lines = ['e', ...(machine && !has('no-home') ? homeLines(machine) : []), ...linesOf(file, machine?.pen ? { pen: machine.pen } : {}), 'd'];
122
144
  // the whole file is checked before anything moves: a block refused halfway through a drawing would spoil it
123
- let r;
145
+ let r, lines, st;
146
+ try { st = streamerOf(machine); lines = ['e', ...(machine && !has('no-home') ? homeLines(machine) : []), ...linesOf(file, { ...(machine?.pen ? { pen: machine.pen } : {}), axes: st.axes, ...(machine ? { names: machine.axes.map((a) => a.name) } : {}) }), 'd']; } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
124
147
  try { r = dryRun(lines, { machine }); } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
125
148
  if (has('dry-run')) {
126
149
  if (!has('quiet')) for (const s of r.said) console.log(s);
127
- console.log(`dry run: ${r.lines} lines, ${r.m} blocks, ${r.p} pen moves, ${r.h} homes, peak ${r.peakRate} steps/s (the streamer takes ${MAX_RATE})${machine ? `, axes at most ${r.axisPeaks.slice(0, machine.axes.length).map((x, k) => `${Math.round(x)} of ${machine.axes[k].maxRate}`).join(', ')} steps/s` : ''}${gait(file)}`);
150
+ console.log(`dry run: ${r.lines} lines, ${r.m} blocks, ${r.p} pen moves, ${r.h} homes, peak ${r.peakRate} steps/s (the streamer on ${st.name === 'uno' ? 'an' : 'a'} ${st.board} takes ${MAX_RATE})${machine ? `, axes at most ${r.axisPeaks.slice(0, machine.axes.length).map((x, k) => `${Math.round(x)} of ${machine.axes[k].maxRate}`).join(', ')} steps/s` : ''}${gait(file)}`);
128
151
  process.exit(0);
129
152
  }
130
153
  if (!opt('port')) { console.error('--port <device>, or --dry-run'); process.exit(2); }
131
154
  // a gait has no home: the streamer counts from where the motors stand when it starts, so the leg must be in its pose
132
155
  if (file.kind === 'gait') console.log(`a gait${gait(file)}: the streamer counts from where the motors stand now, so the leg must be in ${file.pose ? `its pose "${file.pose}"` : "the cycle's first frame"}`);
133
- send(opt('port'), lines, console.log).then(() => console.log('done')).catch((e) => { console.error(e.message); process.exit(1); });
156
+ send(opt('port'), lines, console.log, st.axes).then(() => console.log('done')).catch((e) => { console.error(e.message); process.exit(1); });
134
157
  }
@@ -0,0 +1,209 @@
1
+ # The streamer and its sender
2
+
3
+ A machine in the kit moves with two programs. The streamer runs on an Arduino: it takes blocks of synchronised steps
4
+ over the USB serial line and moves the motors. `send.mjs` runs on your computer: it reads a step file that `cad plot`
5
+ wrote, homes the machine where it has switches and sends the file to the board a line at a time. The board knows
6
+ nothing of the machine's shape. All the maths happens in `cad plot`.
7
+
8
+ The streamer is one sketch, the same in every project: `firmware/arm/arm.ino` in the arm's project and
9
+ `firmware/leg/leg.ino` in the leg's. The board it is compiled for picks its pins:
10
+
11
+ | Board | Axes | For | Pins |
12
+ |---|---|---|---|
13
+ | Arduino Uno under a CNC Shield V3 | 3 | the arm, the leg's stand | the shield's: STEP on D2 to D4, DIR on D5 to D7, home switches on D9, D10, D12, enable D8 |
14
+ | Arduino Mega 2560, a step driver for each axis on its own breakout | 8 | the quadruped | STEP on D22 to D29, DIR on D37 down to D30, home switches on A8 to A15, enable D38 (the `arduino-mega-2560` rule set) |
15
+
16
+ The machine description says which board a machine has: `cad machine` reads it from the bought board in the assembly
17
+ (`cnc-shield-v3` or `arduino-mega-2560`) and writes it as `controller.board`, and `send.mjs` writes its lines for that
18
+ board's axes.
19
+
20
+ **Status.** The sketch is compiled for the Uno and for the Mega, and run on a simulated Uno and a simulated Mega, on
21
+ every push to the kit (the `firmware` job of its tests). The simulation homes the arm and streams the worked arm's
22
+ step file, the stand's gait and the quadruped's trot through it. Moving real hardware is your test: each machine's
23
+ measured milestone.
24
+
25
+ ## What you need
26
+
27
+ | | |
28
+ |---|---|
29
+ | **Board** | Arduino Uno (16 MHz), CNC Shield V3 on top, a step driver (DRV8825 or A4988) in each slot used; or an Arduino Mega 2560 (16 MHz) with a DRV8825 on a driver breakout for each axis |
30
+ | **On your computer** | Node 20 or later; the Arduino IDE or `arduino-cli` with the `arduino:avr` core and the `Servo` library, to flash the sketch (`--fqbn arduino:avr:uno`, or `arduino:avr:mega` for the Mega) |
31
+ | **Wiring** | The shoulder on the shield's X slot, the elbow on Y, a third axis (if any) on Z; the home switches on the X and Y limit pins (D9 and D10), a third axis's on D12; the pen servo's signal on D11 (the Z limit pin on a V3.00 shield). `cad machine` writes the wiring sheet |
32
+
33
+ ## Using it
34
+
35
+ 1. Flash the sketch: `arduino-cli compile --fqbn arduino:avr:uno firmware/arm` then `arduino-cli upload -p <port> --fqbn arduino:avr:uno firmware/arm`, or open `firmware/arm/arm.ino` in the Arduino IDE and upload it.
36
+ 2. Write the machine description and a step file: `npx cad machine arm/arm` writes `exports/arm/arm.machine.json`, and `npx cad plot arm/arm projects/arm/drawings/test.svg` writes `exports/arm/arm-test.steps.json`. `npx cad plot arm/arm --calibrate` writes the calibration drawing (a 100 mm square and a circle at three places on the sheet).
37
+ 3. Dry run, with no board: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --dry-run`. It prints each line it would send with the answer the streamer would give, then a summary. `--quiet` prints the summary only. A dry run has no clock, so it takes each block as finished before the next line: its answer to `?` is the positions summed from the blocks so far, with 0 blocks queued.
38
+ 4. Draw: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --port <port>`. It turns the drivers on, homes each axis, sends the file, reports every hundredth line, and turns the drivers off. `--no-home` skips homing.
39
+
40
+ ## A leg on the same streamer
41
+
42
+ The streamer knows only axes and steps, so a leg runs on it as the arm does. The leg's stand (`projects/leg`, with the
43
+ hip's motor on the shield's X slot and the knee's on Y) takes the same sketch, the same drivers and the same sender:
44
+
45
+ 1. Flash the streamer to the stand's Uno, as in step 1 above (`firmware/leg` in the leg's project).
46
+ 2. Write the machine and the gait's step file: `npx cad machine leg/stand` writes `exports/leg/stand.machine.json`, and
47
+ `npx cad plot leg/stand` writes `exports/leg/stand-gait.steps.json`: three cycles of the gait, from the pose the
48
+ assembly shows (`standing`) and back to it. `--cycles 5` plays five, `--pose <name>` starts and ends at another pose,
49
+ and `--period 4` plays a cycle in 4 s. `.preview/leg/stand-gait.svg` draws each axis through the run.
50
+ 3. Dry run: `node projects/leg/send.mjs exports/leg/stand-gait.steps.json --machine exports/leg/stand.machine.json --dry-run`.
51
+ 4. Stand the leg in its pose, then send the file with `--port <port>`. The stand has no home switches, so the streamer
52
+ counts from where the motors are when it starts: the file's first block takes the leg from its pose to the cycle, and
53
+ its last brings it back. At the end the drivers go off and the carriage settles on its stop collars.
54
+
55
+ How the gait becomes blocks:
56
+
57
+ | | |
58
+ |---|---|
59
+ | **A block** | The move from one frame of the gait (48 a cycle) to the next, every axis in it, at the rate that keeps to the gait's period |
60
+ | **Too fast for a motor** | A block that would step an axis past its `maxRate` (the motor's working speed, from `cad machine`) is slowed to it, and the cycle takes longer. `cad plot` says by how much, with a warning when a cycle takes over 5% longer than the gait's period. The stand's gait asks the knee for 11712 steps/s at its 2 s period, past the 5333 of a 17HS4401 at 200 rpm and 1/8 steps, so a cycle takes 2.89 s on the motors |
61
+ | **A joint turning back** | Where a foot lifts off or sets down, a joint reverses. The run slows there so that no axis changes speed by more than its jump at once: an eighth of its `maxRate`, the rate `cad machine` homes it at from rest. It speeds up and slows down at no more than 4 × `maxRate` steps/s², full speed in 0.25 s. Both are estimates: no motor's start-stop rate under load has been measured yet |
62
+ | **From the pose and back** | A move from rest to rest at half the axes' fastest |
63
+
64
+ ## Eight axes on a Mega 2560
65
+
66
+ The quadruped has eight motors, more than the Uno's three. It carries an Arduino Mega 2560, which runs the same
67
+ streamer built for eight axes, and a DRV8825 for each motor on its own driver breakout. One board steps every leg in
68
+ the same blocks; two Unos kept in step would need a clock shared between them, and each would start its blocks when
69
+ its own line arrived. Each motor's wire goes to its breakout's terminals; each breakout's EN, STEP, DIR and GND go to
70
+ one of the Mega's slots, `S0` to `S7`, the streamer's axes 0 to 7. `cad machine leg/quadruped` lists them:
71
+
72
+ | Slot | Axis | STEP | DIR | Home switch |
73
+ |---|---|---|---|---|
74
+ | S0 | fl_hd, the front left hip | D22 | D37 | A8 |
75
+ | S1 | fl_kd, its knee | D23 | D36 | A9 |
76
+ | S2 | fr_hd | D24 | D35 | A10 |
77
+ | S3 | fr_kd | D25 | D34 | A11 |
78
+ | S4 | bl_hd | D26 | D33 | A12 |
79
+ | S5 | bl_kd | D27 | D32 | A13 |
80
+ | S6 | br_hd | D28 | D31 | A14 |
81
+ | S7 | br_kd | D29 | D30 | A15 |
82
+
83
+ The drivers' EN pins all go to D38. STEP on one port (port A) lets the streamer step every axis due on a tick in one
84
+ write, and DIR on another (port C) sets them all in one write at a block's start.
85
+
86
+ 1. Set each breakout's microstep switches to 1/8, as `cad machine` counts them (1600 steps a turn): M0 and M1 on,
87
+ M2 off (the DRV8825's mode table: MODE0 and MODE1 high is 1/8). The breakouts come with every switch on, which is
88
+ 1/32: left like that, every joint moves a quarter as far as the file asks. Set each driver's current too, as on the
89
+ stand (its trimmer, Vref = current / 2 at 0.1 ohm).
90
+ 2. Wire a 12 V supply's 12 V and ground to each breakout's motor terminals. Eight motors take about 6 A, four times
91
+ the stand's 1.5 A for two (an estimate, until measured), past the bench supply: the quadruped lists a Mean Well
92
+ LRS-100-12 (8.5 A) to buy.
93
+ 3. Flash the streamer for the Mega: `arduino-cli compile --fqbn arduino:avr:mega firmware/leg` then
94
+ `arduino-cli upload -p <port> --fqbn arduino:avr:mega firmware/leg`. It says `streamer ready, 8 axes`.
95
+ 4. `npx cad machine leg/quadruped` and `npx cad plot leg/quadruped`: three cycles of the trot from the pose `standing`.
96
+ 5. Dry run: `node projects/leg/send.mjs exports/leg/quadruped-gait.steps.json --machine exports/leg/quadruped.machine.json --dry-run`.
97
+ Without `--machine` the sender writes for the Uno's three axes and refuses the file.
98
+ 6. Stand the robot in its pose, then send with `--port <port>`. A sender whose lines are for one board refuses to send
99
+ to a streamer that says it was built for the other.
100
+
101
+ ## Homing
102
+
103
+ The arm homes on switches: each axis steps towards its switch until it closes (`h`). The legs have no switches yet,
104
+ so the streamer counts from where the motors stand when it starts, and each gait file starts and ends at a pose you
105
+ set by hand. Switches are the way to home here: the DRV8825's current limit is set with its trimmer ("the trimmer
106
+ potentiometer on the board can be used to set the current limit", Pololu's DRV8825 carrier page, product 2133), so the
107
+ streamer cannot turn the current down to home against a stop, and the driver cannot tell a stall (homing without
108
+ switches, as Klipper does it, needs "a stallGuard capable TMC stepper driver", Klipper's TMC drivers page). Against a
109
+ stop at the stand's 0.5 A, a 17HS4401 holds about 0.4 x 0.5 / 1.5 = 0.13 N m, through the 38:1 gearbox at 47%
110
+ 2.4 N m on the printed joint at every homing, five times the 0.48 N m the trot asks of a hip. The streamer and the
111
+ sender already home any axis with a switch (`home` on its joint, as the arm's), on the Mega's A8 to A15 as on the
112
+ shield's limit pins; the leg's printed parts do not yet carry a switch's post and a flag to press it.
113
+
114
+ ## The line protocol
115
+
116
+ 115200 baud, 8 data bits, no parity, 1 stop bit. One command a line, ended by a newline. The streamer answers every
117
+ line once: `ok` when it has taken the line, or `error: <what>` when it cannot. The sender waits for that answer before
118
+ it sends the next line. That is the flow control: a line that finds the queue full is held until a block finishes,
119
+ and only then answered, so the 12-block queue never overruns. A line is at most 95 characters on the Uno and 127 on the
120
+ Mega. Every number is a whole number.
121
+
122
+ The streamer reads a line a character at a time as it arrives, between steps, so a line costs it no more than its bytes
123
+ take on the wire. Because the sender waits for each answer, a block must last at least as long as its own line, the
124
+ newline and the 4-byte answer (`ok`, then a carriage return and a line feed) take to cross the serial line, plus the
125
+ time the USB link holds them: otherwise the queue runs dry and the motors stop between blocks. `send.mjs` refuses such a
126
+ block, naming its line, before it sends anything (see Timing). `cad plot` plans none that short: the arm's task gives
127
+ `"blockTime": 0.011`, the least seconds a move lasts, and a shorter move is slowed until it lasts that long.
128
+
129
+ | Command | Arguments | What it does | Answers |
130
+ |---|---|---|---|
131
+ | `e` | | Drivers on: the motors hold | `ok` |
132
+ | `d` | | Drivers off: the motors go slack | `ok` |
133
+ | `h` | axis, direction, rate, back | Home one axis (0, 1 or 2 on the Uno, 0 to 7 on the Mega): step towards direction (1 or -1) at rate steps/s until its switch closes, then step back off it by back steps, and call that position 0. It waits for the queue to empty first | `ok`; `error: endstop` if the switch has not closed after 60 s; `error: home` for a bad axis or rate |
134
+ | `p` | degrees, milliseconds | Queue the pen servo to degrees, then a wait of milliseconds before the next block | `ok` |
135
+ | `w` | milliseconds | Queue a wait | `ok` |
136
+ | `m` | a, b, c, entry, peak, exit, accel, up, down | Queue a block: signed steps on each axis (axes 0, 1 and 2 on the Uno; eight numbers, axes 0 to 7, on the Mega); the major axis's rate at entry, at its peak and at exit (steps/s); its acceleration (steps/s²); the major axis's steps spent speeding up, and slowing down. The major axis is the one with the most steps; the others step in proportion | `ok`; `error: block` if it moves nothing or its peak or acceleration is 0; `error: rate` if a rate is past MAX_RATE |
137
+ | `?` | | Report | `q <pos0> <pos1> <pos2> <queued>` (eight positions on the Mega): positions in steps as of the last step taken, and the blocks waiting |
138
+ | `!` | | Stop at once and empty the queue; the drivers stay on | `ok` |
139
+ | | | A line over 95 characters (127 on the Mega), or a number in it that is not a whole number | `error: line` |
140
+ | | | Anything else | `error: command` |
141
+
142
+ On power-up, and each time the serial port opens (which resets the board), the streamer prints
143
+ `streamer ready, 3 axes` (`8 axes` on the Mega). The sender waits 2.5 s for it, and refuses to send lines written for
144
+ the other board.
145
+
146
+ ## Timing
147
+
148
+ | Figure | Value | Source |
149
+ |---|---|---|
150
+ | MAX_RATE, the fastest block the streamer takes | 8000 steps/s on the major axis | `RATE_LIMIT` in `arm.ino`, and `MAX_RATE` in `send.mjs` (a test holds them equal) |
151
+ | What the worked arm asks | up to 8000 steps/s an axis (`maxRate`: 300 rpm of a 200-step motor at 1/8 microstepping is 300 × 1600 / 60), 7799 steps/s in the test drawing | `cad machine arm/arm` and `cad plot` |
152
+ | The loop's own ceiling while speeding up, one, two and three axes stepping at once | 16547, 15288 and 14208 steps/s | measured on a simulated 16 MHz Uno (avr8js), the sketch built with RATE_LIMIT raised: the mean over a long block's middle steps |
153
+ | The loop's own ceiling while slowing down, one, two and three axes | 16376, 15142 and 14082 steps/s | the same |
154
+ | The loop's own ceiling at a block's cruise, one, two and three axes | 35777, 30370 and 26384 steps/s | the same |
155
+ | On the Mega, one to eight axes, speeding up | 15726, 14587, 13601, 12741, 11982, 11309, 10708 and 10167 steps/s | the same, on a simulated 16 MHz Mega 2560 |
156
+ | On the Mega, slowing down | 15504, 14395, 13435, 12594, 11853, 11194, 10604 and 10074 steps/s | the same |
157
+ | On the Mega, at the cruise | 33135, 28452, 24929, 22183, 19982, 18177, 16672 and 15397 steps/s | the same |
158
+ | What the quadruped asks | up to 5333 steps/s an axis (200 rpm at 1/8: 200 x 1600 / 60) | `cad machine leg/quadruped` |
159
+ | A byte on the serial line | 86.8 µs | 115200 baud, 10 bits a byte (start, 8 data, stop) |
160
+ | A line's cost to the streamer | its bytes, its newline and the 4-byte answer on the wire, and nothing more measurable | measured on the simulated Uno: a 36-character block line and its answer take 3.55 ms there, against 3.56 ms on the wire (before the streamer parsed as it read, 3.87 ms) |
161
+ | The USB turnaround | 5.1 ms, an estimate | the Uno's USB chip (an ATmega16U2 running Arduino-usbserial) passes the answer on when its timer 0 overflows, 256 × 256 / 16 MHz = 4.1 ms (`Arduino-usbserial.c` in ArduinoCore-avr, read 2026-11-23); then up to a 1 ms USB frame for the next line. Copies with a CH340 USB chip differ |
162
+ | The least time a block lasts | (characters in its line + 1 + 4) × 86.8 µs + 5.1 ms: 8.66 ms for a 36-character line, 70 steps at MAX_RATE | `leastBlockTime` in `send.mjs`, from the three rows above |
163
+ | The arm's planned least block time | 0.011 s (`task.blockTime` in `assemblies/arm.json`) | the least time for a 60-character line, 10.74 ms; the worked file's block lines are 34 to 41 characters |
164
+ | STEP pulse width | 3.06 µs high | measured on the simulated Uno; the DRV8825 needs 1.9 µs, the A4988 1 µs (Pololu's DRV8825 carrier page, product 2133, from TI's datasheet) |
165
+ | Uno clock | 16 MHz | Arduino Uno Rev3 |
166
+
167
+ The slowest of the Uno's nine ceilings, three axes slowing down at 14082 steps/s, is 1.76 times MAX_RATE; the slowest
168
+ of the Mega's twenty-four, eight axes slowing down at 10074 steps/s, is 1.26 times MAX_RATE and 1.89 times the 5333 the
169
+ quadruped asks. Each axis's figures are worked out at a block's start (its steps without their sign, the way it steps,
170
+ its pin), and only the axes that move are stepped: the Uno's three-axis ceilings rose 13% with that (12428 to 14082
171
+ slowing down), and the Mega's eight-axis one from 8115 to 10074. A step that changes
172
+ speed costs a float multiply and a division (gap = 1000000 / rate), which is why speeding up and slowing down are slower
173
+ than the cruise (3.30 times MAX_RATE on the Uno), where the gap stays as it is. Past 5000 steps/s the speed is worked out every
174
+ other step, over both steps' time: done on every step, three axes slowing down reached only 8904 steps/s, and with lines
175
+ arriving the streamer fell 8% behind on short blocks. The simulation fails if any of them falls under MAX_RATE.
176
+
177
+ The ceilings are measured with one long block and no serial traffic, so they do not show what a stream of short blocks
178
+ costs. The simulation streams those too: the shortest blocks the sender passes, at MAX_RATE on three axes, cruising
179
+ (29 steps, 3.63 ms) and slowing down on every step (32 steps, 4.0 ms), with no USB turnaround since the simulation has no
180
+ USB link. Both keep to their planned time (0.2500 s of 0.2500 s, and 0.2519 s of 0.2519 s); the simulation fails if
181
+ either is more than 1% behind. On the Mega the same, on eight axes: 39 steps (4.88 ms) cruising and 42 (5.25 ms)
182
+ slowing down, 0.2534 s of 0.2534 s and 0.2519 s of 0.2519 s. Before the streamer parsed as it read, the same streams took 8% and 16% longer, and
183
+ 3-axis blocks of 20 steps at MAX_RATE took 55% longer: such blocks are now refused by the sender.
184
+
185
+ A step that an interrupt (the serial line, the clock, the servo) or a block's start delays is caught up at once, so one
186
+ gap can be as long as about 240 µs and the next as short as about 50 µs; the steps keep to their planned times on
187
+ average. The simulation runs the compiled program an instruction at a time, each taking its cycles at 16 MHz. A real
188
+ board has not yet been timed: your bench test does that, and the USB turnaround with it.
189
+
190
+ ## How the sketch is checked
191
+
192
+ `node scripts/firmware.mjs` (in the kit's repository) compiles every sketch for `arduino:avr:uno`, and the streamer for
193
+ `arduino:avr:mega` too, and fails on a compile error. With `--simulate <steps file> --machine <machine file>` it also
194
+ runs this streamer on a simulated board, the Uno or the Mega as the machine's controller says, and fails when any of
195
+ these does not hold. The two flags can be given again for another step file: the kit's tests stream the arm's drawing,
196
+ the stand's gait and the quadruped's trot, each with its own machine, and measure the loop's own ceilings once on each
197
+ board. On the simulated Mega the trot's 148 lines stream in 14.43 s against 14.52 s planned, every one of its
198
+ 178596 steps counted and the streamer's own report back at 0 on all eight axes.
199
+
200
+ | Check | Held to |
201
+ |---|---|
202
+ | Every line answered | `ok`, homing included |
203
+ | Homing | each axis stops at its switch (placed 300 steps away) and backs off by `back` steps |
204
+ | Steps | each axis's step count and its net position equal the step file's sums, and the streamer's own `?` report agrees |
205
+ | Keeping up | the moves take no more than 5% longer than `cad plot` planned |
206
+ | Short blocks | the shortest blocks the sender passes, streamed at MAX_RATE on every axis (three, or eight), cruising and slowing down on every step, take no more than 1% longer than planned |
207
+ | MAX_RATE | a block 1 step/s past it is answered `error: rate`, a block at it `ok` |
208
+ | Ceiling | the loop steps one to all its axes faster than MAX_RATE at the cruise, speeding up and slowing down (nine figures on the Uno, twenty-four on the Mega), and no axis of the machine asks more than MAX_RATE |
209
+ | STEP pulse | at least 1.9 µs high |
@@ -0,0 +1,256 @@
1
+ // A streamer for a machine's stepper axes: it takes synchronised step blocks over serial and moves. The same program runs
2
+ // an arm or a leg's stand on an Arduino Uno with a CNC Shield V3 (three axes), and a quadruped's eight axes on an Arduino
3
+ // Mega 2560 with a step driver for each on a breakout; the board it is built for picks its pins (see BOARD below).
4
+ // Not a general firmware. It knows nothing of the machine: cad plot does the maths and send.mjs sends the result.
5
+ // 115200 baud, one command a line. Every line is answered "ok" once it is taken, or "error: ..." if it can't be; send the
6
+ // next line only after the answer: that is the flow control, and the buffer can never overrun.
7
+ //
8
+ // e drivers on (the motors hold)
9
+ // d drivers off
10
+ // h <axis> <dir> <rate> <back> home an axis (0 to AXES - 1): step towards dir (1 or -1) at rate steps/s until its
11
+ // endstop closes, then come back off it by back steps. Answers "ok" when done, "error: endstop" if none in 60 s
12
+ // p <deg> <ms> the pen servo to deg, then wait ms before anything after it
13
+ // w <ms> wait
14
+ // m <a> <b> <c> <entry> <peak> <exit> <accel> <up> <down>
15
+ // a block: signed steps for each of the AXES axes (three on the Uno, eight on the Mega), then
16
+ // the major axis's step rate at entry, peak and exit
17
+ // (steps/s), its acceleration (steps/s²), and the major steps spent speeding up and slowing down.
18
+ // "error: rate" if its peak is past MAX_RATE, "error: block" if it moves nothing
19
+ // (a block must last as long as its line and answer take to cross the serial line: send.mjs
20
+ // refuses a shorter one, and cad plot plans none shorter than the task's blockTime)
21
+ // ? prints "q <pos0> <pos1> ... <blocks queued>", a position for each axis (in steps, as of the last step)
22
+ // ! stop at once, empty the queue, drivers stay on: answers "ok"
23
+ //
24
+ // "error: line" if a line is over LINE_MAX characters (95 on the Uno, 127 on the Mega) or a number in it is not a whole number.
25
+ //
26
+ // Timing: steps are timed in the main loop from micros(), with serial read between them, so the servo library keeps its
27
+ // timer. A line is parsed a character at a time as it arrives, so no step waits for a whole line to be read, and a block
28
+ // that follows another keeps its time: its first step is one gap after the last block's last. The step pins are all on one
29
+ // port (the Uno's port D, D2 to D4; the Mega's port A, D22 to D29), so the axes due on a tick are stepped in one write, and
30
+ // so are the direction pins (the Uno's D5 to D7, also port D; the Mega's port C, D37 down to D30). A step that changes
31
+ // speed costs a division; past 5000 steps/s that is done every other step, over both steps' time. MAX_RATE is the
32
+ // fastest block it takes: on a simulated 16 MHz Uno and Mega (scripts/firmware.mjs --simulate, in CI) the loop keeps up
33
+ // with more than that with all its axes stepping at once, speeding up and slowing down as well as at the cruise, and with
34
+ // the shortest blocks the sender passes streaming in.
35
+ // Compiled for the Uno and the Mega and run on simulated ones in CI; moving hardware is a bench test (the machine's measured
36
+ // milestone).
37
+ #include <Servo.h>
38
+
39
+ // BOARD. The pins come from the board the sketch is compiled for. Uno: the CNC Shield V3's (its user guide). Mega 2560:
40
+ // chosen so that each set is one port (ArduinoCore-avr's variants/mega/pins_arduino.h): STEP on D22 to D29 (PA0 to PA7),
41
+ // DIR on D37 to D30 (PC0 to PC7), the home switches on A8 to A15 (PK0 to PK7), the drivers' shared enable on D38.
42
+ #if defined(__AVR_ATmega2560__)
43
+ #define AXES 8
44
+ #define STEP_PORT PORTA
45
+ #define DIR_PORT PORTC
46
+ const uint8_t STEP[AXES] = { 22, 23, 24, 25, 26, 27, 28, 29 }, DIR[AXES] = { 37, 36, 35, 34, 33, 32, 31, 30 };
47
+ const uint8_t LIMIT[AXES] = { A8, A9, A10, A11, A12, A13, A14, A15 }, ENABLE_PIN = 38, PEN_PIN = 11;
48
+ const uint8_t STEP_MASK[AXES] = { _BV(PA0), _BV(PA1), _BV(PA2), _BV(PA3), _BV(PA4), _BV(PA5), _BV(PA6), _BV(PA7) }; // the STEP pins' bits in PORTA
49
+ const uint8_t DIR_MASK[AXES] = { _BV(PC0), _BV(PC1), _BV(PC2), _BV(PC3), _BV(PC4), _BV(PC5), _BV(PC6), _BV(PC7) }; // the DIR pins' bits in PORTC
50
+ const uint8_t LINE_MAX = 127;
51
+ #elif defined(__AVR_ATmega328P__)
52
+ #define AXES 3
53
+ #define STEP_PORT PORTD
54
+ #define DIR_PORT PORTD
55
+ const uint8_t STEP[AXES] = { 2, 3, 4 }, DIR[AXES] = { 5, 6, 7 }, LIMIT[AXES] = { 9, 10, 12 }, ENABLE_PIN = 8, PEN_PIN = 11;
56
+ const uint8_t STEP_MASK[AXES] = { _BV(PD2), _BV(PD3), _BV(PD4) }; // the STEP pins' bits in PORTD
57
+ const uint8_t DIR_MASK[AXES] = { _BV(PD5), _BV(PD6), _BV(PD7) }; // the DIR pins' bits in PORTD
58
+ const uint8_t LINE_MAX = 95;
59
+ #else
60
+ #error "the streamer is written for an Arduino Uno (ATmega328P) under a CNC Shield V3, or an Arduino Mega 2560"
61
+ #endif
62
+
63
+ #ifndef RATE_LIMIT
64
+ #define RATE_LIMIT 8000
65
+ #endif
66
+ const long MAX_RATE = RATE_LIMIT; // steps/s on a block's major axis; the simulation builds with -DRATE_LIMIT raised to find the loop's own limit
67
+ const uint8_t QUEUE = 12;
68
+ const long MIN_RATE = 80; // steps/s: slower than this a block would take seconds to start
69
+
70
+ enum Kind : uint8_t { MOVE, PEN, WAIT };
71
+ struct Block { Kind kind; long steps[AXES]; long major, entry, peak, exit_, accel, up, down; };
72
+ Block queue[QUEUE];
73
+ uint8_t head = 0, tail = 0;
74
+ inline uint8_t count() { return head >= tail ? head - tail : head + QUEUE - tail; }
75
+
76
+ Servo pen;
77
+ // The line being read, taken a character at a time as it arrives, between steps: its command letter, then up to ARGS
78
+ // whole numbers, each built up digit by digit. Parsing a whole line at its end (strtol) held the steps up 520 to 600 µs.
79
+ const uint8_t ARGS = AXES + 6;
80
+ char cmd = 0;
81
+ long arg[ARGS];
82
+ uint8_t len = 0, nargs = 0;
83
+ bool inNumber = false, negative = false, bad = false;
84
+ bool pending = false; // a whole line is waiting for room in the queue
85
+
86
+ // The block being run
87
+ bool running = false;
88
+ Block cur;
89
+ long done = 0;
90
+ // Each axis as the loop steps it, in one record so a step reaches all of it from one address: its position (steps, as of
91
+ // its last step), its Bresenham count, its steps in the block without their sign and the step each takes on the position
92
+ // (1 or -1), and its STEP pin's bit. A block's start lists the axes that move, so the Mega's eight in a block that moves
93
+ // two cost the loop no more than two.
94
+ struct Axis { long position, acc, dist; int8_t sign; uint8_t mask; };
95
+ Axis ax[AXES];
96
+ Axis *moving[AXES];
97
+ uint8_t nMoving = 0;
98
+ unsigned long nextAt = 0, waitUntil = 0;
99
+ bool waiting = false;
100
+ bool chained = false; // the last block ended on a step with the next due one gap after it: the next block keeps that time
101
+ float rate = 0, gap = 0; // steps/s, and the µs from this step to the next
102
+ // The block's speed figures as floats, worked out once at its start: the acceleration per µs, the peak, the least exit
103
+ // rate, and the step from which it slows down
104
+ float accelUs = 0, peakF = 0, floorF = 0;
105
+ long downFrom = 0;
106
+ // A gap shorter than this (faster than 5000 steps/s), µs: the speed is worked out every other step, over both steps' time.
107
+ // A speed change costs a float multiply and a division, about half the 125 µs between steps at MAX_RATE, and the loop
108
+ // reads the serial line too; done every step the streamer fell behind slowing down from MAX_RATE with lines arriving.
109
+ const float FINE_GAP = 200;
110
+ bool skipped = false; // the last step in a ramp left its speed change to this one
111
+
112
+ void setup() {
113
+ Serial.begin(115200);
114
+ for (uint8_t i = 0; i < AXES; i++) { pinMode(STEP[i], OUTPUT); pinMode(DIR[i], OUTPUT); pinMode(LIMIT[i], INPUT_PULLUP); }
115
+ pinMode(ENABLE_PIN, OUTPUT);
116
+ digitalWrite(ENABLE_PIN, HIGH); // off until asked: the shield's enable is active low
117
+ pen.attach(PEN_PIN);
118
+ Serial.print(F("streamer ready, ")); Serial.print(AXES); Serial.println(F(" axes"));
119
+ }
120
+
121
+ // A STEP pulse on the axes in mask, 3 µs high (delayMicroseconds(3) gave 2.06 µs on the simulated Uno, too near the
122
+ // DRV8825's 1.9 µs minimum; the A4988's is 1 µs)
123
+ void pulse(uint8_t mask) { STEP_PORT |= mask; delayMicroseconds(4); STEP_PORT &= ~mask; }
124
+
125
+ bool home(uint8_t axis, int dir, long hz, long back) {
126
+ digitalWrite(DIR[axis], dir > 0 ? HIGH : LOW);
127
+ unsigned long gap = 1000000UL / hz, start = millis();
128
+ while (digitalRead(LIMIT[axis]) == HIGH) {
129
+ if (millis() - start > 60000UL) return false;
130
+ pulse(STEP_MASK[axis]); delayMicroseconds(gap);
131
+ }
132
+ digitalWrite(DIR[axis], dir > 0 ? LOW : HIGH);
133
+ for (long i = 0; i < back; i++) { pulse(STEP_MASK[axis]); delayMicroseconds(gap); }
134
+ ax[axis].position = 0;
135
+ return true;
136
+ }
137
+
138
+ // One character of a line: the first is the command, then numbers separated by spaces, a minus sign before a negative one
139
+ void endNumber() { if (inNumber) { if (negative) arg[nargs] = -arg[nargs]; nargs++; inNumber = false; } }
140
+ void take(char c) {
141
+ if (!len++) { cmd = c; nargs = 0; inNumber = false; bad = false; return; }
142
+ if (len > LINE_MAX) { bad = true; return; }
143
+ if (c == ' ') { endNumber(); return; }
144
+ if (!inNumber) {
145
+ if (nargs >= ARGS) { bad = true; return; }
146
+ inNumber = true; negative = c == '-'; arg[nargs] = 0;
147
+ if (negative) return;
148
+ }
149
+ if (c < '0' || c > '9') { bad = true; return; }
150
+ arg[nargs] = arg[nargs] * 10 + (c - '0');
151
+ }
152
+ long a(uint8_t i) { return i < nargs ? arg[i] : 0; } // a number missing from the end of a line is 0
153
+
154
+ // True if the line was dealt with; false if it has to wait for room in the queue
155
+ bool obey() {
156
+ char c = cmd;
157
+ if (bad) { Serial.println(F("error: line")); return true; }
158
+ if (c == 'e') { digitalWrite(ENABLE_PIN, LOW); Serial.println(F("ok")); return true; }
159
+ if (c == 'd') { digitalWrite(ENABLE_PIN, HIGH); Serial.println(F("ok")); return true; }
160
+ if (c == '!') { head = tail = 0; running = false; waiting = false; chained = false; Serial.println(F("ok")); return true; }
161
+ if (c == '?') { Serial.print(F("q ")); for (uint8_t i = 0; i < AXES; i++) { Serial.print(ax[i].position); Serial.print(' '); } Serial.println(count()); return true; }
162
+ if (c == 'h') {
163
+ if (running || count()) return false; // home only when everything before it is finished
164
+ long axis = a(0), dir = a(1), hz = a(2), back = a(3);
165
+ if (axis < 0 || axis >= AXES || hz <= 0) { Serial.println(F("error: home")); return true; }
166
+ Serial.println(home(axis, dir, hz, back) ? F("ok") : F("error: endstop"));
167
+ return true;
168
+ }
169
+ if (c != 'm' && c != 'p' && c != 'w') { Serial.println(F("error: command")); return true; }
170
+ if (count() >= QUEUE - 1) return false;
171
+ Block &b = queue[head];
172
+ if (c == 'm') {
173
+ b.kind = MOVE;
174
+ b.major = 0;
175
+ for (uint8_t i = 0; i < AXES; i++) { b.steps[i] = a(i); if (labs(b.steps[i]) > b.major) b.major = labs(b.steps[i]); }
176
+ b.entry = a(AXES); b.peak = a(AXES + 1); b.exit_ = a(AXES + 2); b.accel = a(AXES + 3); b.up = a(AXES + 4); b.down = a(AXES + 5);
177
+ if (b.major == 0 || b.peak <= 0 || b.accel <= 0) { Serial.println(F("error: block")); return true; }
178
+ if (b.peak > MAX_RATE || b.entry > MAX_RATE || b.exit_ > MAX_RATE) { Serial.println(F("error: rate")); return true; }
179
+ } else if (c == 'p') { b.kind = PEN; b.major = a(0); b.up = a(1); }
180
+ else { b.kind = WAIT; b.up = a(0); }
181
+ if (++head == QUEUE) head = 0;
182
+ Serial.println(F("ok"));
183
+ return true;
184
+ }
185
+
186
+ void readSerial() {
187
+ if (pending) { if (obey()) pending = false; else return; }
188
+ while (Serial.available()) {
189
+ char c = Serial.read();
190
+ if (c == '\n' || c == '\r') {
191
+ if (!len) continue;
192
+ endNumber(); len = 0;
193
+ if (!obey()) pending = true;
194
+ return;
195
+ }
196
+ take(c);
197
+ }
198
+ }
199
+
200
+ void start() {
201
+ cur = queue[tail];
202
+ if (++tail == QUEUE) tail = 0;
203
+ if (cur.kind != MOVE) chained = false;
204
+ if (cur.kind == PEN) { pen.write(cur.major); waitUntil = millis() + cur.up; waiting = true; return; }
205
+ if (cur.kind == WAIT) { waitUntil = millis() + cur.up; waiting = true; return; }
206
+ // the direction pins in one write, and each axis's Bresenham count from half the block (a shift: a long division here
207
+ // cost about 600 cycles an axis between one block's last step and the next block's first)
208
+ uint8_t dirs = 0, all = 0;
209
+ nMoving = 0;
210
+ for (uint8_t i = 0; i < AXES; i++) {
211
+ all |= DIR_MASK[i]; if (cur.steps[i] >= 0) dirs |= DIR_MASK[i];
212
+ Axis &x = ax[i];
213
+ x.acc = cur.major >> 1; x.dist = labs(cur.steps[i]); x.sign = cur.steps[i] < 0 ? -1 : 1; x.mask = STEP_MASK[i];
214
+ if (x.dist) moving[nMoving++] = &x;
215
+ }
216
+ DIR_PORT = (DIR_PORT & ~all) | dirs;
217
+ rate = max(cur.entry, MIN_RATE); gap = 1000000.0 / rate;
218
+ accelUs = cur.accel * 1e-6f; peakF = cur.peak; floorF = max(cur.exit_, MIN_RATE); downFrom = cur.major - cur.down; skipped = false;
219
+ done = 0; running = true;
220
+ if (!chained) nextAt = micros(); // from rest, its first step now; following a block, one gap after that block's last
221
+ chained = false;
222
+ }
223
+
224
+ void tick() {
225
+ if ((long)(micros() - nextAt) < 0) return;
226
+ uint8_t mask = 0;
227
+ const long major = cur.major;
228
+ for (uint8_t j = 0; j < nMoving; j++) {
229
+ Axis *x = moving[j];
230
+ x->acc += x->dist;
231
+ if (x->acc >= major) { x->acc -= major; mask |= x->mask; x->position += x->sign; }
232
+ }
233
+ pulse(mask);
234
+ done++;
235
+ if (done >= cur.major) { running = false; nextAt += (unsigned long)gap; chained = true; return; }
236
+ // Constant acceleration: dv = a dt, dt this step's gap (1 / v), or two gaps when the last step left its change to this one
237
+ // (the gap is the same for both: it changes only here). The last step speeding up always changes, so the cruise is at peak.
238
+ bool up = done < cur.up;
239
+ if (up || done >= downFrom) {
240
+ if (gap >= FINE_GAP || skipped || done + 1 == cur.up) {
241
+ float dv = accelUs * (skipped ? gap + gap : gap);
242
+ skipped = false;
243
+ if (up) { rate += dv; if (rate > peakF) rate = peakF; }
244
+ else { rate -= dv; if (rate < floorF) rate = floorF; }
245
+ gap = 1000000.0 / rate;
246
+ } else skipped = true;
247
+ }
248
+ nextAt += (unsigned long)gap;
249
+ }
250
+
251
+ void loop() {
252
+ readSerial();
253
+ if (waiting) { if ((long)(millis() - waitUntil) >= 0) waiting = false; return; }
254
+ if (running) { tick(); return; }
255
+ if (count()) start(); else chained = false; // the queue ran dry: the motors stopped, and the next block starts from rest
256
+ }