periph 1.3.3 → 1.4.0

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.
Files changed (41) hide show
  1. package/README.md +9 -0
  2. package/examples/adc_dac/es8311/complete.js +80 -0
  3. package/examples/adc_dac/es8311/demo.js +59 -0
  4. package/examples/adc_dac/es8311/minimal.js +18 -0
  5. package/examples/adc_dac/mcp4xxx/complete.js +97 -0
  6. package/examples/adc_dac/mcp4xxx/demo.js +76 -0
  7. package/examples/adc_dac/mcp4xxx/minimal.js +22 -0
  8. package/examples/imu/qmi8658a/complete.js +134 -0
  9. package/examples/imu/qmi8658a/demo.js +81 -0
  10. package/examples/imu/qmi8658a/minimal.js +22 -0
  11. package/examples/motor/tmc2130/complete.js +138 -0
  12. package/examples/motor/tmc2130/demo.js +96 -0
  13. package/examples/motor/tmc2130/minimal.js +30 -0
  14. package/examples/motor/tmc2208/complete.js +92 -0
  15. package/examples/motor/tmc2208/demo.js +85 -0
  16. package/examples/motor/tmc2208/minimal.js +25 -0
  17. package/examples/motor/tmc2209/complete.js +106 -0
  18. package/examples/motor/tmc2209/demo.js +97 -0
  19. package/examples/motor/tmc2209/minimal.js +25 -0
  20. package/examples/motor/tmc5160/complete.js +205 -0
  21. package/examples/motor/tmc5160/demo.js +104 -0
  22. package/examples/motor/tmc5160/minimal.js +35 -0
  23. package/examples/power/axp2101/complete.js +135 -0
  24. package/examples/power/axp2101/demo.js +68 -0
  25. package/examples/power/axp2101/minimal.js +24 -0
  26. package/examples/rtc/pcf85063a/complete.js +68 -0
  27. package/examples/rtc/pcf85063a/demo.js +76 -0
  28. package/examples/rtc/pcf85063a/minimal.js +20 -0
  29. package/package.json +1 -1
  30. package/src/chips/adc_dac/es8311.js +621 -0
  31. package/src/chips/adc_dac/mcp4xxx.js +982 -0
  32. package/src/chips/imu/qmi8658a.js +1011 -0
  33. package/src/chips/motor/tmc2130.js +537 -0
  34. package/src/chips/motor/tmc2208.js +490 -0
  35. package/src/chips/motor/tmc2209.js +565 -0
  36. package/src/chips/motor/tmc5160.js +900 -0
  37. package/src/chips/power/axp2101.js +968 -0
  38. package/src/chips/rtc/pcf85063a.js +482 -0
  39. package/src/connection/uart.js +9 -0
  40. package/src/connection/uart_mock.js +65 -0
  41. package/src/discovery/registry.js +25 -0
@@ -0,0 +1,537 @@
1
+ 'use strict';
2
+
3
+ const REG_GCONF = 0x00;
4
+ const REG_GSTAT = 0x01;
5
+ const REG_IOIN = 0x04;
6
+ const REG_IHOLD_IRUN = 0x10;
7
+ const REG_TPOWERDOWN = 0x11;
8
+ const REG_TSTEP = 0x12;
9
+ const REG_TPWMTHRS = 0x13;
10
+ const REG_TCOOLTHRS = 0x14;
11
+ const REG_THIGH = 0x15;
12
+ const REG_XDIRECT = 0x2D;
13
+ const REG_VDCMIN = 0x33;
14
+ const REG_MSLUT0 = 0x60;
15
+ const REG_MSLUTSEL = 0x68;
16
+ const REG_MSLUTSTART = 0x69;
17
+ const REG_MSCNT = 0x6A;
18
+ const REG_MSCURACT = 0x6B;
19
+ const REG_CHOPCONF = 0x6C;
20
+ const REG_COOLCONF = 0x6D;
21
+ const REG_DCCTRL = 0x6E;
22
+ const REG_DRV_STATUS = 0x6F;
23
+ const REG_PWMCONF = 0x70;
24
+ const REG_PWM_SCALE = 0x71;
25
+ const REG_LOST_STEPS = 0x73;
26
+
27
+ const READABLE = new Set([0x00, 0x01, 0x04, 0x12, 0x2D, 0x6A, 0x6B, 0x6C, 0x6F, 0x71, 0x73]);
28
+ const WRITABLE = new Set([0x00, 0x10, 0x11, 0x13, 0x14, 0x15, 0x2D, 0x33, 0x60, 0x61, 0x62, 0x63,
29
+ 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6C, 0x6D, 0x6E, 0x70]);
30
+
31
+ const GCONF_I_SCALE_ANALOG = 1 << 0;
32
+ const GCONF_INTERNAL_RSENSE = 1 << 1;
33
+ const GCONF_EN_PWM_MODE = 1 << 2;
34
+ const GCONF_SHAFT = 1 << 4;
35
+ const GCONF_SMALL_HYSTERESIS = 1 << 14;
36
+ const GCONF_STOP_ENABLE = 1 << 15;
37
+ const GCONF_DIRECT_MODE = 1 << 16;
38
+
39
+ const VERSION = 0x11;
40
+ const CHOPCONF_DEFAULT = 0x140100C3;
41
+ const PWMCONF_DEFAULT = 0x000401C8;
42
+
43
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
44
+ const toSigned = (value, bits) => {
45
+ const v = value & ((1 << bits) - 1);
46
+ return (v & (1 << (bits - 1))) ? v - (1 << bits) : v;
47
+ };
48
+
49
+ /**
50
+ * Trinamic TMC2130 stepper driver over SPI -- minimal interface.
51
+ *
52
+ * Brings the driver up in SPI mode (internal reference, StealthChop below
53
+ * TPWMTHRS = 500 and SpreadCycle above it, 16 microsteps with 256-step
54
+ * interpolation, 0.5 A RMS run current) and moves the motor with STEP/DIR
55
+ * pulses -- the chip has no internal step generator. The 40-bit datagram
56
+ * framing and the pipelined two-datagram read are handled here; the
57
+ * connection only needs `write` / `writeRead` (SPI Mode 3, MSB first).
58
+ *
59
+ * The constructor performs no I/O; call `await init()` before use.
60
+ */
61
+ class TMC2130Minimal {
62
+ /**
63
+ * @param {object} connection - SPI connection configured for Mode 3.
64
+ * @param {object} stepPin - OutputPin wired to STEP.
65
+ * @param {object} dirPin - OutputPin wired to DIR.
66
+ * @param {object} [options]
67
+ * @param {number} [options.rSenseOhm=0.11] - External sense resistor in ohm.
68
+ * @param {object|null} [options.enPin=null] - OutputPin wired to ENN (active low).
69
+ */
70
+ constructor(connection, stepPin, dirPin, options = {}) {
71
+ this._conn = connection;
72
+ this._stepPin = stepPin;
73
+ this._dirPin = dirPin;
74
+ this._rSense = options.rSenseOhm ?? 0.11;
75
+ this._enPin = options.enPin ?? null;
76
+ this._fclk = options.fclkHz ?? 12000000;
77
+ this._shadow = new Map();
78
+ this._microsteps = 16;
79
+ this._vsense = false;
80
+ this._autoVsense = true;
81
+ this._internalRsense = false;
82
+ this._toff = 3;
83
+ this._runCs = 0;
84
+ this._holdCs = 0;
85
+ this._iholdDelay = 6;
86
+ }
87
+
88
+ async _writeReg(reg, value, verify = false) {
89
+ value = value >>> 0;
90
+ await this._conn.write(Buffer.from([(reg | 0x80) & 0xFF,
91
+ (value >>> 24) & 0xFF, (value >>> 16) & 0xFF, (value >>> 8) & 0xFF, value & 0xFF]));
92
+ this._shadow.set(reg, value);
93
+ if (verify) {
94
+ const mirror = await this._secondDatagram();
95
+ if (mirror !== value) throw new Error('TMC2130: write mirror mismatch (reg 0x' + reg.toString(16) + ')');
96
+ }
97
+ }
98
+
99
+ // A harmless GCONF read request whose reply is the previous datagram's
100
+ // answer (pipelined protocol). Never GSTAT, which clears on read.
101
+ async _secondDatagram() {
102
+ const reply = Buffer.from(await this._conn.writeRead(Buffer.from([REG_GCONF]), 4));
103
+ if (reply.length !== 4) throw new Error('TMC2130: short read');
104
+ return reply.readUInt32BE(0);
105
+ }
106
+
107
+ async _readReg(reg) {
108
+ await this._conn.writeRead(Buffer.from([reg & 0x7F]), 4);
109
+ return this._secondDatagram();
110
+ }
111
+
112
+ async _modify(reg, mask, value) {
113
+ const current = this._shadow.get(reg) ?? 0;
114
+ await this._writeReg(reg, ((current & ~mask) | (value & mask)) >>> 0);
115
+ }
116
+
117
+ _csFor(rmsA, vsense) {
118
+ const vfs = vsense ? 0.180 : 0.325;
119
+ const cs = Math.round(rmsA * Math.SQRT2 * (this._rSense + 0.020) * 32 / vfs) - 1;
120
+ return Math.max(0, Math.min(31, cs));
121
+ }
122
+
123
+ // Returns [cs, vsense]; picks vsense automatically unless fixed.
124
+ _currentToCs(rmsA, vsense) {
125
+ if (this._internalRsense) throw new RangeError('set_current is unsupported with internal Rsense');
126
+ if (vsense !== undefined) return [this._csFor(rmsA, vsense), vsense];
127
+ if (!this._autoVsense) return [this._csFor(rmsA, this._vsense), this._vsense];
128
+ const cs = this._csFor(rmsA, false);
129
+ if (cs < 16) {
130
+ const high = this._csFor(rmsA, true);
131
+ if (high <= 31) return [high, true];
132
+ }
133
+ return [cs, false];
134
+ }
135
+
136
+ async _writeIholdIrun(verify = false) {
137
+ await this._writeReg(REG_IHOLD_IRUN,
138
+ (this._holdCs & 0x1F) | ((this._runCs & 0x1F) << 8) | ((this._iholdDelay & 0xF) << 16), verify);
139
+ }
140
+
141
+ /**
142
+ * Probe the chip, apply the default configuration and verify the writes.
143
+ * @returns {Promise<void>}
144
+ * @throws {Error} If the chip does not answer, has an unexpected identity
145
+ * or a write is not mirrored back.
146
+ */
147
+ async init() {
148
+ if (this._enPin) await this._enPin.set(true);
149
+ await sleep(10);
150
+ const ioin = await this._readReg(REG_IOIN);
151
+ if (((ioin >>> 24) & 0xFF) !== VERSION || !(ioin & (1 << 6))) {
152
+ throw new Error('TMC2130 not found (IOIN=0x' + ioin.toString(16) + ')');
153
+ }
154
+ await this._readReg(REG_GSTAT);
155
+ const [cs, vsense] = this._currentToCs(0.5);
156
+ this._runCs = cs;
157
+ this._holdCs = Math.floor(cs / 3);
158
+ this._vsense = vsense;
159
+ await this._writeReg(REG_CHOPCONF, (CHOPCONF_DEFAULT | (vsense ? (1 << 17) : 0)) >>> 0, true);
160
+ await this._writeIholdIrun(true);
161
+ await this._writeReg(REG_TPOWERDOWN, 10, true);
162
+ await this._writeReg(REG_GCONF, GCONF_EN_PWM_MODE, true);
163
+ await this._writeReg(REG_TPWMTHRS, 500, true);
164
+ await this._writeReg(REG_PWMCONF, PWMCONF_DEFAULT, true);
165
+ if ((await this._readReg(REG_GCONF)) !== this._shadow.get(REG_GCONF) ||
166
+ (await this._readReg(REG_CHOPCONF)) !== this._shadow.get(REG_CHOPCONF)) {
167
+ throw new Error('TMC2130: GCONF/CHOPCONF readback mismatch');
168
+ }
169
+ }
170
+
171
+ /** Switch the power stage on and wait 100 ms for StealthChop to settle. @returns {Promise<void>} */
172
+ async enable() {
173
+ if (this._enPin) await this._enPin.set(false);
174
+ else await this._writeReg(REG_CHOPCONF, ((this._shadow.get(REG_CHOPCONF) & ~0xF) | this._toff) >>> 0);
175
+ await sleep(100);
176
+ }
177
+
178
+ /** Switch the power stage off; the motor freewheels. @returns {Promise<void>} */
179
+ async disable() {
180
+ if (this._enPin) { await this._enPin.set(true); return; }
181
+ const chop = this._shadow.get(REG_CHOPCONF);
182
+ if (chop & 0xF) this._toff = chop & 0xF;
183
+ await this._writeReg(REG_CHOPCONF, (chop & ~0xF) >>> 0);
184
+ }
185
+
186
+ /**
187
+ * Set the run current; hold current becomes one third of it. Selects the
188
+ * sense range (CHOPCONF.vsense) automatically unless setVsense() was called.
189
+ * @param {number} rmsA - Run current in A RMS (at most 1.4).
190
+ * @returns {Promise<void>}
191
+ * @throws {RangeError} If rmsA is above 1.4 or the internal sense resistors are in use.
192
+ */
193
+ async setCurrent(rmsA) {
194
+ if (rmsA > 1.4) throw new RangeError('rmsA must be at most 1.4 A');
195
+ const [cs, vsense] = this._currentToCs(rmsA);
196
+ this._runCs = cs;
197
+ this._holdCs = Math.floor(cs / 3);
198
+ if (vsense !== this._vsense) {
199
+ this._vsense = vsense;
200
+ await this._modify(REG_CHOPCONF, 1 << 17, vsense ? (1 << 17) : 0);
201
+ }
202
+ await this._writeIholdIrun();
203
+ }
204
+
205
+ /**
206
+ * Move a number of full steps (software-timed STEP pulses).
207
+ * @param {number} fullSteps - Full steps to move; the sign sets the direction.
208
+ * @param {number} fullStepsPerS - Speed in full steps per second (> 0).
209
+ * @returns {Promise<void>}
210
+ * @throws {RangeError} If fullStepsPerS is not positive.
211
+ */
212
+ async move(fullSteps, fullStepsPerS) {
213
+ if (!(fullStepsPerS > 0)) throw new RangeError('fullStepsPerS must be > 0');
214
+ const pulses = Math.abs(Math.trunc(fullSteps)) * this._microsteps;
215
+ const halfMs = 1000 / (2 * fullStepsPerS * this._microsteps);
216
+ await this._dirPin.set(fullSteps >= 0);
217
+ for (let i = 0; i < pulses; i++) {
218
+ await this._stepPin.set(true);
219
+ await sleep(halfMs);
220
+ await this._stepPin.set(false);
221
+ await sleep(halfMs);
222
+ }
223
+ }
224
+
225
+ /** @returns {Promise<boolean>} True when DRV_STATUS.stst is set. */
226
+ async isStandstill() { return ((await this._readReg(REG_DRV_STATUS)) >>> 31) === 1; }
227
+
228
+ /** @returns {Promise<number>} Bitmask of FAULT_* constants, 0 when none. */
229
+ async readFault() {
230
+ const s = await this._readReg(REG_DRV_STATUS);
231
+ let f = 0;
232
+ if (s & (1 << 26)) f |= TMC2130Minimal.FAULT_OVERTEMP_WARNING;
233
+ if (s & (1 << 25)) f |= TMC2130Minimal.FAULT_OVERTEMP;
234
+ if (s & (3 << 27)) f |= TMC2130Minimal.FAULT_SHORT_GND;
235
+ if (s & (3 << 29)) f |= TMC2130Minimal.FAULT_OPEN_LOAD;
236
+ return f;
237
+ }
238
+ }
239
+ TMC2130Minimal.FAULT_OVERTEMP_WARNING = 0x01;
240
+ TMC2130Minimal.FAULT_OVERTEMP = 0x02;
241
+ TMC2130Minimal.FAULT_SHORT_GND = 0x04;
242
+ TMC2130Minimal.FAULT_OPEN_LOAD = 0x10;
243
+
244
+ /**
245
+ * Complete TMC2130 driver: raw register access, independent hold current,
246
+ * microstep / chopper / StealthChop tuning, StallGuard2 and CoolStep, DIAG
247
+ * routing, DcStep, direct coil-current mode, the microstep table and every
248
+ * status read-back.
249
+ */
250
+ class TMC2130Full extends TMC2130Minimal {
251
+ /**
252
+ * @param {object} connection - SPI connection configured for Mode 3.
253
+ * @param {object} stepPin - OutputPin wired to STEP.
254
+ * @param {object} dirPin - OutputPin wired to DIR.
255
+ * @param {object} [options]
256
+ * @param {number} [options.rSenseOhm=0.11] - External sense resistor in ohm.
257
+ * @param {object|null} [options.enPin=null] - OutputPin wired to ENN.
258
+ * @param {object|null} [options.diag0Pin=null] - InputPin wired to DIAG0.
259
+ * @param {object|null} [options.diag1Pin=null] - InputPin wired to DIAG1.
260
+ * @param {number} [options.fclkHz=12000000] - Chip clock in Hz.
261
+ */
262
+ constructor(connection, stepPin, dirPin, options = {}) {
263
+ super(connection, stepPin, dirPin, options);
264
+ this._diagPins = [options.diag0Pin ?? null, options.diag1Pin ?? null];
265
+ }
266
+
267
+ /** @param {number} reg - Readable register. @returns {Promise<number>} Raw 32-bit value. @throws {RangeError} For write-only/reserved registers. */
268
+ async readRegister(reg) {
269
+ if (!READABLE.has(reg)) throw new RangeError('register 0x' + reg.toString(16) + ' is not readable');
270
+ return this._readReg(reg);
271
+ }
272
+
273
+ /** @param {number} reg - Writable register. @param {number} value - 32-bit value. @param {boolean} [verify=false] - Also check the mirror. @returns {Promise<void>} @throws {RangeError} For read-only/reserved registers. */
274
+ async writeRegister(reg, value, verify = false) {
275
+ if (!WRITABLE.has(reg)) throw new RangeError('register 0x' + reg.toString(16) + ' is not writable');
276
+ await this._writeReg(reg, value, verify);
277
+ }
278
+
279
+ /** @param {number} rmsA - Hold current in A RMS. @returns {Promise<void>} */
280
+ async setHoldCurrent(rmsA) {
281
+ this._holdCs = this._currentToCs(rmsA, this._vsense)[0];
282
+ await this._writeIholdIrun();
283
+ }
284
+
285
+ /** @param {number} iholdDelay - IHOLDDELAY 0-15. @param {number} tpowerdown - TPOWERDOWN 0-255. @returns {Promise<void>} @throws {RangeError} If out of range. */
286
+ async setCurrentDelay(iholdDelay, tpowerdown) {
287
+ if (!(iholdDelay >= 0 && iholdDelay <= 15 && tpowerdown >= 0 && tpowerdown <= 255)) {
288
+ throw new RangeError('ihold_delay 0-15 / tpowerdown 0-255');
289
+ }
290
+ this._iholdDelay = iholdDelay;
291
+ await this._writeIholdIrun();
292
+ await this._writeReg(REG_TPOWERDOWN, tpowerdown);
293
+ }
294
+
295
+ /** @param {number} n - 1, 2, 4, ... 256. @returns {Promise<void>} @throws {RangeError} For any other value. */
296
+ async setMicrosteps(n) {
297
+ if (![1, 2, 4, 8, 16, 32, 64, 128, 256].includes(n)) throw new RangeError('microsteps must be a power of two, 1-256');
298
+ await this._modify(REG_CHOPCONF, 0xF << 24, (8 - Math.log2(n)) << 24);
299
+ this._microsteps = n;
300
+ }
301
+
302
+ /** @param {boolean} enabled - CHOPCONF.intpol. @returns {Promise<void>} */
303
+ async setInterpolation(enabled) { await this._modify(REG_CHOPCONF, 1 << 28, enabled ? (1 << 28) : 0); }
304
+
305
+ /** @param {boolean} spreadcycle - True for SpreadCycle only, false for StealthChop (switch at standstill). @returns {Promise<void>} */
306
+ async setChopperMode(spreadcycle) { await this._modify(REG_GCONF, GCONF_EN_PWM_MODE, spreadcycle ? 0 : GCONF_EN_PWM_MODE); }
307
+
308
+ /** @param {number} tpwmthrs - TPWMTHRS (20 bit); 0 disables. @returns {Promise<void>} @throws {RangeError} If out of range. */
309
+ async setStealthchopThreshold(tpwmthrs) {
310
+ if (!(tpwmthrs >= 0 && tpwmthrs <= 0xFFFFF)) throw new RangeError('tpwmthrs 0-1048575');
311
+ await this._writeReg(REG_TPWMTHRS, tpwmthrs);
312
+ }
313
+
314
+ /** @param {number} thigh - THIGH (20 bit). @returns {Promise<void>} @throws {RangeError} If out of range. */
315
+ async setHighVelocityThreshold(thigh) {
316
+ if (!(thigh >= 0 && thigh <= 0xFFFFF)) throw new RangeError('thigh 0-1048575');
317
+ await this._writeReg(REG_THIGH, thigh);
318
+ }
319
+
320
+ /** SpreadCycle (chm = 0) fields. @param {number} toff 0-15 @param {number} tbl 0-3 @param {number} hstrt 0-7 @param {number} hend raw 0-15 @returns {Promise<void>} @throws {RangeError} If a field is out of range. */
321
+ async configureChopper(toff, tbl, hstrt, hend) {
322
+ if (!(toff >= 0 && toff <= 15 && tbl >= 0 && tbl <= 3 && hstrt >= 0 && hstrt <= 7 && hend >= 0 && hend <= 15)) {
323
+ throw new RangeError('chopper field out of range');
324
+ }
325
+ if (toff) this._toff = toff;
326
+ await this._modify(REG_CHOPCONF, 0xF | (3 << 15) | (7 << 4) | (0xF << 7) | (1 << 14) | (1 << 11),
327
+ toff | (tbl << 15) | (hstrt << 4) | (hend << 7));
328
+ }
329
+
330
+ /** Constant-off-time (chm = 1) fields. @param {number} toff 0-15 @param {number} tbl 0-3 @param {number} tfd 0-15 @param {number} offset -3..12 @param {boolean} disfdcc @param {boolean} rndtf @returns {Promise<void>} @throws {RangeError} If a field is out of range. */
331
+ async configureConstantOffTime(toff, tbl, tfd, offset, disfdcc, rndtf) {
332
+ if (!(toff >= 0 && toff <= 15 && tbl >= 0 && tbl <= 3 && tfd >= 0 && tfd <= 15 && offset >= -3 && offset <= 12)) {
333
+ throw new RangeError('chopper field out of range');
334
+ }
335
+ if (toff) this._toff = toff;
336
+ const mask = 0xF | (3 << 15) | (7 << 4) | (0xF << 7) | (1 << 14) | (1 << 13) | (1 << 12) | (1 << 11);
337
+ const value = toff | (tbl << 15) | ((tfd & 7) << 4) | ((offset + 3) << 7) | (1 << 14) |
338
+ (rndtf ? (1 << 13) : 0) | (disfdcc ? (1 << 12) : 0) | (((tfd >> 3) & 1) << 11);
339
+ await this._modify(REG_CHOPCONF, mask, value);
340
+ }
341
+
342
+ /** @param {boolean} vhighchm @param {boolean} vhighfs @returns {Promise<void>} */
343
+ async configureHighVelocity(vhighchm, vhighfs) {
344
+ await this._modify(REG_CHOPCONF, (1 << 19) | (1 << 18), (vhighchm ? (1 << 19) : 0) | (vhighfs ? (1 << 18) : 0));
345
+ }
346
+
347
+ /** @param {number} sync - CHOPCONF.SYNC 0-15. @returns {Promise<void>} @throws {RangeError} If out of range. */
348
+ async setChopperSync(sync) {
349
+ if (!(sync >= 0 && sync <= 15)) throw new RangeError('sync 0-15');
350
+ await this._modify(REG_CHOPCONF, 0xF << 20, sync << 20);
351
+ }
352
+
353
+ /** PWMCONF fields (freewheel kept). @param {boolean} autoscale @param {boolean} symmetric @param {number} pwmAmpl 0-255 @param {number} pwmGrad 0-255 @param {number} pwmFreq 0-3 @returns {Promise<void>} @throws {RangeError} If a field is out of range. */
354
+ async configureStealthchop(autoscale, symmetric, pwmAmpl, pwmGrad, pwmFreq) {
355
+ if (!(pwmAmpl >= 0 && pwmAmpl <= 255 && pwmGrad >= 0 && pwmGrad <= 255 && pwmFreq >= 0 && pwmFreq <= 3)) {
356
+ throw new RangeError('stealthchop field out of range');
357
+ }
358
+ await this._modify(REG_PWMCONF, (1 << 19) | (1 << 18) | (3 << 16) | (0xFF << 8) | 0xFF,
359
+ (symmetric ? (1 << 19) : 0) | (autoscale ? (1 << 18) : 0) | (pwmFreq << 16) | (pwmGrad << 8) | pwmAmpl);
360
+ }
361
+
362
+ /** @param {number} mode - 0 normal, 1 freewheel, 2 low-side short, 3 high-side short. @returns {Promise<void>} @throws {RangeError} If mode is not 0-3. */
363
+ async setFreewheel(mode) {
364
+ if (!(mode >= 0 && mode <= 3)) throw new RangeError('freewheel mode 0-3');
365
+ await this._modify(REG_PWMCONF, 3 << 20, mode << 20);
366
+ }
367
+
368
+ /** @param {boolean} highSensitivity - True for the 0.18 V range; disables automatic selection. @returns {Promise<void>} */
369
+ async setVsense(highSensitivity) {
370
+ await this._modify(REG_CHOPCONF, 1 << 17, highSensitivity ? (1 << 17) : 0);
371
+ this._vsense = !!highSensitivity;
372
+ this._autoVsense = false;
373
+ }
374
+
375
+ /** @param {boolean} enabled - Internal sense resistors (setCurrent then throws). @returns {Promise<void>} */
376
+ async setInternalRsense(enabled) {
377
+ await this._modify(REG_GCONF, GCONF_INTERNAL_RSENSE, enabled ? GCONF_INTERNAL_RSENSE : 0);
378
+ this._internalRsense = !!enabled;
379
+ }
380
+
381
+ /** @param {boolean} enabled - Current reference from AIN_IREF. @returns {Promise<void>} */
382
+ async setAnalogScaling(enabled) { await this._modify(REG_GCONF, GCONF_I_SCALE_ANALOG, enabled ? GCONF_I_SCALE_ANALOG : 0); }
383
+
384
+ /** @param {boolean} inverted - GCONF.shaft. @returns {Promise<void>} */
385
+ async setDirectionInverted(inverted) { await this._modify(REG_GCONF, GCONF_SHAFT, inverted ? GCONF_SHAFT : 0); }
386
+
387
+ /**
388
+ * Route events to DIAG0 / DIAG1 (GCONF bits 5-13).
389
+ * @param {object} [o] - Booleans: diag0Error, diag0Otpw, diag0Stall, diag1Stall, diag1Index, diag1Onstate, diag0Pushpull, diag1Pushpull.
390
+ * @returns {Promise<void>}
391
+ */
392
+ async configureDiag(o = {}) {
393
+ const flags = [o.diag0Error, o.diag0Otpw, o.diag0Stall, o.diag1Stall, o.diag1Index, o.diag1Onstate];
394
+ let value = 0;
395
+ flags.forEach((f, i) => { if (f) value |= 1 << (5 + i); });
396
+ if (o.diag0Pushpull) value |= 1 << 12;
397
+ if (o.diag1Pushpull) value |= 1 << 13;
398
+ await this._modify(REG_GCONF, 0x3FE0 & ~(1 << 11), value);
399
+ }
400
+
401
+ /** @param {boolean} enabled - CHOPCONF.dedge. @returns {Promise<void>} */
402
+ async setDoubleEdge(enabled) { await this._modify(REG_CHOPCONF, 1 << 29, enabled ? (1 << 29) : 0); }
403
+
404
+ /** @param {boolean} shortGnd - True keeps the short-to-GND protection. @returns {Promise<void>} */
405
+ async setShortProtection(shortGnd) { await this._modify(REG_CHOPCONF, 1 << 30, shortGnd ? 0 : (1 << 30)); }
406
+
407
+ /** @param {boolean} enabled - GCONF.small_hysteresis. @returns {Promise<void>} */
408
+ async setSmallHysteresis(enabled) { await this._modify(REG_GCONF, GCONF_SMALL_HYSTERESIS, enabled ? GCONF_SMALL_HYSTERESIS : 0); }
409
+
410
+ /** @param {boolean} enabled - GCONF.stop_enable. @returns {Promise<void>} */
411
+ async setEmergencyStop(enabled) { await this._modify(REG_GCONF, GCONF_STOP_ENABLE, enabled ? GCONF_STOP_ENABLE : 0); }
412
+
413
+ /** @param {number} sgt - StallGuard2 threshold -64..63 (lower is more sensitive). @returns {Promise<void>} @throws {RangeError} If out of range. */
414
+ async setStallThreshold(sgt) {
415
+ if (!(sgt >= -64 && sgt <= 63)) throw new RangeError('sgt -64..63');
416
+ await this._modify(REG_COOLCONF, 0x7F << 16, (sgt & 0x7F) << 16);
417
+ }
418
+
419
+ /** @param {boolean} enabled - COOLCONF.sfilt. @returns {Promise<void>} */
420
+ async setStallguardFilter(enabled) { await this._modify(REG_COOLCONF, 1 << 24, enabled ? (1 << 24) : 0); }
421
+
422
+ /** @param {number} tcoolthrs - TCOOLTHRS (20 bit); 0 disables. @returns {Promise<void>} @throws {RangeError} If out of range. */
423
+ async setCoolstepThreshold(tcoolthrs) {
424
+ if (!(tcoolthrs >= 0 && tcoolthrs <= 0xFFFFF)) throw new RangeError('tcoolthrs 0-1048575');
425
+ await this._writeReg(REG_TCOOLTHRS, tcoolthrs);
426
+ }
427
+
428
+ /** CoolStep fields (sgt / sfilt kept). @param {number} semin 0-15 @param {number} semax 0-15 @param {number} seup 0-3 @param {number} sedn 0-3 @param {number} seimin 0|1 @returns {Promise<void>} @throws {RangeError} If a field is out of range. */
429
+ async configureCoolstep(semin, semax, seup, sedn, seimin) {
430
+ if (!(semin >= 0 && semin <= 15 && semax >= 0 && semax <= 15 && seup >= 0 && seup <= 3 &&
431
+ sedn >= 0 && sedn <= 3 && (seimin === 0 || seimin === 1))) {
432
+ throw new RangeError('COOLCONF field out of range');
433
+ }
434
+ await this._modify(REG_COOLCONF, 0xF | (3 << 5) | (0xF << 8) | (3 << 13) | (1 << 15),
435
+ semin | (seup << 5) | (semax << 8) | (sedn << 13) | (seimin << 15));
436
+ }
437
+
438
+ /** @returns {Promise<number>} SG_RESULT 0-1023 (0 = highest load). */
439
+ async readStallguard() { return (await this._readReg(REG_DRV_STATUS)) & 0x3FF; }
440
+
441
+ /** @returns {Promise<boolean>} DRV_STATUS.StallGuard. */
442
+ async isStalled() { return (((await this._readReg(REG_DRV_STATUS)) >>> 24) & 1) === 1; }
443
+
444
+ /** @param {number} n - 0 for DIAG0, 1 for DIAG1. @returns {boolean} Pin level. @throws {RangeError} If n is not 0/1. @throws {Error} If that pin is not wired. */
445
+ readDiag(n) {
446
+ if (n !== 0 && n !== 1) throw new RangeError('n must be 0 or 1');
447
+ const pin = this._diagPins[n];
448
+ if (!pin) throw new Error('readDiag() requires diag' + n + 'Pin');
449
+ return !!pin.isHigh();
450
+ }
451
+
452
+ /** Emit STEP pulses (no microstep conversion). @param {number} count - Pulses; negative reverses. @param {number} delayS - Time between edges in seconds. @returns {Promise<void>} */
453
+ async step(count, delayS) {
454
+ await this._dirPin.set(count >= 0);
455
+ for (let i = 0; i < Math.abs(count); i++) {
456
+ await this._stepPin.set(true);
457
+ await sleep(delayS * 1000);
458
+ await this._stepPin.set(false);
459
+ await sleep(delayS * 1000);
460
+ }
461
+ }
462
+
463
+ /** @param {boolean} enabled - GCONF.direct_mode. @returns {Promise<void>} */
464
+ async setDirectMode(enabled) { await this._modify(REG_GCONF, GCONF_DIRECT_MODE, enabled ? GCONF_DIRECT_MODE : 0); }
465
+
466
+ /** Write XDIRECT. @param {number} coilA -255..255 @param {number} coilB -255..255 @returns {Promise<void>} @throws {Error} If direct mode is off. @throws {RangeError} If out of range. */
467
+ async setCoilCurrents(coilA, coilB) {
468
+ if (!((this._shadow.get(REG_GCONF) ?? 0) & GCONF_DIRECT_MODE)) throw new Error('setCoilCurrents() requires direct mode');
469
+ if (!(coilA >= -255 && coilA <= 255 && coilB >= -255 && coilB <= 255)) throw new RangeError('coil currents -255..255');
470
+ await this._writeReg(REG_XDIRECT, ((coilA & 0x1FF) | ((coilB & 0x1FF) << 16)) >>> 0);
471
+ }
472
+
473
+ /** @param {number} vdcmin 0..2^23-1 @param {number} dcTime 0-1023 @param {number} dcSg 0-255 @returns {Promise<void>} @throws {RangeError} If out of range. */
474
+ async setDcstep(vdcmin, dcTime, dcSg) {
475
+ if (!(vdcmin >= 0 && vdcmin <= 0x7FFFFF && dcTime >= 0 && dcTime <= 1023 && dcSg >= 0 && dcSg <= 255)) {
476
+ throw new RangeError('DcStep field out of range');
477
+ }
478
+ await this._writeReg(REG_VDCMIN, vdcmin);
479
+ await this._writeReg(REG_DCCTRL, (dcTime | (dcSg << 16)) >>> 0);
480
+ }
481
+
482
+ /** Program the microstep table (call at MSCNT = 0). @param {number[]} mslut - 8 words @param {number} mslutsel @param {number} mslutstart @returns {Promise<void>} @throws {RangeError} If mslut does not hold 8 words. */
483
+ async writeMicrostepTable(mslut, mslutsel, mslutstart) {
484
+ if (mslut.length !== 8) throw new RangeError('mslut needs 8 words');
485
+ for (let i = 0; i < 8; i++) await this._writeReg(REG_MSLUT0 + i, mslut[i]);
486
+ await this._writeReg(REG_MSLUTSEL, mslutsel);
487
+ await this._writeReg(REG_MSLUTSTART, mslutstart);
488
+ }
489
+
490
+ /** @returns {Promise<number>} MSCNT 0-1023. */
491
+ async microstepPosition() { return (await this._readReg(REG_MSCNT)) & 0x3FF; }
492
+
493
+ /** @returns {Promise<number>} DRV_STATUS.CS_ACTUAL 0-31. */
494
+ async readCurrentScale() { return ((await this._readReg(REG_DRV_STATUS)) >>> 16) & 0x1F; }
495
+
496
+ /** @returns {Promise<number[]>} Signed [CUR_A, CUR_B] from MSCURACT. */
497
+ async readCoilCurrents() {
498
+ const raw = await this._readReg(REG_MSCURACT);
499
+ return [toSigned(raw >>> 16, 9), toSigned(raw, 9)];
500
+ }
501
+
502
+ /** @returns {Promise<number>} TSTEP (20 bit). */
503
+ async readTstep() { return (await this._readReg(REG_TSTEP)) & 0xFFFFF; }
504
+
505
+ /** @returns {Promise<number>} PWM_SCALE 0-255. */
506
+ async readPwmScale() { return (await this._readReg(REG_PWM_SCALE)) & 0xFF; }
507
+
508
+ /** @returns {Promise<number>} LOST_STEPS (20 bit). */
509
+ async readLostSteps() { return (await this._readReg(REG_LOST_STEPS)) & 0xFFFFF; }
510
+
511
+ /** @returns {Promise<object>} {stst, fsactive, cs_actual, sg_result, stallguard, otpw, ot, short_gnd, open_load}. */
512
+ async readStatus() {
513
+ const s = await this._readReg(REG_DRV_STATUS);
514
+ return {
515
+ stst: !!(s & 0x80000000), fsactive: !!(s & (1 << 15)), cs_actual: (s >>> 16) & 0x1F,
516
+ sg_result: s & 0x3FF, stallguard: !!(s & (1 << 24)), otpw: !!(s & (1 << 26)),
517
+ ot: !!(s & (1 << 25)), short_gnd: !!(s & (3 << 27)), open_load: !!(s & (3 << 29)),
518
+ };
519
+ }
520
+
521
+ /** Reads GSTAT; the chip clears the flags on read. @returns {Promise<object>} {reset, drv_err, uv_cp}. */
522
+ async readGlobalStatus() {
523
+ const g = await this._readReg(REG_GSTAT);
524
+ return { reset: !!(g & 1), drv_err: !!(g & 2), uv_cp: !!(g & 4) };
525
+ }
526
+
527
+ /** @returns {Promise<object>} {raw, step, dir, dcen, dcin, enn, dco, version}. */
528
+ async readIoin() {
529
+ const raw = await this._readReg(REG_IOIN);
530
+ return {
531
+ raw, step: !!(raw & 1), dir: !!(raw & 2), dcen: !!(raw & 4), dcin: !!(raw & 8),
532
+ enn: !!(raw & 16), dco: !!(raw & 32), version: (raw >>> 24) & 0xFF,
533
+ };
534
+ }
535
+ }
536
+
537
+ module.exports = { TMC2130Minimal, TMC2130Full };