periph 1.3.2 → 1.3.3

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 (76) hide show
  1. package/README.md +18 -0
  2. package/examples/accelerometer/bma180/complete.js +83 -0
  3. package/examples/accelerometer/bma180/demo.js +47 -0
  4. package/examples/accelerometer/bma180/minimal.js +21 -0
  5. package/examples/accelerometer/fxos8700/complete.js +111 -0
  6. package/examples/accelerometer/fxos8700/demo.js +80 -0
  7. package/examples/accelerometer/fxos8700/minimal.js +20 -0
  8. package/examples/accelerometer/lis3dh/complete.js +123 -0
  9. package/examples/accelerometer/lis3dh/demo.js +99 -0
  10. package/examples/accelerometer/lis3dh/minimal.js +19 -0
  11. package/examples/accelerometer/lsm303/complete.js +82 -0
  12. package/examples/accelerometer/lsm303/demo.js +96 -0
  13. package/examples/accelerometer/lsm303/minimal.js +23 -0
  14. package/examples/accelerometer/mma8451q/complete.js +96 -0
  15. package/examples/accelerometer/mma8451q/demo.js +120 -0
  16. package/examples/accelerometer/mma8451q/minimal.js +20 -0
  17. package/examples/adc_dac/ad5243/complete.js +52 -0
  18. package/examples/adc_dac/ad5243/demo.js +50 -0
  19. package/examples/adc_dac/ad5243/minimal.js +23 -0
  20. package/examples/adc_dac/ad5248/complete.js +49 -0
  21. package/examples/adc_dac/ad5248/demo.js +42 -0
  22. package/examples/adc_dac/ad5248/minimal.js +21 -0
  23. package/examples/adc_dac/ads1013/complete.js +51 -0
  24. package/examples/adc_dac/ads1013/demo.js +51 -0
  25. package/examples/adc_dac/ads1013/minimal.js +21 -0
  26. package/examples/adc_dac/ads1014/complete.js +88 -0
  27. package/examples/adc_dac/ads1014/demo.js +52 -0
  28. package/examples/adc_dac/ads1014/minimal.js +21 -0
  29. package/examples/adc_dac/ads1113/complete.js +47 -0
  30. package/examples/adc_dac/ads1113/demo.js +39 -0
  31. package/examples/adc_dac/ads1113/minimal.js +20 -0
  32. package/examples/adc_dac/ads1114/complete.js +77 -0
  33. package/examples/adc_dac/ads1114/demo.js +47 -0
  34. package/examples/adc_dac/ads1114/minimal.js +20 -0
  35. package/examples/adc_dac/ads1115/complete.js +82 -0
  36. package/examples/adc_dac/ads1115/demo.js +55 -0
  37. package/examples/adc_dac/ads1115/minimal.js +20 -0
  38. package/examples/display/pcf8578/complete.js +58 -0
  39. package/examples/display/pcf8578/demo.js +62 -0
  40. package/examples/display/pcf8578/minimal.js +19 -0
  41. package/examples/display/pcf8579/complete.js +58 -0
  42. package/examples/display/pcf8579/demo.js +61 -0
  43. package/examples/display/pcf8579/minimal.js +19 -0
  44. package/examples/imu/icm20948/complete.js +114 -0
  45. package/examples/imu/icm20948/demo.js +79 -0
  46. package/examples/imu/icm20948/minimal.js +22 -0
  47. package/examples/io_expander/mcp23008/complete.js +70 -0
  48. package/examples/io_expander/mcp23008/demo.js +58 -0
  49. package/examples/io_expander/mcp23008/minimal.js +20 -0
  50. package/examples/memory/mb85rc/complete.js +40 -0
  51. package/examples/memory/mb85rc/demo.js +58 -0
  52. package/examples/memory/mb85rc/minimal.js +15 -0
  53. package/examples/motor/drv2605/complete.js +100 -0
  54. package/examples/motor/drv2605/demo.js +55 -0
  55. package/examples/motor/drv2605/minimal.js +24 -0
  56. package/package.json +1 -1
  57. package/src/chips/accelerometer/bma180.js +573 -0
  58. package/src/chips/accelerometer/fxos8700.js +1600 -0
  59. package/src/chips/accelerometer/lis3dh.js +1341 -0
  60. package/src/chips/accelerometer/lsm303.js +1471 -0
  61. package/src/chips/accelerometer/mma8451q.js +1406 -0
  62. package/src/chips/adc_dac/_ads111x_base.js +272 -0
  63. package/src/chips/adc_dac/ad5243.js +231 -0
  64. package/src/chips/adc_dac/ad5248.js +194 -0
  65. package/src/chips/adc_dac/ads1013.js +219 -0
  66. package/src/chips/adc_dac/ads1014.js +509 -0
  67. package/src/chips/adc_dac/ads1113.js +112 -0
  68. package/src/chips/adc_dac/ads1114.js +201 -0
  69. package/src/chips/adc_dac/ads1115.js +232 -0
  70. package/src/chips/display/pcf8578.js +452 -0
  71. package/src/chips/display/pcf8579.js +451 -0
  72. package/src/chips/imu/icm20948.js +849 -0
  73. package/src/chips/io_expander/mcp23008.js +558 -0
  74. package/src/chips/memory/mb85rc.js +166 -0
  75. package/src/chips/motor/drv2605.js +592 -0
  76. package/src/discovery/registry.js +20 -19
@@ -0,0 +1,114 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { ICM20948Full } = require('../../../src/chips/imu/icm20948');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x68', 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 ICM20948Full(connection); // Create ICM20948 driver, (connection) → void
14
+ await imu.init(); // Wait for initialization, () → void
15
+ // runs the WHO_AM_I check and the default configuration
16
+
17
+ const [ax, ay, az] = await imu.accel(); // Read 3-axis acceleration, () → [number, number, number] m/s²
18
+ // converts raw accel registers to m/s² (16384 LSB/g at ±2g)
19
+ const [gx, gy, gz] = await imu.gyro(); // Read 3-axis angular rate, () → [number, number, number] rad/s
20
+ // converts raw gyro registers to rad/s (131 LSB/(°/s) at ±250dps)
21
+ const [accel, gyro, temp] = await imu.readAll(); // Read one coherent sample, () → [[number x3], [number x3], number] m/s², rad/s, °C
22
+ // burst-reads registers 0x2D…0x3A so all three belong to one sample
23
+ const t = await imu.temperature(); // Read die temperature, () → number °C
24
+ // converts raw temp register: raw/333.87 + 21.0
25
+
26
+ const [rax, ray, raz] = await imu.accelRaw(); // Read raw accel values, () → [number, number, number]
27
+ // returns signed 16-bit accelerometer counts
28
+ const [rgx, rgy, rgz] = await imu.gyroRaw(); // Read raw gyro values, () → [number, number, number]
29
+ // returns signed 16-bit gyroscope counts
30
+
31
+ await imu.configureGyro(1); // Configure gyro range, (fullScale=0) → void
32
+ // sets GYRO_FS_SEL: 0=±250, 1=±500, 2=±1000, 3=±2000 dps
33
+ await imu.configureAccel(1); // Configure accel range, (fullScale=0) → void
34
+ // sets ACCEL_FS_SEL: 0=±2g, 1=±4g, 2=±8g, 3=±16g
35
+ await imu.configureFilters(3, 3, true, true); // Configure low-pass filters, (gyroDlpf=3, accelDlpf=3, gyroFilter=true, accelFilter=true) → void
36
+ // sets *_DLPFCFG and *_FCHOICE; filter false bypasses the filter
37
+ await imu.configureSampleRate(10, 10); // Configure sample rate, (gyroDiv=10, accelDiv=10) → void
38
+ // sets the dividers; ODR = 1125 Hz / (1 + div)
39
+ await imu.setSensors(true, true); // Power sensors, (accel=true, gyro=true) → void
40
+ // writes PWR_MGMT_2 DISABLE_ACCEL / DISABLE_GYRO
41
+ await imu.setLowPower(false, false, 0, 0); // Configure duty-cycled mode, (accel=false, gyro=false, accelAvg=0, gyroAvg=0) → void
42
+ // writes LP_CONFIG and averaging; LP_EN is set last
43
+ await imu.setGyroOffset(0, 0, 0); // Set gyro offsets, (x, y, z) rad/s → void
44
+ // writes the 16-bit offset-cancellation registers (0.0305 dps/LSB)
45
+ const [ox, oy, oz] = await imu.getAccelOffset(); // Read accel offset codes, () → [number, number, number]
46
+ // reads the factory-trimmed 15-bit offsets (0.98 mg/LSB)
47
+ await imu.setAccelOffset(ox, oy, oz); // Write accel offset codes, (x, y, z) → void
48
+ // writes the 15-bit offsets back unchanged
49
+
50
+ await imu.enableMag(); // Enable magnetometer, () → void
51
+ // starts the I²C master and reads the AK09916 block continuously
52
+ const [mx, my, mz] = await imu.mag(); // Read 3-axis magnetic field, () → [number, number, number] µT
53
+ // converts raw counts at 0.15 µT/LSB; rejects on HOFL
54
+ const [rmx, rmy, rmz] = await imu.magRaw(); // Read raw mag values, () → [number, number, number]
55
+ // returns signed 16-bit magnetometer counts
56
+ const magReady = await imu.magDataReady(); // Check magnetometer data ready, () → boolean
57
+ // reads ST1.DRDY from the shadowed block
58
+ await imu.magSetMode(8); // Set magnetometer mode, (mode) → void
59
+ // writes CNTL2: 0=off, 1=single, 2/4/6/8=continuous 1-4
60
+ const who = await imu.auxReadByte(0x0C, 0x01); // Read auxiliary byte, (address, register) → number
61
+ // reads AK09916 WIA2 (0x09) through I²C-master slave 4
62
+ await imu.auxWriteByte(0x0C, 0x31, 0x08); // Write auxiliary byte, (address, register, value) → void
63
+ // writes AK09916 CNTL2 through slave 4
64
+
65
+ const ready = await imu.dataReady(); // Check data ready flag, () → boolean
66
+ // reads INT_STATUS_1.RAW_DATA_0_RDY_INT
67
+
68
+ await imu.enableFifo(true, true, false); // Enable FIFO sources, (accel=true, gyro=true, temp=false) → void
69
+ // sets FIFO_EN_2 and USER_CTRL.FIFO_EN, then resets the FIFO
70
+ await imu.setFifoMode(false); // Select FIFO mode, (snapshot=false) → void
71
+ // 0 = stream (overwrite oldest), 1 = snapshot (stop when full)
72
+ await sleep(50);
73
+ const count = await imu.fifoCount(); // Read FIFO byte count, () → number
74
+ // reads FIFO_COUNTH/L: number of bytes available
75
+ const data = await imu.readFifo(); // Read FIFO data, (count?) → Buffer
76
+ // reads available bytes from FIFO_R_W in chunks
77
+ await imu.resetFifo(); // Reset FIFO buffer, () → void
78
+ // asserts and de-asserts FIFO_RST
79
+
80
+ await imu.setWakeOnMotion(200, true); // Arm wake-on-motion, (thresholdMg, enabled=true) → void
81
+ // writes ACCEL_WOM_THR (4 mg/LSB) and ACCEL_INTEL_CTRL
82
+ await imu.setInterruptPin(false, false, true, false); // Configure INT1 pin, (activeLow=false, openDrain=false, latch=false, anyReadClears=false) → void
83
+ // writes INT_PIN_CFG
84
+ await imu.enableInterrupt(ICM20948Full.SOURCE_DATA_READY); // Enable interrupt source, (source) → void
85
+ // sets the source's enable bit in INT_ENABLE*
86
+ const status = await imu.pollInterrupt(); // Read interrupt status, () → number
87
+ // reads INT_STATUS, _1, _2 (clearing them) into SOURCE_* bits
88
+ await imu.disableInterrupt(ICM20948Full.SOURCE_DATA_READY); // Disable interrupt source, (source) → void
89
+ // clears the source's enable bit
90
+ await imu.onInterrupt((s) => console.log('INT', s)); // Subscribe to INT1, (callback) → void
91
+ // callback receives the status from pollInterrupt
92
+ await imu.offInterrupt(); // Unsubscribe, () → void
93
+ // removes the callback
94
+
95
+ const [stAccel, stGyro] = await imu.selfTest(); // Run self-test, () → [[number x3], [number x3]]
96
+ // raw response (enabled minus disabled) per axis; no pass/fail
97
+ const tbc = await imu.readTimebaseCorrection(); // Read PLL time-base correction, () → number %
98
+ // reads TIMEBASE_CORRECTION_PLL (0.079 %/LSB, signed)
99
+
100
+ await imu.setSleep(true); // Enter sleep mode, (sleep=true) → void
101
+ // sets SLEEP bit in PWR_MGMT_1
102
+ await sleep(10);
103
+ await imu.setSleep(false); // Wake from sleep, (sleep=true) → void
104
+ // clears SLEEP bit in PWR_MGMT_1
105
+
106
+ console.log('t=%s mag=%s,%s,%s ready=%s', t.toFixed(2), mx.toFixed(1), my.toFixed(1), mz.toFixed(1), ready);
107
+ void [ax, ay, az, gx, gy, gz, accel, gyro, temp, rax, ray, raz, rgx, rgy, rgz, rmx, rmy, rmz,
108
+ magReady, who, count, data, status, stAccel, stGyro, tbc];
109
+ await imu.reset(); // Reset the device, () → void
110
+ // DEVICE_RESET and wait; create a new driver afterwards
111
+ connection.close();
112
+ }
113
+
114
+ main().catch(err => { console.error(err); process.exit(1); });
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { ICM20948Full } = require('../../../src/chips/imu/icm20948');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x68', 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
+
14
+ // --- Configure for motion and heading monitoring ---
15
+ // ±4g / ±500dps give headroom for sharper motion; DLPFCFG 3 with a divider of
16
+ // 10 keeps a ~100 Hz sample rate with a ~50 Hz noise bandwidth. The
17
+ // magnetometer runs through the chip's own I²C master, so one connection
18
+ // is enough.
19
+ const imu = new ICM20948Full(connection); // Create ICM20948 driver, (connection) → void
20
+ await imu.configureAccel(1); // Configure accel range, (fullScale=0) → void
21
+ await imu.configureGyro(1); // Configure gyro range, (fullScale=0) → void
22
+ await imu.configureFilters(3, 3); // Configure low-pass filters, (gyroDlpf=3, accelDlpf=3, gyroFilter=true, accelFilter=true) → void
23
+ await imu.configureSampleRate(10, 10); // Configure sample rate, (gyroDiv=10, accelDiv=10) → void
24
+ await imu.enableMag(); // Enable magnetometer, () → void
25
+
26
+ console.log('ICM-20948 die temperature: %s C', (await imu.temperature()).toFixed(1)); // Read die temperature, () → number °C
27
+
28
+ // --- Arm wake-on-motion and route it to the interrupt status ---
29
+ // A 200 mg threshold flags a bump; pollInterrupt() reports it as
30
+ // SOURCE_WAKE_ON_MOTION without needing the INT pin wired.
31
+ await imu.setWakeOnMotion(200); // Arm wake-on-motion, (thresholdMg, enabled=true) → void
32
+ await imu.enableInterrupt(ICM20948Full.SOURCE_WAKE_ON_MOTION); // Enable interrupt source, (source) → void
33
+
34
+ // --- Stream accelerometer + gyro into the FIFO ---
35
+ // Stream mode overwrites the oldest data; once per second the FIFO is
36
+ // drained and counted in 12-byte frames (accel X, Y, Z, gyro X, Y, Z).
37
+ await imu.enableFifo(true, true); // Enable FIFO sources, (accel=true, gyro=true, temp=false) → void
38
+ await imu.setFifoMode(false); // Select FIFO mode, (snapshot=false) → void
39
+
40
+ console.log('roll pitch heading |gyro|');
41
+
42
+ const start = Date.now();
43
+ let lastFifo = start;
44
+ while (Date.now() - start < 60000) {
45
+ const [[ax, ay, az], [gx, gy, gz]] = await imu.readAll(); // Read one coherent sample, () → [[number x3], [number x3], number] m/s², rad/s, °C
46
+ const [mx, my, mz] = await imu.mag(); // Read 3-axis magnetic field, () → [number, number, number] µT
47
+
48
+ // --- Compute roll, pitch and a tilt-compensated heading ---
49
+ // The magnetometer frame is rotated 180° about X relative to the
50
+ // inertial frame, so (mx, -my, -mz) maps it into the accel frame
51
+ // before the tilt compensation rotates it into the horizontal plane.
52
+ const roll = Math.atan2(ay, az);
53
+ const pitch = Math.atan2(-ax, Math.sqrt(ay * ay + az * az));
54
+ const bx = mx, by = -my, bz = -mz;
55
+ const xh = bx * Math.cos(pitch) + bz * Math.sin(pitch);
56
+ const yh = bx * Math.sin(roll) * Math.sin(pitch) + by * Math.cos(roll)
57
+ - bz * Math.sin(roll) * Math.cos(pitch);
58
+ const heading = (Math.atan2(-yh, xh) * 180 / Math.PI + 360) % 360;
59
+ const gyroMag = Math.sqrt(gx * gx + gy * gy + gz * gz);
60
+
61
+ console.log('%s %s %s %s',
62
+ (roll * 180 / Math.PI).toFixed(1), (pitch * 180 / Math.PI).toFixed(1),
63
+ heading.toFixed(1), gyroMag.toFixed(3));
64
+
65
+ const status = await imu.pollInterrupt(); // Read interrupt status, () → number
66
+ if (status & ICM20948Full.SOURCE_WAKE_ON_MOTION) console.log('MOTION');
67
+
68
+ if (Date.now() - lastFifo >= 1000) {
69
+ lastFifo = Date.now();
70
+ const count = await imu.fifoCount(); // Read FIFO byte count, () → number
71
+ const data = await imu.readFifo(); // Read FIFO data, (count?) → Buffer
72
+ console.log('FIFO: %d bytes (count %d), %d frames', data.length, count, Math.floor(data.length / 12));
73
+ }
74
+ await sleep(100);
75
+ }
76
+ connection.close();
77
+ }
78
+
79
+ 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 { ICM20948Minimal } = require('../../../src/chips/imu/icm20948');
5
+
6
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
7
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x68', 16);
8
+
9
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR);
10
+ const imu = new ICM20948Minimal(connection); // Create ICM20948 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,70 @@
1
+ 'use strict';
2
+ const { I2CConnection } = require('periph/src/connection/i2c');
3
+ const { Mcp23008Full } = require('periph/src/chips/io_expander/mcp23008');
4
+
5
+ async function main() {
6
+ const connection = new I2CConnection(1, 0x20); // Create I2C connection, (bus, addr=0x20)
7
+ const chip = new Mcp23008Full(connection); // Create MCP23008 full driver, (connection, addr=0x20)
8
+ // clears OLAT; all pins start as inputs
9
+ await chip.ready;
10
+
11
+ // --- Pin proxy — async API ---
12
+ const p0 = chip.pin(0, 'out'); // Get full pin proxy, (n, direction='in') → FullPin
13
+ // GP0 as output; GP7 is a normal bidirectional pin
14
+ console.log('direction:', p0.direction); // direction property, () → string 'in'|'out'
15
+ await p0.write(1); // Write pin, (value=0|1) → Promise<void>
16
+ // sets the OLAT bit via the shadow
17
+ const v = await p0.read(); // Read pin, () → Promise<int 0|1>
18
+ // reads GPIO (actual pin level)
19
+ console.log('GP0 level:', v);
20
+ await p0.setDirection('in'); // Set direction, (direction) → Promise<void>
21
+ // writes IODIR; OLAT is latched first for outputs
22
+
23
+ // --- Port-level operations ---
24
+ await chip.writePort(0, 0b00001111); // Write all 8 pins, (port=0, mask) → Promise<void>
25
+ // whole-port OLAT write
26
+ const port = await chip.readPort(); // Read all 8 pins, (port=0) → Promise<int bitmask>
27
+ // GPIO register
28
+ console.log('GPIO=0x' + port.toString(16).padStart(2, '0'));
29
+
30
+ // --- Configuration ---
31
+ await chip.configurePullup(0xF0); // Configure pull-ups, (mask) → Promise<void>
32
+ // 100 kΩ pull-ups on GP4–GP7 (inputs only)
33
+ await chip.configurePolarity(0x00); // Configure input polarity, (mask) → Promise<void>
34
+ // 1 bits invert the GPIO read
35
+ await chip.setDefaultValue(0x00); // Set DEFVAL, (mask) → Promise<void>
36
+ // reference for default-compare interrupts
37
+ await chip.configureIntPin({ openDrain: false, activeHigh: false }); // Configure INT output, (options) → Promise<void>
38
+ // push-pull, active-low (IOCON ODR/INTPOL)
39
+ await chip.setSequential(true); // Sequential access, (enabled) → Promise<void>
40
+ // IOCON SEQOP = 0 (driver default)
41
+ const iodir = await chip.readRegister(0x00); // Read raw register, (reg) → Promise<int>
42
+ // escape hatch for debugging
43
+ console.log('IODIR=0x' + iodir.toString(16).padStart(2, '0'));
44
+ await chip.writeRegister(0x02, 0x10); // Write raw register, (reg, value) → Promise<void>
45
+ // GPINTEN: arm GP4
46
+
47
+ // --- Interrupts ---
48
+ await chip.enablePinInterrupt(0xF0); // Arm interrupt-on-change, (mask) → Promise<void>
49
+ // GP4–GP7
50
+ await chip.onInterrupt((status) => { // Subscribe to INT, (callback, options) → Promise<void>
51
+ console.log('interrupt, INTF=0x' + status.toString(16)); // INT line if wired, else 5 ms polling
52
+ }, { mode: 'default' });
53
+ const p4 = chip.pin(4, 'in');
54
+ await p4.watch((pin) => console.log('GP4 changed'), 'change'); // Watch a pin, (handler, trigger='change') → Promise<void>
55
+ // arms GP4 in GPINTEN, edge filtered in software
56
+ const flags = await chip.pollInterrupt(); // Read INTF and clear, () → Promise<int>
57
+ // INTCAP is read and discarded
58
+ const cap = await chip.readCapture(); // Read captured port, () → Promise<int>
59
+ // port snapshot at the interrupt
60
+ console.log('INTF=0x' + flags.toString(16) + ' INTCAP=0x' + cap.toString(16));
61
+ await p4.unwatch(); // Stop watching, () → Promise<void>
62
+ // clears its GPINTEN bit
63
+ await chip.offInterrupt(); // Unsubscribe, () → Promise<void>
64
+ // stops delivery
65
+ await chip.reset(); // Restore reset values, () → Promise<void>
66
+ // rewrites all registers, clears shadows
67
+ await connection.close();
68
+ }
69
+
70
+ main();
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+ /**
3
+ * MCP23008 demo — LED scanner with interrupt-driven button input.
4
+ *
5
+ * Hardware:
6
+ * GP0–GP3: four LEDs (anode → GP via 220 Ω, cathode → GND; active-high)
7
+ * GP4–GP7: four push buttons (pin → GND when pressed; 100 kΩ pull-up enabled)
8
+ *
9
+ * Runs a scanner pattern on the LEDs. Button presses raise an interrupt-on-change;
10
+ * the callback prints the INTF mask and INTCAP snapshot and holds the LED
11
+ * matching the pressed button (GP4→GP0, …) for one second.
12
+ */
13
+ const { I2CConnection } = require('periph/src/connection/i2c');
14
+ const { Mcp23008Full } = require('periph/src/chips/io_expander/mcp23008');
15
+
16
+ async function main() {
17
+ // --- Initialise bus and driver ---
18
+ const connection = new I2CConnection(1, 0x20); // Create I2C connection, (bus, addr=0x20)
19
+ const chip = new Mcp23008Full(connection); // Create MCP23008 full driver, (connection, addr=0x20)
20
+ await chip.ready;
21
+
22
+ // --- Configure LEDs and buttons ---
23
+ // GP0–GP3 are outputs; GP4–GP7 stay inputs with pull-ups, so a pressed button reads 0.
24
+ for (let n = 0; n < 4; n++) await chip.pin(n, 'out').setDirection('out'); // Set LED direction, (direction) → Promise<void>
25
+ await chip.configurePullup(0xF0); // Configure pull-ups, (mask) → Promise<void>
26
+
27
+ // --- Arm interrupt-on-change on the buttons ---
28
+ // Any button edge raises INT (or the 5 ms poll sees it); the callback reports INTF and
29
+ // INTCAP, then holds the matching LED.
30
+ let holdUntil = 0;
31
+ let holdMask = 0;
32
+ await chip.enablePinInterrupt(0xF0); // Arm GP4–GP7, (mask) → Promise<void>
33
+ await chip.onInterrupt(async (status) => { // Subscribe to INT, (callback, options) → Promise<void>
34
+ const captured = await chip.readCapture(); // Read port snapshot, () → Promise<int>
35
+ console.log('button INTF=0x' + status.toString(16) + ' INTCAP=0x' + captured.toString(16));
36
+ holdMask = (status >> 4) & 0x0F;
37
+ holdUntil = Date.now() + 1000;
38
+ });
39
+
40
+ // --- Scanner loop ---
41
+ let step = 0;
42
+ console.log('Running — press buttons GP4–GP7 to hold the matching LED');
43
+ const timer = setInterval(async () => {
44
+ const leds = Date.now() < holdUntil ? holdMask : (1 << (step % 4));
45
+ await chip.writePort(0, leds); // Write all 8 pins, (port=0, mask) → Promise<void>
46
+ const port = await chip.readPort(); // Read all 8 pins, (port=0) → Promise<int bitmask>
47
+ console.log('pos=' + (step % 4) + ' port=0x' + port.toString(16).padStart(2, '0'));
48
+ step++;
49
+ if (step >= 40) {
50
+ clearInterval(timer);
51
+ await chip.offInterrupt(); // Unsubscribe, () → Promise<void>
52
+ await chip.writePort(0, 0x00); // Clear all outputs, (port=0, mask=0x00) → Promise<void>
53
+ await connection.close();
54
+ }
55
+ }, 100);
56
+ }
57
+
58
+ main();
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+ const { I2CConnection } = require('periph/src/connection/i2c');
3
+ const { Mcp23008Minimal } = require('periph/src/chips/io_expander/mcp23008');
4
+
5
+ async function main() {
6
+ const connection = new I2CConnection(1, 0x20); // Create I2C connection, (bus, addr=0x20)
7
+ const chip = new Mcp23008Minimal(connection); // Create MCP23008 driver, (connection, addr=0x20)
8
+
9
+ const p0 = chip.pin(0, 'in'); // Get pin proxy, (n, direction='in') → Pin
10
+ const p7 = chip.pin(7, 'out'); // Get pin proxy, (n, direction='out') → Pin
11
+
12
+ setInterval(async () => {
13
+ const port = await chip.readPort(); // Read all 8 pins, (port=0) → Promise<int bitmask>
14
+ const level = await p0.read(); // Read pin, () → Promise<int 0|1>
15
+ await p7.write(level); // Write pin, (value=0|1) → Promise<void>
16
+ console.log('GPIO=0x' + port.toString(16).padStart(2, '0') + ' GP0=' + level);
17
+ }, 200);
18
+ }
19
+
20
+ main();
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { MB85RCFull } = require('../../../src/chips/memory/mb85rc');
5
+
6
+ async function main() {
7
+ const connection = new I2CConnection(1, 0x50, null, null, 2); // Create I2C connection, (bus=1, addr=0x50, intPin=null, enPin=null, regBytes=2) → Connection
8
+ const fram = new MB85RCFull(connection); // Create MB85RC driver, (connection) → void
9
+
10
+ console.log('Size:', fram.size(), 'bytes'); // Get array size, () → number
11
+ // always 32768 for the MB85RC256V
12
+ fram.maxChunk = 16; // Set max bytes per bus transaction, (maxChunk=30) → void
13
+ console.log('maxChunk:', fram.maxChunk); // Get max bytes per bus transaction, () → number
14
+
15
+ await fram.writeByte(0x0010, 0xA5); // Write a single byte, (address 0–32767, value 0–255) → void
16
+ // no write cycle, no polling
17
+ console.log('Byte:', (await fram.readByte(0x0010)).toString(16)); // Read a single byte, (address 0–32767) → number
18
+ // random read
19
+
20
+ await fram.write(0x0100, Buffer.from(Array.from({ length: 40 }, (_, i) => i))); // Sequential write, (address, data) → void
21
+ // split into maxChunk-byte transactions
22
+ const data = await fram.read(0x0100, 40); // Sequential read, (address, length) → Buffer
23
+ // split into maxChunk-byte transactions
24
+ console.log('Block:', data.toString('hex'));
25
+
26
+ await fram.fill(0x0100, 40, 0xFF); // Fill a range, (address, length, value=0) → void
27
+ // writes value over the range in chunks
28
+ console.log('After fill:', (await fram.read(0x0100, 8)).toString('hex'));
29
+
30
+ try {
31
+ const idConnection = new I2CConnection(1, 0x7C, null, null, 1); // Create Device ID connection, (bus=1, addr=0x7C, intPin=null, enPin=null, regBytes=1) → Connection
32
+ const id = await fram.readDeviceId(idConnection, 0x50); // Read Device ID, (idConnection, address=0x50) → {manufacturer, density, product}
33
+ // reads 3 bytes via reserved slave address 0x7C
34
+ console.log('Device ID:', id);
35
+ } catch (e) {
36
+ console.log('Device ID not readable on this bus');
37
+ }
38
+ }
39
+
40
+ main().catch(console.error);
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { MB85RCFull } = require('../../../src/chips/memory/mb85rc');
5
+
6
+ async function main() {
7
+ const connection = new I2CConnection(1, 0x50, null, null, 2); // Create I2C connection, (bus=1, addr=0x50, intPin=null, enPin=null, regBytes=2) → Connection
8
+ const fram = new MB85RCFull(connection); // Create MB85RC driver, (connection) → void
9
+
10
+ // --- Persistent boot counter ---
11
+ // A 4-byte big-endian counter at 0x0000 survives power loss. FRAM has no
12
+ // write cycle, so the increment is committed the moment the write ends.
13
+ const counter = (await fram.read(0x0000, 4)).readUInt32BE(0) + 1; // Sequential read, (address, length) → Buffer
14
+ const cbuf = Buffer.alloc(4);
15
+ cbuf.writeUInt32BE(counter, 0);
16
+ await fram.write(0x0000, cbuf); // Sequential write, (address, data) → void
17
+ console.log('Boot count:', counter);
18
+
19
+ // --- Ring-buffer logger, back-to-back with no delays ---
20
+ // 1,000 records of 16 bytes (index + counter + padding) are written one
21
+ // after the other without any pause — an EEPROM would need ACK polling
22
+ // after every page, FRAM does not.
23
+ const LOG_BASE = 0x0100, RECORD = 16, COUNT = 1000, RING = 200;
24
+ const t0 = Date.now();
25
+ for (let i = 0; i < COUNT; i++) {
26
+ const rec = Buffer.alloc(RECORD);
27
+ rec.writeUInt32BE(i, 0);
28
+ rec.writeUInt32BE(counter, 4);
29
+ await fram.write(LOG_BASE + (i % RING) * RECORD, rec); // Sequential write, (address, data) → void
30
+ }
31
+ const dt = (Date.now() - t0) / 1000;
32
+ console.log('Logged', COUNT * RECORD, 'bytes in', dt.toFixed(3), 's =', Math.round(COUNT * RECORD / dt), 'B/s');
33
+
34
+ // --- Verify the last five records ---
35
+ // Read back the newest records from the ring and check their contents.
36
+ let ok = true;
37
+ for (let i = COUNT - 5; i < COUNT; i++) {
38
+ const rec = await fram.read(LOG_BASE + (i % RING) * RECORD, RECORD); // Sequential read, (address, length) → Buffer
39
+ if (rec.readUInt32BE(0) !== i || rec.readUInt32BE(4) !== counter) ok = false;
40
+ }
41
+ console.log('Last 5 records verified:', ok);
42
+
43
+ // --- Clear the log area ---
44
+ // fill() zeroes the whole ring in chunked transactions.
45
+ await fram.fill(LOG_BASE, RING * RECORD, 0); // Fill a range, (address, length, value=0) → void
46
+ console.log('Log cleared; array size:', fram.size(), 'bytes'); // Get array size, () → number
47
+
48
+ // --- Device ID (needs the reserved address 0x7C) ---
49
+ // Some hosts (Linux i2c-dev) refuse addresses 0x78-0x7F; skip then.
50
+ try {
51
+ const idConnection = new I2CConnection(1, 0x7C, null, null, 1); // Create Device ID connection, (bus=1, addr=0x7C, intPin=null, enPin=null, regBytes=1) → Connection
52
+ console.log('Device ID:', await fram.readDeviceId(idConnection, 0x50)); // Read Device ID, (idConnection, address=0x50) → {manufacturer, density, product}
53
+ } catch (e) {
54
+ console.log('Device ID not available');
55
+ }
56
+ }
57
+
58
+ main().catch(console.error);
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('../../../src/connection/i2c');
4
+ const { MB85RCMinimal } = require('../../../src/chips/memory/mb85rc');
5
+
6
+ const connection = new I2CConnection(1, 0x50, null, null, 2); // Create I2C connection, (bus=1, addr=0x50, intPin=null, enPin=null, regBytes=2) → Connection
7
+ const fram = new MB85RCMinimal(connection); // Create MB85RC driver, (connection) → void
8
+
9
+ let counter = 0;
10
+ setInterval(async () => {
11
+ await fram.writeByte(0x0000, counter); // Write a single byte, (address 0–32767, value 0–255) → void
12
+ const value = await fram.readByte(0x0000); // Read a single byte, (address 0–32767) → number
13
+ console.log('Stored:', value);
14
+ counter = (counter + 1) & 0xFF;
15
+ }, 1000);
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { DRV2605Full } = require('periph/src/chips/motor/drv2605');
5
+
6
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
7
+
8
+ (async () => {
9
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
10
+ const connection = new I2CConnection(bus, DRV2605Full.I2C_ADDRESS);
11
+ const haptic = new DRV2605Full(connection, false); // Create DRV2605 Full driver, (connection, lra=false)
12
+ await haptic.init(); // Reset, verify and configure the chip, () → None
13
+ // DEV_RESET, DEVICE_ID check, leave standby, select ERM/LRA
14
+
15
+ console.log('device id', await haptic.readDeviceId()); // Read DEVICE_ID, () → number
16
+ // bits 7:5 of STATUS; 3 for the DRV2605
17
+ await haptic.playEffect(DRV2605Full.EFFECT_STRONG_CLICK); // Play a ROM effect, (effectId 1–123) → None
18
+ // writes slot 1 and the end marker, then sets GO
19
+ await haptic.waitDone(); // Wait for playback, (timeoutMs=5000) → boolean
20
+ // polls GO until the sequence finishes
21
+ await haptic.playSequence([DRV2605Full.EFFECT_STRONG_CLICK, ['wait', 100], DRV2605Full.EFFECT_BUZZ]); // Play a sequence, (items ≤ 8) → None
22
+ // number = effect, ['wait', ms] = delay in 10 ms steps
23
+ await haptic.waitDone(); // Wait for playback, (timeoutMs=5000) → boolean
24
+ console.log('playing', await haptic.isPlaying()); // Check playback, () → boolean
25
+ // reads the GO bit
26
+ await haptic.stop(); // Cancel playback, () → None
27
+ // clears GO; also leaves RTP mode
28
+
29
+ await haptic.setLibrary(1); // Select ROM library, (library 0–6) → None
30
+ // 0 empty, 1–5 ERM libraries A–E, 6 LRA library
31
+ await haptic.setActuator(false); // Select actuator type, (lra) → None
32
+ // sets N_ERM_LRA; recalibrate after changing it
33
+ await haptic.setOpenLoop(true); // Select open-loop drive, (enabled) → None
34
+ // ERM_OPEN_LOOP for an ERM, LRA_OPEN_LOOP for an LRA
35
+ await haptic.setBidirectional(true); // Select bidirectional input, (enabled) → None
36
+ // unidirectional is only valid closed-loop
37
+ await haptic.setRatedVoltage({ volts: 3.0 }); // Set rated voltage, ({volts V | code 0–255, lraFreqHz Hz}) → None
38
+ // code = V / 21.33 mV for an ERM
39
+ await haptic.setOverdriveClamp({ volts: 3.0 }); // Set overdrive clamp, ({volts V | code 0–255, lraFreqHz Hz}) → None
40
+ // code = V / 21.96 mV in open loop
41
+ await haptic.setDriveTime(2.0); // Set drive time, (ms) → None
42
+ // ERM back-EMF sample period (1 ms + 0.2 ms × code)
43
+ await haptic.setFeedback(3, 1, 2); // Set feedback control, (brakeFactor 0–7, loopGain 0–3, bemfGain 0–3) → None
44
+ // keeps the actuator-type bit
45
+ await haptic.setAdvanced(); // Set CONTROL1–3 fields, ({startupBoost, brakeStabilizer, sampleTime, blankingTime, idissTime, lraDriveTwice, supplyComp, noiseGate}) → None
46
+ // defaults match the chip's reset values
47
+ await haptic.setTimeOffsets({ overdriveMs: 0, sustainPosMs: 0, sustainNegMs: 0, brakeMs: 0 }); // Set library time offsets, ({overdriveMs, sustainPosMs, sustainNegMs, brakeMs}) → None
48
+ // ODT/SPT/SNT/BRT for open-loop ROM playback
49
+
50
+ await haptic.rtpLevel(0.5); // Stream an RTP amplitude, (level 0.0–1.0) → None
51
+ // enters RTP mode with signed data; 0.5 → 64
52
+ await sleep(500);
53
+ await haptic.setRtpFormat(false); // Select RTP data format, (unsigned) → None
54
+ // false = signed (default)
55
+ await haptic.rtpWrite(0x3F); // Write a raw RTP byte, (value 0–255) → None
56
+ // 0x3F = half scale in signed bidirectional mode
57
+ await sleep(500);
58
+ await haptic.stop(); // Cancel playback, () → None
59
+ // zeroes RTP_INPUT and returns to internal trigger
60
+
61
+ await haptic.setMode(DRV2605Full.MODE_INTERNAL_TRIGGER); // Select operating mode, (mode 0–7) → None
62
+ // 0 internal trigger … 7 auto-calibration
63
+ await haptic.setInput(false); // Select PWM/analog input, (analog) → None
64
+ // N_PWM_ANALOG; used with mode 3
65
+ await haptic.setHiZ(false); // Set high-impedance outputs, (enabled) → None
66
+ // true floats OUT+/OUT−
67
+ const cal = await haptic.calibrate(false, 3.0, 3.0); // Run auto-calibration, (lra, ratedVoltage V, overdriveVoltage V, lraFreqHz Hz) → {ok, comp, bemf, bemfGain}
68
+ // takes up to 1.2 s
69
+ console.log('calibrated', cal);
70
+ const stored = await haptic.getCalibration(); // Read calibration results, () → {comp, bemf, bemfGain}
71
+ // A_CAL_COMP, A_CAL_BEMF, BEMF_GAIN
72
+ await haptic.setCalibration(stored.comp, stored.bemf, stored.bemfGain); // Restore calibration, (comp, bemf, bemfGain) → None
73
+ // avoids recalibrating after a reset
74
+ console.log('actuator ok', await haptic.diagnose()); // Run actuator diagnostics, () → boolean
75
+ // true if DIAG_RESULT = 0
76
+ await haptic.setAudioToVibe({ acCouple: true, peakTimeMs: 20, filterHz: 125, minInputV: 0.1, maxInputV: 1.8, minDrive: 0.1, maxDrive: 1.0 }); // Configure audio-to-vibe, ({acCouple, peakTimeMs, filterHz, minInputV, maxInputV, minDrive, maxDrive}) → None
77
+ // enters audio-to-vibe mode
78
+ await haptic.setMode(DRV2605Full.MODE_INTERNAL_TRIGGER); // Select operating mode, (mode 0–7) → None
79
+ // back to internal trigger
80
+
81
+ await haptic.playEffect(DRV2605Full.EFFECT_BUZZ); // Play a ROM effect, (effectId 1–123) → None
82
+ // a buzz, so the supply and LRA readings are valid
83
+ await sleep(200);
84
+ console.log('vdd', await haptic.readSupplyVoltage()); // Read supply voltage, () → number V
85
+ // VBAT × 5.6 / 255; valid during playback
86
+ console.log('lra', await haptic.readLraFrequency()); // Read LRA frequency, () → number Hz | null
87
+ // null when LRA_PERIOD is 0
88
+ await haptic.stop(); // Cancel playback, () → None
89
+ console.log(await haptic.readStatus()); // Read status flags, () → {diagFailed, fbTimeout, overTemp, overCurrent}
90
+ // clears the latched flags
91
+ console.log('otp', await haptic.otpProgrammed()); // Read OTP status, () → boolean
92
+ // true once the OTP has been burned
93
+ // await haptic.programOtp(true); // IRREVERSIBLE one-time OTP burn, (confirm) → None
94
+ await haptic.standby(); // Enter software standby, () → None
95
+ // also stops playback
96
+ await haptic.wake(); // Leave software standby, () → None
97
+ await haptic.reset(); // Reset all registers, () → None
98
+ // re-run init() afterwards
99
+ await connection.close();
100
+ })();