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,81 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { QMI8658AFull } = require('../../../src/chips/imu/qmi8658a');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x6B', 16);
8
+
9
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
10
+
11
+ async function main() {
12
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR);
13
+ const imu = new QMI8658AFull(connection); // Create QMI8658A driver, (connection) → void
14
+
15
+ // --- Identify the part and run the built-in checks ---
16
+ // The revision, firmware version and USID identify the silicon; the
17
+ // self-tests need the board lying still and the gyro calibration trims the
18
+ // X/Y gains before real use.
19
+ const info = await imu.deviceInfo(); // Read device info, () → {revision, firmware, usid}
20
+ console.log('revision 0x%s firmware %s usid %s', info.revision.toString(16), info.firmware.toString('hex'), info.usid.toString('hex'));
21
+ const [accelOk] = await imu.selfTestAccel(); // Run accel self-test, () → [boolean, [number, number, number]] m/s²
22
+ console.log('accel self-test:', accelOk ? 'PASS' : 'FAIL');
23
+ const [gyroOk] = await imu.selfTestGyro(); // Run gyro self-test, () → [boolean, [number, number, number]] rad/s
24
+ console.log('gyro self-test:', gyroOk ? 'PASS' : 'FAIL');
25
+ const [calOk, codStatus] = await imu.calibrateGyro(); // Calibrate gyroscope, () → [boolean, number]
26
+ console.log('gyro calibration:', calOk ? 'OK' : 'FAILED 0x' + codStatus.toString(16));
27
+
28
+ // --- Configure ±4 g / ±512 dps at 112.1 Hz ---
29
+ // ODR code 6 gives 112.1 Hz for both sensors; mode 3 filters keep the
30
+ // noise bandwidth near 15 Hz.
31
+ await imu.configureAccel(1, 6); // Configure accelerometer, (fullScale=0, odr=5) → void
32
+ await imu.configureGyro(5, 6); // Configure gyroscope, (fullScale=4, odr=5) → void
33
+ await imu.configureFilters(true, 3, true, 3); // Configure low-pass filters, (accelFilter=true, accelMode=3, gyroFilter=true, gyroMode=3) → void
34
+
35
+ // --- Step counting and tap detection ---
36
+ // The pedometer defaults suit ~50 Hz, so the window parameters are scaled
37
+ // for 112 Hz; the tap engine runs best above 200 Hz and is only a coarse
38
+ // detector at this rate.
39
+ await imu.configurePedometer(112, 200, 100, 450, 45, 10, 0, 1); // Configure pedometer, (sampleCount=50, …) → void
40
+ await imu.enablePedometer(true); // Enable pedometer, (enabled=true) → void
41
+ await imu.configureTap(); // Configure tap engine, (priority=0, …) → void
42
+ await imu.enableTap(true); // Enable tap engine, (enabled=true) → void
43
+
44
+ // --- Stream into the FIFO ---
45
+ // Stream mode with 32 samples and a watermark of 16 is drained once per
46
+ // second; each sample is a 12-byte frame (accel XYZ then gyro XYZ).
47
+ await imu.configureFifo(2, 1, 16); // Configure FIFO, (mode=2, size=3, watermark=0) → void
48
+ await sleep(200);
49
+
50
+ const start = Date.now();
51
+ let lastFifo = start;
52
+ while (Date.now() - start < 60000) {
53
+ if (await imu.dataReady()) { // Check for new data, () → boolean
54
+ const [[ax, ay, az], [gx, gy, gz], temp] = await imu.readAll(); // Read one coherent sample, () → [[number, number, number], [number, number, number], number] m/s², rad/s, °C
55
+ const roll = Math.atan2(ay, az) * 180 / Math.PI;
56
+ const pitch = Math.atan2(-ax, Math.sqrt(ay * ay + az * az)) * 180 / Math.PI;
57
+ const mag = Math.sqrt(gx * gx + gy * gy + gz * gz);
58
+ console.log('roll %s pitch %s |gyro| %s rad/s %s C steps %d', roll.toFixed(1), pitch.toFixed(1),
59
+ mag.toFixed(3), temp.toFixed(1), await imu.stepCount()); // Read step count, () → number
60
+ }
61
+
62
+ // --- Report taps ---
63
+ // pollInterrupt() flags a tap without the INT pin wired.
64
+ const status = await imu.pollInterrupt(); // Poll interrupt status, () → number
65
+ if (status & QMI8658AFull.SOURCE_TAP) {
66
+ const [taps, axis] = await imu.tapStatus(); // Read tap event, () → [number, number, boolean]
67
+ console.log('TAP %s on axis %s', taps === 2 ? 'double' : 'single', axis ? 'XYZ'[axis - 1] : '?');
68
+ }
69
+
70
+ // --- Drain the FIFO once per second ---
71
+ if (Date.now() - lastFifo >= 1000) {
72
+ lastFifo = Date.now();
73
+ const n = await imu.fifoCount(); // Read FIFO fill, () → number bytes
74
+ const data = await imu.readFifo(); // Drain the FIFO, (count?) → Buffer
75
+ console.log('FIFO: %d bytes (%d), %d frames', n, data.length, Math.floor(data.length / 12));
76
+ }
77
+ await sleep(100);
78
+ }
79
+ }
80
+
81
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { QMI8658AMinimal } = require('../../../src/chips/imu/qmi8658a');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x6B', 16);
8
+
9
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR);
10
+ const imu = new QMI8658AMinimal(connection); // Create QMI8658A driver, (connection) → void
11
+
12
+ async function main() {
13
+ while (true) {
14
+ const [ax, ay, az] = await imu.accel(); // Read 3-axis acceleration, () → [number, number, number] m/s²
15
+ const [gx, gy, gz] = await imu.gyro(); // Read 3-axis angular rate, () → [number, number, number] rad/s
16
+ console.log('accel: %s %s %s gyro: %s %s %s',
17
+ ax.toFixed(2), ay.toFixed(2), az.toFixed(2), gx.toFixed(2), gy.toFixed(2), gz.toFixed(2));
18
+ await new Promise(r => setTimeout(r, 100));
19
+ }
20
+ }
21
+
22
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('periph/src/connection/spi');
4
+ const { GpioOutputPin } = require('periph/src/connection/output_pin');
5
+ const { Default } = require('opengpio');
6
+ const { TMC2130Full } = require('periph/src/chips/motor/tmc2130');
7
+
8
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
9
+ const SPI_BUS = parseInt(process.env.SPI_BUS || '0', 10);
10
+ const SPI_DEV = parseInt(process.env.SPI_DEV || '0', 10);
11
+
12
+ (async () => {
13
+ const spi = new SPIConnection(SPI_BUS, SPI_DEV, { mode: 3, maxSpeedHz: 1_000_000 }); // Create SPI connection, (busNumber, deviceNumber, {mode=3, maxSpeedHz=1 MHz})
14
+ const stepPin = new GpioOutputPin(Default.output({ chip: 0, line: 27 })); // Create STEP pin, (chip, line=27) → OutputPin
15
+ const dirPin = new GpioOutputPin(Default.output({ chip: 0, line: 22 })); // Create DIR pin, (chip, line=22) → OutputPin
16
+ const enPin = new GpioOutputPin(Default.output({ chip: 0, line: 17 })); // Create ENN pin, (chip, line=17) → OutputPin
17
+ const motor = new TMC2130Full(spi, stepPin, dirPin, { rSenseOhm: 0.11, enPin }); // Create TMC2130 Full driver, (connection, stepPin, dirPin, {rSenseOhm=0.11 Ω, enPin, diag0Pin, diag1Pin, fclkHz=12000000 Hz})
18
+ await motor.init(); // Probe the chip and apply defaults, () → None
19
+ // reads IOIN to verify the chip, writes the default configuration with mirror checks
20
+
21
+ await motor.enable(); // Power stage on, () → None
22
+ // drives ENN low, waits 100 ms
23
+ await motor.setCurrent(0.8); // Set run current, (rmsA A RMS) → None
24
+ // converts amperes to the 0–31 scale, picks vsense automatically
25
+ await motor.setHoldCurrent(0.2); // Set hold current, (rmsA A RMS) → None
26
+ // overrides the automatic one-third hold current
27
+ await motor.setCurrentDelay(6, 10); // Set power-down timing, (iholdDelay 0–15, tpowerdown 0–255) → None
28
+ // IHOLDDELAY and TPOWERDOWN, units of 2^18 clocks
29
+ await motor.setMicrosteps(32); // Set microstep resolution, (n 1–256) → None
30
+ // writes CHOPCONF.MRES
31
+ await motor.setInterpolation(true); // Interpolate to 256 microsteps, (enabled) → None
32
+ // sets CHOPCONF.intpol
33
+ await motor.setChopperMode(false); // Choose chopper, (spreadcycle) → None
34
+ // false enables StealthChop below TPWMTHRS
35
+ await motor.setStealthchopThreshold(500); // Set StealthChop velocity limit, (tpwmthrs 20 bit) → None
36
+ // faster than this the chip switches to SpreadCycle
37
+ await motor.setHighVelocityThreshold(0); // Set THIGH, (thigh 20 bit) → None
38
+ // 0 keeps the high-velocity features off
39
+ await motor.configureChopper(3, 2, 4, 1); // Configure SpreadCycle timing, (toff, tbl, hstrt, hend) → None
40
+ // direct CHOPCONF fields with chm = 0
41
+ await motor.configureConstantOffTime(3, 2, 4, 0, false, false); // Configure constant off time, (toff, tbl, tfd, offset, disfdcc, rndtf) → None
42
+ // chm = 1 with fast decay
43
+ await motor.configureChopper(3, 2, 4, 1); // Back to SpreadCycle, (toff, tbl, hstrt, hend) → None
44
+ // chm = 0 again
45
+ await motor.configureHighVelocity(false, false); // Behaviour above THIGH, (vhighchm, vhighfs) → None
46
+ // both off
47
+ await motor.setChopperSync(0); // Set chopSync2, (sync 0–15) → None
48
+ // 0 = off
49
+ await motor.configureStealthchop(true, false, 200, 1, 0); // Configure StealthChop, (autoscale, symmetric, pwmAmpl, pwmGrad, pwmFreq) → None
50
+ // direct PWMCONF fields
51
+ await motor.setFreewheel(0); // Set standstill mode, (mode 0–3) → None
52
+ // PWMCONF.freewheel, only effective when IHOLD is 0
53
+ await motor.setVsense(false); // Select sense range, (highSensitivity) → None
54
+ // false keeps the 0.325 V full scale; disables automatic selection
55
+ await motor.setInternalRsense(false); // Internal sense resistors, (enabled) → None
56
+ // keep false on boards with external resistors
57
+ await motor.setAnalogScaling(false); // Current reference source, (enabled) → None
58
+ // false uses the internal reference
59
+ await motor.setDirectionInverted(false); // Invert direction, (inverted) → None
60
+ // GCONF.shaft
61
+ await motor.configureDiag({ diag0Stall: true, diag1Index: true }); // Route events to DIAG pins, ({diag0Error, diag0Otpw, diag0Stall, diag1Stall, diag1Index, diag1Onstate, diag0Pushpull, diag1Pushpull}) → None
62
+ // GCONF bits 5–13
63
+ await motor.setDoubleEdge(false); // Step on both edges, (enabled) → None
64
+ // CHOPCONF.dedge
65
+ await motor.setShortProtection(true); // Short-to-GND protection, (shortGnd) → None
66
+ // true keeps the protection enabled
67
+ await motor.setSmallHysteresis(false); // Comparison hysteresis, (enabled) → None
68
+ // false = 1/16
69
+ await motor.setEmergencyStop(false); // DCIN emergency stop, (enabled) → None
70
+ // GCONF.stop_enable
71
+ await motor.setStallThreshold(0); // Set StallGuard2 threshold, (sgt -64..63) → None
72
+ // lower = more sensitive
73
+ await motor.setStallguardFilter(false); // StallGuard2 filter, (enabled) → None
74
+ // COOLCONF.sfilt
75
+ await motor.setCoolstepThreshold(1000); // Set CoolStep / stall velocity limit, (tcoolthrs 20 bit) → None
76
+ // active while TCOOLTHRS >= TSTEP >= THIGH
77
+ await motor.configureCoolstep(5, 2, 1, 1, 0); // Configure CoolStep, (semin 0–15, semax 0–15, seup 0–3, sedn 0–3, seimin 0–1) → None
78
+ // semin = 0 would disable CoolStep
79
+
80
+ await motor.move(200, 150); // Move, (fullSteps, fullStepsPerS full steps/s) → None
81
+ // blocking, software-timed STEP pulses
82
+ await motor.step(400, 0.001); // Pulse the STEP pin, (count, delayS s) → None
83
+ // negative counts reverse via DIR
84
+ console.log('position', await motor.microstepPosition()); // Read microstep counter, () → number 0–1023
85
+ // MSCNT
86
+ console.log('currents', await motor.readCoilCurrents()); // Read coil currents, () → [number, number]
87
+ // signed [CUR_A, CUR_B] from MSCURACT
88
+ console.log('tstep', await motor.readTstep()); // Read step interval, () → number clocks
89
+ // time between 1/256 microsteps
90
+ console.log('scale', await motor.readCurrentScale()); // Read actual current scale, () → number 0–31
91
+ // DRV_STATUS.CS_ACTUAL
92
+ console.log('sg_result', await motor.readStallguard()); // Read StallGuard2 result, () → number 0–1023
93
+ // SG_RESULT, 0 = highest load
94
+ console.log('stalled', await motor.isStalled()); // Read stall flag, () → boolean
95
+ // DRV_STATUS.StallGuard
96
+ try {
97
+ console.log('diag0', motor.readDiag(0)); // Read DIAG0 pin, (n 0 or 1) → boolean
98
+ // needs the diag pin to be wired
99
+ } catch (e) {
100
+ console.log('diag0: not wired');
101
+ }
102
+ console.log('pwm_scale', await motor.readPwmScale()); // Read PWM scaler, () → number 0–255
103
+ // PWM_SCALE
104
+ console.log('lost_steps', await motor.readLostSteps()); // Read skipped DcStep steps, () → number
105
+ // LOST_STEPS
106
+ console.log('status', await motor.readStatus()); // Read driver status, () → object
107
+ // decoded DRV_STATUS
108
+ console.log('standstill', await motor.isStandstill()); // Read standstill flag, () → boolean
109
+ // DRV_STATUS.stst
110
+ console.log('fault', await motor.readFault()); // Read fault bitmask, () → number
111
+ // FAULT_* constants, 0 = none
112
+ console.log('gstat', await motor.readGlobalStatus()); // Read GSTAT, () → object
113
+ // reset, drv_err, uv_cp; the chip clears them on read
114
+ console.log('ioin', await motor.readIoin()); // Read IOIN, () → object
115
+ // raw word, pin states and silicon version
116
+ console.log('gconf', (await motor.readRegister(0x00)).toString(16)); // Read a raw register, (reg) → number
117
+ // any readable register
118
+ await motor.writeRegister(0x13, 500, true); // Write a raw register, (reg, value, verify=false) → None
119
+ // here TPWMTHRS again, with the mirror check
120
+
121
+ await motor.setDcstep(0, 0, 0); // Configure DcStep, (vdcmin, dcTime, dcSg) → None
122
+ // all zero keeps DcStep off
123
+ await motor.setDirectMode(true); // Direct coil-current mode, (enabled) → None
124
+ // GCONF.direct_mode
125
+ await motor.setCoilCurrents(100, 0); // Write XDIRECT, (coilA, coilB -255..255) → None
126
+ // scaled by IHOLD
127
+ await sleep(500);
128
+ await motor.setDirectMode(false); // Back to STEP/DIR, (enabled) → None
129
+ // GCONF.direct_mode = 0
130
+ const customTable = null; // replace with { mslut: [8 words], mslutsel, mslutstart } to program a table
131
+ if (customTable && (await motor.microstepPosition()) === 0) {
132
+ await motor.writeMicrostepTable(customTable.mslut, customTable.mslutsel, customTable.mslutstart); // Program the microstep table, (mslut 8 words, mslutsel, mslutstart) → None
133
+ // MSLUT0..7, MSLUTSEL, MSLUTSTART; call at MSCNT = 0
134
+ }
135
+ await motor.disable(); // Power stage off, () → None
136
+ // drives ENN high; the motor freewheels
137
+ await spi.close();
138
+ })();
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Demo for the TMC2130 — sensorless homing of a linear axis with StallGuard2.
5
+ *
6
+ * Enables the driver at 0.8 A with 16 microsteps, proves the SPI link by
7
+ * reading IOIN.VERSION (0x11), switches to SpreadCycle (StallGuard2 does not
8
+ * work in StealthChop) and drives toward the end stop in bursts of 20 full
9
+ * steps at 150 full steps/s. When SG_RESULT reaches 0 the demo stops, prints
10
+ * the SG_RESULT history, backs off 200 full steps and finishes with a
11
+ * CoolStep move. Any fault disables the driver and exits.
12
+ */
13
+
14
+ const { SPIConnection } = require('periph/src/connection/spi');
15
+ const { GpioOutputPin } = require('periph/src/connection/output_pin');
16
+ const { Default } = require('opengpio');
17
+ const { TMC2130Full } = require('periph/src/chips/motor/tmc2130');
18
+
19
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
20
+ const SPI_BUS = parseInt(process.env.SPI_BUS || '0', 10);
21
+ const SPI_DEV = parseInt(process.env.SPI_DEV || '0', 10);
22
+ const HOMING_SPEED = 150;
23
+ const BURST = 20;
24
+
25
+ (async () => {
26
+ const spi = new SPIConnection(SPI_BUS, SPI_DEV, { mode: 3, maxSpeedHz: 1_000_000 }); // Create SPI connection, (busNumber, deviceNumber, {mode=3, maxSpeedHz=1 MHz})
27
+ const stepPin = new GpioOutputPin(Default.output({ chip: 0, line: 27 })); // Create STEP pin, (chip, line=27) → OutputPin
28
+ const dirPin = new GpioOutputPin(Default.output({ chip: 0, line: 22 })); // Create DIR pin, (chip, line=22) → OutputPin
29
+ const enPin = new GpioOutputPin(Default.output({ chip: 0, line: 17 })); // Create ENN pin, (chip, line=17) → OutputPin
30
+ const motor = new TMC2130Full(spi, stepPin, dirPin, { enPin }); // Create TMC2130 Full driver, (connection, stepPin, dirPin, {rSenseOhm=0.11 Ω, enPin})
31
+ await motor.init(); // Probe the chip and apply defaults, () → None
32
+
33
+ async function guard() {
34
+ // --- Stop on any driver fault ---
35
+ // Short circuits and over-temperature latch until the driver is
36
+ // disabled, so the demo shuts everything down and reports which fault fired.
37
+ const fault = await motor.readFault(); // Read fault bitmask, () → number
38
+ if (fault) {
39
+ await motor.disable(); // Power stage off, () → None
40
+ console.log('fault 0x' + fault.toString(16));
41
+ await spi.close();
42
+ process.exit(1);
43
+ }
44
+ }
45
+
46
+ // --- Bring up the link and the power stage ---
47
+ // IOIN.VERSION proves the SPI wiring and Mode 3 setting work before any
48
+ // motion is attempted.
49
+ const ioin = await motor.readIoin(); // Read IOIN, () → object
50
+ console.log('version 0x' + ioin.version.toString(16));
51
+ await motor.setCurrent(0.8); // Set run current, (rmsA A RMS) → None
52
+ await motor.setMicrosteps(16); // Set microstep resolution, (n 1–256) → None
53
+ await motor.enable(); // Power stage on, () → None
54
+
55
+ // --- Arm StallGuard2 for the homing speed ---
56
+ // StallGuard2 needs SpreadCycle and TSTEP <= TCOOLTHRS, so TCOOLTHRS is set
57
+ // just above the TSTEP of the homing speed; sgt = 0 is the usual start value.
58
+ await motor.setChopperMode(true); // Choose chopper, (spreadcycle) → None
59
+ await motor.setStallThreshold(0); // Set StallGuard2 threshold, (sgt -64..63) → None
60
+ await motor.setCoolstepThreshold(Math.floor(12e6 / (HOMING_SPEED * 256 / 2))); // Set CoolStep / stall velocity limit, (tcoolthrs 20 bit) → None
61
+
62
+ // --- Drive toward the end stop in short bursts ---
63
+ // The first burst is spin-up, where SG_RESULT is not yet valid; after each
64
+ // burst the demo reads SG_RESULT until the stall flag is set.
65
+ const history = [];
66
+ await motor.move(BURST, HOMING_SPEED); // Move, (fullSteps, fullStepsPerS full steps/s) → None
67
+ for (;;) {
68
+ await motor.move(BURST, HOMING_SPEED); // Move, (fullSteps, fullStepsPerS full steps/s) → None
69
+ const sg = await motor.readStallguard(); // Read StallGuard2 result, () → number 0–1023
70
+ history.push(sg);
71
+ console.log('SG_RESULT', sg);
72
+ if (await motor.isStalled()) break; // Read stall flag, () → boolean
73
+ await guard();
74
+ }
75
+
76
+ // --- End stop found: report and back off ---
77
+ // The last few SG_RESULT values show how the load built up before the stall.
78
+ console.log('history', history.slice(-5));
79
+ await motor.move(-200, HOMING_SPEED); // Move, (fullSteps, fullStepsPerS full steps/s) → None
80
+
81
+ // --- Final move with CoolStep ---
82
+ // CoolStep lowers the current while the load is light; CS_ACTUAL shows it.
83
+ await motor.configureCoolstep(5, 2, 1, 1, 0); // Configure CoolStep, (semin 0–15, semax 0–15, seup 0–3, sedn 0–3, seimin 0–1) → None
84
+ for (let i = 0; i < 10; i++) {
85
+ await motor.move(20, HOMING_SPEED); // Move, (fullSteps, fullStepsPerS full steps/s) → None
86
+ console.log('CS_ACTUAL', await motor.readCurrentScale()); // Read actual current scale, () → number 0–31
87
+ await guard();
88
+ }
89
+
90
+ // --- Shut down and report ---
91
+ // GSTAT shows whether the run stressed the driver; the chip clears it on read.
92
+ console.log('status', await motor.readStatus()); // Read driver status, () → object
93
+ console.log('global status', await motor.readGlobalStatus()); // Read GSTAT, () → object
94
+ await motor.disable(); // Power stage off, () → None
95
+ await spi.close();
96
+ })();
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('periph/src/connection/spi');
4
+ const { GpioOutputPin } = require('periph/src/connection/output_pin');
5
+ const { Default } = require('opengpio');
6
+ const { TMC2130Minimal } = require('periph/src/chips/motor/tmc2130');
7
+
8
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
9
+ const SPI_BUS = parseInt(process.env.SPI_BUS || '0', 10);
10
+ const SPI_DEV = parseInt(process.env.SPI_DEV || '0', 10);
11
+
12
+ (async () => {
13
+ const spi = new SPIConnection(SPI_BUS, SPI_DEV, { mode: 3, maxSpeedHz: 1_000_000 }); // Create SPI connection, (busNumber, deviceNumber, {mode=3, maxSpeedHz=1 MHz})
14
+ const stepPin = new GpioOutputPin(Default.output({ chip: 0, line: 27 })); // Create STEP pin, (chip, line=27) → OutputPin
15
+ const dirPin = new GpioOutputPin(Default.output({ chip: 0, line: 22 })); // Create DIR pin, (chip, line=22) → OutputPin
16
+ const motor = new TMC2130Minimal(spi, stepPin, dirPin, { rSenseOhm: 0.11 }); // Create TMC2130 driver, (connection, stepPin, dirPin, {rSenseOhm=0.11 Ω, enPin=null})
17
+ await motor.init(); // Probe the chip and apply defaults, () → None
18
+
19
+ await motor.setCurrent(0.8); // Set run current, (rmsA A RMS) → None
20
+ await motor.enable(); // Power stage on, () → None
21
+ for (const steps of [400, -400]) {
22
+ await motor.move(steps, 200); // Move, (fullSteps, fullStepsPerS full steps/s) → None
23
+ await sleep(500);
24
+ console.log('standstill:', await motor.isStandstill()); // Read standstill flag, () → boolean
25
+ console.log('fault:', await motor.readFault()); // Read fault bitmask, () → number
26
+ }
27
+
28
+ await motor.disable(); // Power stage off, () → None
29
+ await spi.close();
30
+ })();
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+
3
+ const { UARTConnection } = require('periph/src/connection/uart');
4
+ const { TMC2208Full } = require('periph/src/chips/motor/tmc2208');
5
+
6
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
7
+
8
+ (async () => {
9
+ const port = process.env.UART_PORT || '/dev/ttyS0';
10
+ const connection = new UARTConnection(port, { baudRate: 115200, timeoutMs: 100 });
11
+ await connection.open();
12
+ const motor = new TMC2208Full(connection, { rSenseOhm: 0.11 }); // Create TMC2208 Full driver, (connection, {rSenseOhm=0.11 Ω, enPin, echo=true, stepPin, dirPin, fclkHz=12000000 Hz, tmc2224=false})
13
+ await motor.init(); // Probe the chip and apply defaults, () → None
14
+ // reads IOIN to verify the chip, writes the default configuration and checks IFCNT
15
+
16
+ await motor.enable(); // Power stage on, () → None
17
+ // restores TOFF (or drives ENN low when enPin is wired)
18
+ await motor.setCurrent(0.8); // Set run current, (rmsA A RMS) → None
19
+ // converts amperes to the 0–31 scale; hold current becomes a third
20
+ await motor.setHoldCurrent(0.2); // Set hold current, (rmsA A RMS) → None
21
+ // overrides the automatic one-third hold current
22
+ await motor.setCurrentDelay(6, 20); // Set power-down timing, (iholdDelay 0–15, tpowerdown 0–255) → None
23
+ // IHOLDDELAY and TPOWERDOWN, units of 2^18 clocks
24
+ await motor.setMicrosteps(32); // Set microstep resolution, (n 1–256) → None
25
+ // writes CHOPCONF.MRES
26
+ await motor.setInterpolation(true); // Interpolate to 256 microsteps, (enabled) → None
27
+ // sets CHOPCONF.intpol
28
+ await motor.setChopperMode(false); // Choose chopper, (spreadcycle) → None
29
+ // false selects StealthChop
30
+ await motor.setStealthchopThreshold(300); // Set StealthChop velocity limit, (tpwmthrs 20 bit) → None
31
+ // faster than this the chip switches to SpreadCycle
32
+ await motor.configureChopper(3, 2, 5, 0); // Configure chopper timing, (toff, tbl, hstrt, hend) → None
33
+ // direct CHOPCONF fields
34
+ await motor.configureStealthchop(true, true, 36, 14, 1, 4, 12); // Configure StealthChop, (autoscale, autograd, pwmOfs, pwmGrad, pwmFreq, pwmReg, pwmLim) → None
35
+ // direct PWMCONF fields
36
+ await motor.setFreewheel(0); // Set standstill mode, (mode 0–3) → None
37
+ // PWMCONF.freewheel, only effective when IHOLD is 0
38
+ await motor.setVsense(false); // Select sense range, (highSensitivity) → None
39
+ // false keeps the 0.325 V full scale
40
+ await motor.setAnalogScaling(true); // Current reference source, (enabled) → None
41
+ // true takes the reference from VREF
42
+ await motor.setDirectionInverted(false); // Invert direction, (inverted) → None
43
+ // GCONF.shaft
44
+ await motor.setIndexOutput(0); // Select INDEX output, (mode 0–2) → None
45
+ // 0 first microstep, 1 pre-warning, 2 step pulses
46
+ await motor.setDriverProtection(true, true); // Short protections, (shortLs, shortGnd) → None
47
+ // true keeps the protection enabled
48
+ await motor.setDoubleEdge(false); // Step on both edges, (enabled) → None
49
+ // CHOPCONF.dedge
50
+ await motor.setSendDelay(0); // Set reply delay, (n 0–15) → None
51
+ // NODECONF.SENDDELAY
52
+
53
+ await motor.run(300); // Spin with the internal generator, (stepsPerS full steps/s) → None
54
+ // converts to VACTUAL using the 12 MHz clock
55
+ await sleep(2000);
56
+ console.log('position', await motor.microstepPosition()); // Read microstep counter, () → number 0–1023
57
+ // MSCNT
58
+ console.log('currents', await motor.readCoilCurrents()); // Read coil currents, () → [number, number] table values
59
+ // two signed 9-bit MSCURACT fields
60
+ console.log('tstep', await motor.readTstep()); // Read step interval, () → number clocks
61
+ // time between 1/256 microsteps
62
+ console.log('scale', await motor.readCurrentScale()); // Read actual current scale, () → number 0–31
63
+ // DRV_STATUS.CS_ACTUAL
64
+ console.log('temp', await motor.readTemperatureFlags()); // Read temperature flags, () → number 0–15
65
+ // bit 0 t120 … bit 3 t157
66
+ console.log('status', await motor.readStatus()); // Read driver status, () → object
67
+ // decoded DRV_STATUS
68
+ console.log('standstill', await motor.isStandstill()); // Read standstill flag, () → boolean
69
+ // DRV_STATUS.stst
70
+ console.log('fault', await motor.readFault()); // Read fault bitmask, () → number
71
+ // FAULT_* constants, 0 = none
72
+ await motor.stop(); // Stop the motor, () → None
73
+ // VACTUAL = 0, STEP input takes over again
74
+
75
+ console.log('gstat', await motor.readGlobalStatus(true)); // Read and clear GSTAT, (clear=false) → object
76
+ // reset, drv_err, uv_cp
77
+ console.log('ifcnt', await motor.readIfcnt()); // Read write counter, () → number
78
+ // IFCNT
79
+ console.log('ioin', await motor.readIoin()); // Read IOIN, () → object
80
+ // raw word, sel_a and silicon version
81
+ console.log('otp', (await motor.readOtp()).toString(16)); // Read OTP image, () → number
82
+ // OTP_READ
83
+ console.log('pwm_auto', await motor.readPwmAuto()); // Read StealthChop tuning, () → object
84
+ // PWM_SCALE and PWM_AUTO results
85
+ console.log('gconf', (await motor.readRegister(0x00)).toString(16)); // Read a raw register, (reg) → number
86
+ // any readable register
87
+ await motor.writeRegister(0x13, 300); // Write a raw register, (reg, value) → None
88
+ // here TPWMTHRS again
89
+ await motor.disable(); // Power stage off, () → None
90
+ // the motor freewheels
91
+ await connection.close();
92
+ })();
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Demo for the TMC2208 — a silent desk-fan / camera-slider controller.
5
+ *
6
+ * Enables the driver at 0.8 A with 16 microsteps, proves the UART link by
7
+ * reading IOIN.VERSION and IFCNT, then ramps the internal step generator
8
+ * from 0 to 600 full steps/s in 100 steps/s increments (the chip has no ramp
9
+ * of its own) printing StealthChop/SpreadCycle and CS_ACTUAL at each step.
10
+ * TPWMTHRS switches to SpreadCycle above 400 steps/s. After holding speed
11
+ * for 3 s it ramps down, reverses and repeats once. Any fault stops the
12
+ * motor, disables the driver and exits.
13
+ */
14
+
15
+ const { UARTConnection } = require('periph/src/connection/uart');
16
+ const { TMC2208Full } = require('periph/src/chips/motor/tmc2208');
17
+
18
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
19
+ const MICROSTEPS = 16;
20
+ const SPREAD_ABOVE = 400;
21
+
22
+ (async () => {
23
+ const port = process.env.UART_PORT || '/dev/ttyS0';
24
+ const connection = new UARTConnection(port, { baudRate: 115200, timeoutMs: 100 });
25
+ await connection.open();
26
+ const motor = new TMC2208Full(connection); // Create TMC2208 Full driver, (connection, {rSenseOhm=0.11 Ω, enPin})
27
+ await motor.init(); // Probe the chip and apply defaults, () → None
28
+
29
+ async function guard() {
30
+ // --- Stop on any driver fault ---
31
+ // Short circuits and over-temperature latch until the driver is
32
+ // disabled, so the demo shuts everything down and reports which fault fired.
33
+ const fault = await motor.readFault(); // Read fault bitmask, () → number
34
+ if (fault) {
35
+ await motor.stop(); // Stop the motor, () → None
36
+ await motor.disable(); // Power stage off, () → None
37
+ console.log('fault 0x' + fault.toString(16));
38
+ await connection.close();
39
+ process.exit(1);
40
+ }
41
+ }
42
+
43
+ async function ramp(from, to, sign) {
44
+ // --- Ramp the internal generator in 100 steps/s increments ---
45
+ // VACTUAL has no acceleration of its own, so the demo steps the speed
46
+ // and reports whether the chip is in StealthChop or SpreadCycle.
47
+ const inc = to >= from ? 100 : -100;
48
+ for (let speed = from; inc > 0 ? speed <= to : speed >= to; speed += inc) {
49
+ await motor.run(sign * speed); // Spin with the internal generator, (stepsPerS full steps/s) → None
50
+ await sleep(500);
51
+ const status = await motor.readStatus(); // Read driver status, () → object
52
+ console.log(`${speed} steps/s ${status.stealth ? 'stealth' : 'spread'} CS=${status.cs_actual}`);
53
+ await guard();
54
+ }
55
+ }
56
+
57
+ // --- Bring up the link and the power stage ---
58
+ // IOIN.VERSION and IFCNT prove the UART wiring and echo handling work
59
+ // before any motion is attempted.
60
+ const ioin = await motor.readIoin(); // Read IOIN, () → object
61
+ console.log('version 0x' + ioin.version.toString(16), 'IFCNT', await motor.readIfcnt()); // Read write counter, () → number
62
+ await motor.setCurrent(0.8); // Set run current, (rmsA A RMS) → None
63
+ await motor.setMicrosteps(MICROSTEPS); // Set microstep resolution, (n 1–256) → None
64
+ await motor.enable(); // Power stage on, () → None
65
+
66
+ // --- Quiet at low speed, strong at high speed ---
67
+ // StealthChop is silent but loses torque at speed; TPWMTHRS makes the chip
68
+ // change to SpreadCycle once TSTEP drops below the value for 400 steps/s.
69
+ await motor.setStealthchopThreshold(Math.floor(12e6 / (SPREAD_ABOVE * 256))); // Set StealthChop velocity limit, (tpwmthrs 20 bit) → None
70
+
71
+ for (const sign of [1, -1]) {
72
+ await ramp(0, 600, sign);
73
+ await sleep(3000);
74
+ await ramp(600, 0, sign);
75
+ await motor.stop(); // Stop the motor, () → None
76
+ await sleep(1000);
77
+ }
78
+
79
+ // --- Shut down and report ---
80
+ // Temperature comparators and GSTAT show whether the run stressed the driver.
81
+ console.log('temperature flags', await motor.readTemperatureFlags()); // Read temperature flags, () → number 0–15
82
+ console.log('global status', await motor.readGlobalStatus()); // Read GSTAT, (clear=false) → object
83
+ await motor.disable(); // Power stage off, () → None
84
+ await connection.close();
85
+ })();
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const { UARTConnection } = require('periph/src/connection/uart');
4
+ const { TMC2208Minimal } = require('periph/src/chips/motor/tmc2208');
5
+
6
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
7
+
8
+ (async () => {
9
+ const port = process.env.UART_PORT || '/dev/ttyS0';
10
+ const connection = new UARTConnection(port, { baudRate: 115200, timeoutMs: 100 });
11
+ await connection.open();
12
+ const motor = new TMC2208Minimal(connection, { rSenseOhm: 0.11 }); // Create TMC2208 driver, (connection, {rSenseOhm=0.11 Ω, enPin=null, echo=true})
13
+ await motor.init(); // Probe the chip and apply defaults, () → None
14
+
15
+ await motor.setCurrent(0.8); // Set run current, (rmsA A RMS) → None
16
+ for (const speed of [200, -200]) {
17
+ await motor.run(speed); // Spin with the internal generator, (stepsPerS full steps/s, sign = direction) → None
18
+ await sleep(3000);
19
+ console.log('standstill:', await motor.isStandstill()); // Read standstill flag, () → boolean
20
+ console.log('fault:', await motor.readFault()); // Read fault bitmask, () → number
21
+ }
22
+
23
+ await motor.stop(); // Stop the motor, () → None
24
+ await connection.close();
25
+ })();