periph 1.2.0 → 1.3.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 (153) hide show
  1. package/README.md +18 -0
  2. package/examples/accelerometer/bma150/complete.js +62 -0
  3. package/examples/accelerometer/bma150/demo.js +65 -0
  4. package/examples/accelerometer/bma150/minimal.js +18 -0
  5. package/examples/adc_dac/hy3131/complete.js +66 -0
  6. package/examples/adc_dac/hy3131/demo.js +37 -0
  7. package/examples/adc_dac/hy3131/minimal.js +18 -0
  8. package/examples/discovery/complete.js +25 -0
  9. package/examples/discovery/demo.js +30 -0
  10. package/examples/discovery/minimal.js +12 -0
  11. package/examples/display/il0373/complete.js +71 -0
  12. package/examples/display/il0373/demo.js +49 -0
  13. package/examples/display/il0373/minimal.js +26 -0
  14. package/examples/display/ssd1331/complete.js +83 -0
  15. package/examples/display/ssd1331/demo.js +49 -0
  16. package/examples/display/ssd1331/minimal.js +27 -0
  17. package/examples/display/st7036/complete.js +71 -0
  18. package/examples/display/st7036/demo.js +56 -0
  19. package/examples/display/st7036/minimal.js +21 -0
  20. package/examples/display/uc1611s/complete.js +135 -0
  21. package/examples/display/uc1611s/complete_spi.js +128 -0
  22. package/examples/display/uc1611s/demo.js +90 -0
  23. package/examples/display/uc1611s/demo_spi.js +91 -0
  24. package/examples/display/uc1611s/minimal.js +28 -0
  25. package/examples/display/uc1611s/minimal_spi.js +30 -0
  26. package/examples/display/uc8159/complete.js +64 -0
  27. package/examples/display/uc8159/demo.js +41 -0
  28. package/examples/display/uc8159/minimal.js +28 -0
  29. package/examples/display/uc8276c/complete.js +73 -0
  30. package/examples/display/uc8276c/demo.js +49 -0
  31. package/examples/display/uc8276c/minimal.js +26 -0
  32. package/examples/environmental/bme280/complete.js +1 -1
  33. package/examples/environmental/bme280/demo.js +1 -1
  34. package/examples/environmental/bme280/minimal.js +1 -1
  35. package/examples/gyroscope/l3g4200d/complete.js +1 -1
  36. package/examples/gyroscope/l3g4200d/demo.js +1 -1
  37. package/examples/gyroscope/l3g4200d/minimal.js +1 -1
  38. package/examples/memory/23x1024/complete.js +54 -0
  39. package/examples/memory/23x1024/demo.js +51 -0
  40. package/examples/memory/23x1024/minimal.js +22 -0
  41. package/examples/memory/mx25l12845e/complete.js +66 -0
  42. package/examples/memory/mx25l12845e/demo.js +66 -0
  43. package/examples/memory/mx25l12845e/minimal.js +27 -0
  44. package/examples/memory/sd_spi/complete.js +55 -0
  45. package/examples/memory/sd_spi/demo.js +67 -0
  46. package/examples/memory/sd_spi/minimal.js +32 -0
  47. package/examples/motor/drv8830/complete.js +50 -0
  48. package/examples/motor/drv8830/demo.js +57 -0
  49. package/examples/motor/drv8830/minimal.js +23 -0
  50. package/examples/pressure/bmp280/complete.js +1 -1
  51. package/examples/pressure/bmp280/demo.js +1 -1
  52. package/examples/pressure/bmp280/minimal.js +1 -1
  53. package/examples/pressure/bmp581/complete.js +1 -1
  54. package/examples/pressure/bmp581/demo.js +1 -1
  55. package/examples/pressure/bmp581/minimal.js +1 -1
  56. package/examples/pressure/lps22df/complete.js +1 -1
  57. package/examples/pressure/lps22df/demo.js +1 -1
  58. package/examples/pressure/lps22df/minimal.js +1 -1
  59. package/examples/rtc/ds3231/complete.js +77 -0
  60. package/examples/rtc/ds3231/demo.js +60 -0
  61. package/examples/rtc/ds3231/minimal.js +23 -0
  62. package/examples/rtc/pcf8523/complete.js +66 -0
  63. package/examples/rtc/pcf8523/demo.js +65 -0
  64. package/examples/rtc/pcf8523/minimal.js +20 -0
  65. package/examples/temperature/mcp9808/complete.js +89 -0
  66. package/examples/temperature/mcp9808/demo.js +62 -0
  67. package/examples/temperature/mcp9808/minimal.js +21 -0
  68. package/examples/temperature/tmp117/complete.js +90 -0
  69. package/examples/temperature/tmp117/demo.js +73 -0
  70. package/examples/temperature/tmp117/minimal.js +21 -0
  71. package/examples/tof/vl53l0x/complete.js +118 -0
  72. package/examples/tof/vl53l0x/demo.js +83 -0
  73. package/examples/tof/vl53l0x/minimal.js +25 -0
  74. package/examples/tof/vl53l1x/complete.js +151 -0
  75. package/examples/tof/vl53l1x/demo.js +100 -0
  76. package/examples/tof/vl53l1x/minimal.js +25 -0
  77. package/package.json +1 -1
  78. package/src/chips/accelerometer/adxl345.js +10 -31
  79. package/src/chips/accelerometer/adxl362.js +7 -7
  80. package/src/chips/accelerometer/bma150.js +419 -0
  81. package/src/chips/adc_dac/ad7705.js +36 -9
  82. package/src/chips/adc_dac/ad7706.js +39 -9
  83. package/src/chips/adc_dac/hy3131.js +311 -0
  84. package/src/chips/display/il0373.js +607 -0
  85. package/src/chips/display/ssd1331.js +412 -0
  86. package/src/chips/display/st7036.js +401 -0
  87. package/src/chips/display/uc1611s.js +648 -0
  88. package/src/chips/display/uc8159.js +394 -0
  89. package/src/chips/display/uc8276c.js +658 -0
  90. package/src/chips/environmental/bme280.js +31 -46
  91. package/src/chips/environmental/bme680.js +38 -43
  92. package/src/chips/gas/ens160.js +18 -26
  93. package/src/chips/gyroscope/l3g4200d.js +34 -50
  94. package/src/chips/gyroscope/l3gd20h.js +24 -40
  95. package/src/chips/imu/mpu6050.js +29 -41
  96. package/src/chips/imu/mpu9250.js +45 -69
  97. package/src/chips/imu/mpu9255.js +54 -78
  98. package/src/chips/io_expander/mcp23017.js +24 -33
  99. package/src/chips/light/apds-9930.js +52 -60
  100. package/src/chips/light/apds9960.js +69 -77
  101. package/src/chips/magnetometer/as5600.js +13 -27
  102. package/src/chips/magnetometer/hmc5883l.js +32 -29
  103. package/src/chips/memory/_23x1024.js +228 -0
  104. package/src/chips/memory/_24aa02uid.js +8 -11
  105. package/src/chips/memory/mx25l12845e.js +467 -0
  106. package/src/chips/memory/sd_spi.js +486 -0
  107. package/src/chips/motor/drv8830.js +239 -0
  108. package/src/chips/other/mpr121.js +7 -7
  109. package/src/chips/power/ina219.js +5 -8
  110. package/src/chips/power/ina226.js +5 -8
  111. package/src/chips/power/ina3221.js +5 -8
  112. package/src/chips/pressure/bmp085.js +17 -11
  113. package/src/chips/pressure/bmp180.js +7 -7
  114. package/src/chips/pressure/bmp280.js +21 -33
  115. package/src/chips/pressure/bmp384.js +28 -39
  116. package/src/chips/pressure/bmp581.js +59 -70
  117. package/src/chips/pressure/lps22df.js +50 -52
  118. package/src/chips/pressure/lps28dfw.js +15 -13
  119. package/src/chips/pressure/lps33hw.js +7 -5
  120. package/src/chips/rtc/ds3231.js +504 -0
  121. package/src/chips/rtc/pcf8523.js +533 -0
  122. package/src/chips/temperature/mcp9808.js +490 -0
  123. package/src/chips/temperature/tmp117.js +471 -0
  124. package/src/chips/tof/_vl53_base.js +160 -0
  125. package/src/chips/tof/vl53l0x.js +816 -0
  126. package/src/chips/tof/vl53l1x.js +816 -0
  127. package/src/connection/connection.js +6 -4
  128. package/src/connection/dhtxx.js +5 -3
  129. package/src/connection/display.js +278 -0
  130. package/src/connection/display_mock.js +77 -0
  131. package/src/connection/hx711.js +5 -3
  132. package/src/connection/i2c.js +6 -4
  133. package/src/connection/i2c_mock.js +47 -0
  134. package/src/connection/input_pin.js +36 -5
  135. package/src/connection/register.js +14 -0
  136. package/src/connection/register_connection.js +65 -0
  137. package/src/connection/sipo.js +4 -2
  138. package/src/connection/sipo_mock.js +49 -0
  139. package/src/connection/smbus.js +6 -4
  140. package/src/connection/softspi.js +73 -0
  141. package/src/connection/spi.js +110 -23
  142. package/src/connection/spi_mock.js +50 -0
  143. package/src/connection/uart.js +2 -1
  144. package/src/discovery/discovery.js +218 -0
  145. package/src/discovery/registry.js +85 -0
  146. package/src/storage/block_device.js +95 -0
  147. package/src/storage/ram_block_device.js +72 -0
  148. package/examples/motor/.gitkeep +0 -0
  149. package/examples/temperature/.gitkeep +0 -0
  150. package/examples/tof/.gitkeep +0 -0
  151. package/src/chips/motor/.gitkeep +0 -0
  152. package/src/chips/temperature/.gitkeep +0 -0
  153. package/src/chips/tof/.gitkeep +0 -0
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ // Long-range doorway people counter with a split ROI. The sensor hangs
4
+ // overhead in a doorway (up to 2.5 m). Two narrow 8x16 ROIs (centre SPADs 167
5
+ // and 231, the left/right half-array centres used by ST's own people-counting
6
+ // code) form two virtual beams. Each zone learns its floor distance, then
7
+ // counts as occupied when something is more than 300 mm closer; the order in
8
+ // which the zones become occupied tells IN from OUT. Every 30 s a
9
+ // signal/ambient snapshot is printed and strong sunlight switches to short
10
+ // distance mode. After 60 s or 50 events the full ROI is restored.
11
+
12
+ const { I2CConnection } = require('periph/src/connection/i2c');
13
+ const { VL53L1XFull } = require('periph/src/chips/tof/vl53l1x');
14
+
15
+ const ZONE_CENTRES = [167, 231]; // left, right
16
+ const OCCUPIED_MM = 300;
17
+ const MAX_EVENTS = 50;
18
+ const MAX_MS = 60000;
19
+ const SNAPSHOT_MS = 30000;
20
+ const BRIGHT_MCPS = 5.0;
21
+
22
+ (async () => {
23
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
24
+ const connection = new I2CConnection(bus, VL53L1XFull.I2C_ADDRESS);
25
+ const sensor = new VL53L1XFull(connection); // Create VL53L1X Full driver, (connection)
26
+ await sensor.init(); // Wait for init sequence, () → None
27
+
28
+ // --- Two virtual beams ---
29
+ // Long mode reaches the floor from a 2.5 m ceiling; a 33 ms budget keeps
30
+ // the two zones fast enough to catch a walking person. An 8x16 ROI covers
31
+ // one half of the SPAD array, so alternating the centre alternates beams.
32
+ await sensor.setDistanceMode('long'); // Set distance mode, (mode) → None
33
+ await sensor.setTimingBudget(33000); // Set timing budget, (budgetUs µs) → None
34
+ await sensor.setRoi(8, 16); // Set ROI size, (width SPADs, height SPADs) → None
35
+ console.log('optical centre SPAD', await sensor.opticalCenter(), '- zone centres', ZONE_CENTRES); // Read optical-centre SPAD, () → number
36
+
37
+ const measure = async (zone) => {
38
+ await sensor.setRoiCenter(ZONE_CENTRES[zone]); // Set ROI centre, (spad) → None
39
+ const d = await sensor.distance(); // Measure distance, () → number mm
40
+ return (await sensor.rangeValid()) ? d : null; // Check last measurement, () → boolean
41
+ };
42
+
43
+ // --- Learn the empty doorway ---
44
+ // Twenty readings per zone give the floor distance each beam sees when
45
+ // nobody is there; invalid readings are ignored.
46
+ const baseline = [];
47
+ for (const zone of [0, 1]) {
48
+ const values = [];
49
+ for (let i = 0; i < 20; i++) {
50
+ const v = await measure(zone);
51
+ if (v !== null) values.push(v);
52
+ }
53
+ baseline.push(values.length ? values.reduce((a, b) => a + b, 0) / values.length : 4000);
54
+ }
55
+ console.log(`baseline left ${baseline[0].toFixed(0)} mm, right ${baseline[1].toFixed(0)} mm`);
56
+
57
+ // --- Count crossings ---
58
+ // A person entering blocks the left beam first, then the right one (and
59
+ // the reverse when leaving). Once both beams clear, the recorded order
60
+ // decides the direction.
61
+ let countIn = 0;
62
+ let countOut = 0;
63
+ let events = 0;
64
+ let sequence = [];
65
+ const start = Date.now();
66
+ let lastSnapshot = start;
67
+ while (events < MAX_EVENTS && Date.now() - start < MAX_MS) {
68
+ const readings = [await measure(0), await measure(1)];
69
+ const occupied = readings.map((r, z) => r !== null && r < baseline[z] - OCCUPIED_MM);
70
+ for (const zone of [0, 1]) {
71
+ if (occupied[zone] && !sequence.includes(zone)) sequence.push(zone);
72
+ }
73
+ if (!occupied[0] && !occupied[1] && sequence.length) {
74
+ if (sequence[0] === 0 && sequence[1] === 1) countIn++;
75
+ else if (sequence[0] === 1 && sequence[1] === 0) countOut++;
76
+ events++;
77
+ console.log(`IN ${countIn} OUT ${countOut} (left ${readings[0]}, right ${readings[1]})`);
78
+ sequence = [];
79
+ }
80
+
81
+ // --- Watch the light ---
82
+ // Sunlight through an open door raises the ambient rate and eats
83
+ // long-mode range; short mode keeps working up to ~1.3 m.
84
+ if (Date.now() - lastSnapshot >= SNAPSHOT_MS) {
85
+ lastSnapshot = Date.now();
86
+ await sensor.distance(); // Measure distance, () → number mm
87
+ const m = await sensor.readMeasurement(); // Read result block, () → {distanceMm, …}
88
+ console.log(`signal ${m.signalRateMcps.toFixed(2)} MCPS, ambient ${m.ambientRateMcps.toFixed(2)} MCPS`);
89
+ if (m.ambientRateMcps > BRIGHT_MCPS && (await sensor.distanceMode()) === 'long') { // Read distance mode, () → string
90
+ await sensor.setDistanceMode('short'); // Set distance mode, (mode) → None
91
+ console.log('bright ambient light: switched to short distance mode');
92
+ }
93
+ }
94
+ }
95
+
96
+ // --- Restore the full field of view ---
97
+ await sensor.setRoi(16, 16); // Set ROI size, (width SPADs, height SPADs) → None
98
+ console.log(`done: IN ${countIn} OUT ${countOut}`);
99
+ await connection.close();
100
+ })();
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { VL53L1XMinimal } = require('periph/src/chips/tof/vl53l1x');
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, VL53L1XMinimal.I2C_ADDRESS);
11
+ const sensor = new VL53L1XMinimal(connection); // Create VL53L1X driver, (connection)
12
+ await sensor.init(); // Wait for init sequence, () → None
13
+
14
+ for (let i = 0; i < 50; i++) {
15
+ const d = await sensor.distance(); // Measure distance, () → number mm
16
+ if (await sensor.rangeValid()) { // Check last measurement, () → boolean
17
+ console.log(`${d} mm`);
18
+ } else {
19
+ console.log('out of range');
20
+ }
21
+ await sleep(200);
22
+ }
23
+
24
+ await connection.close();
25
+ })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "periph",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "JavaScript drivers for peripheral chips (I2C, SPI)",
5
5
  "main": "src/index.js",
6
6
  "keywords": [
@@ -53,7 +53,9 @@ function _delayMs(ms) {
53
53
  * ADXL345 3-axis MEMS accelerometer (Analog Devices) — minimal interface.
54
54
  *
55
55
  * Reads X, Y, Z acceleration in *g* with sensible defaults; no configuration
56
- * is required beyond the connection. Supports both I²C and SPI.
56
+ * is required beyond the connection. Supports both I²C and SPI via the shared
57
+ * RegisterConnection (for SPI, construct the connection with
58
+ * `readBit: 0x80, multiByteBit: 0x40` — the ADXL345 R/W|MB|A5..A0 command byte).
57
59
  *
58
60
  * Default configuration (written at construction):
59
61
  * - Full-resolution mode (3.9 mg/LSB at any range)
@@ -73,12 +75,10 @@ function _delayMs(ms) {
73
75
  */
74
76
  class ADXL345Minimal {
75
77
  /**
76
- * @param {import('../../connection/connection').Connection} connection - Configured I²C or SPI connection.
77
- * @param {string} [busType='i2c'] - Bus type: 'i2c' or 'spi'.
78
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - Configured I²C, SMBus, or SPI connection.
78
79
  */
79
- constructor(connection, busType = 'i2c') {
80
+ constructor(connection) {
80
81
  this._conn = connection;
81
- this._busType = busType;
82
82
  this._rangeBits = 0;
83
83
  this._fullRes = true;
84
84
  this._init();
@@ -96,36 +96,16 @@ class ADXL345Minimal {
96
96
  _delayMs(11);
97
97
  }
98
98
 
99
- _cmdByte(reg, read, multi) {
100
- let addr = reg & 0x3F;
101
- if (multi) addr |= 0x40;
102
- if (read) addr |= 0x80;
103
- return addr;
104
- }
105
-
106
99
  async _writeReg(reg, value) {
107
- if (this._busType === 'spi') {
108
- const cmd = this._cmdByte(reg, false, false);
109
- await this._conn.write(Buffer.from([cmd, value & 0xFF]));
110
- } else {
111
- await this._conn.write(Buffer.from([reg & 0xFF, value & 0xFF]));
112
- }
100
+ await this._conn.writeReg(reg, value & 0xFF);
113
101
  }
114
102
 
115
103
  async _readReg(reg) {
116
- if (this._busType === 'spi') {
117
- const cmd = this._cmdByte(reg, true, false);
118
- return (await this._conn.writeRead(Buffer.from([cmd]), 1))[0];
119
- }
120
- return (await this._conn.writeRead(Buffer.from([reg & 0xFF]), 1))[0];
104
+ return (await this._conn.readReg(reg, 1))[0];
121
105
  }
122
106
 
123
107
  async _readBurst(reg, n) {
124
- if (this._busType === 'spi') {
125
- const cmd = this._cmdByte(reg, true, n > 1);
126
- return this._conn.writeRead(Buffer.from([cmd]), n);
127
- }
128
- return this._conn.writeRead(Buffer.from([reg & 0xFF]), n);
108
+ return this._conn.readReg(reg, n);
129
109
  }
130
110
 
131
111
  /**
@@ -160,10 +140,9 @@ class ADXL345Minimal {
160
140
  class ADXL345Full extends ADXL345Minimal {
161
141
  /**
162
142
  * @param {import('../../connection/connection').Connection} connection - Configured I²C or SPI connection.
163
- * @param {string} [busType='i2c'] - Bus type: 'i2c' or 'spi'.
164
143
  */
165
- constructor(connection, busType = 'i2c') {
166
- super(connection, busType);
144
+ constructor(connection) {
145
+ super(connection);
167
146
  }
168
147
 
169
148
  /**
@@ -130,7 +130,7 @@ class ADXL362Minimal {
130
130
  *
131
131
  * @returns {Promise<void>}
132
132
  */
133
- async init() {
133
+ async _init() {
134
134
  await _delayMs(5); // power-up to standby turn-on time
135
135
  const ids = await this._readBurst(REG_DEVID_AD, 3);
136
136
  if (ids[0] !== DEVID_AD_VALUE) {
@@ -414,7 +414,7 @@ const _ADXL362FullMixin = (Base) => class extends Base {
414
414
  }
415
415
 
416
416
  /**
417
- * Set the activity threshold in *g* (clamped to 10-bit range).
417
+ * Set the activity threshold in *g* (clamped to 11-bit range).
418
418
  * @param {number} thresholdG
419
419
  * @param {boolean} [referenced=false]
420
420
  * @returns {Promise<void>}
@@ -422,9 +422,9 @@ const _ADXL362FullMixin = (Base) => class extends Base {
422
422
  async setActivityThreshold(thresholdG, referenced = false) {
423
423
  let raw = Math.round(thresholdG / this._sensitivity());
424
424
  if (raw < 0) raw = 0;
425
- if (raw > 0x3FF) raw = 0x3FF;
425
+ if (raw > 0x7FF) raw = 0x7FF;
426
426
  await this._writeReg(REG_THRESH_ACT_L, raw & 0xFF);
427
- await this._writeReg(REG_THRESH_ACT_H, (raw >> 8) & 0x03);
427
+ await this._writeReg(REG_THRESH_ACT_H, (raw >> 8) & 0x07);
428
428
  const aic = await this._readReg(REG_ACT_INACT_CTL);
429
429
  await this._writeReg(REG_ACT_INACT_CTL, referenced ? (aic | 0x02) : (aic & ~0x02));
430
430
  }
@@ -440,7 +440,7 @@ const _ADXL362FullMixin = (Base) => class extends Base {
440
440
  }
441
441
 
442
442
  /**
443
- * Set the inactivity threshold in *g* (clamped to 10-bit range).
443
+ * Set the inactivity threshold in *g* (clamped to 11-bit range).
444
444
  * @param {number} thresholdG
445
445
  * @param {boolean} [referenced=false]
446
446
  * @returns {Promise<void>}
@@ -448,9 +448,9 @@ const _ADXL362FullMixin = (Base) => class extends Base {
448
448
  async setInactivityThreshold(thresholdG, referenced = false) {
449
449
  let raw = Math.round(thresholdG / this._sensitivity());
450
450
  if (raw < 0) raw = 0;
451
- if (raw > 0x3FF) raw = 0x3FF;
451
+ if (raw > 0x7FF) raw = 0x7FF;
452
452
  await this._writeReg(REG_THRESH_INACT_L, raw & 0xFF);
453
- await this._writeReg(REG_THRESH_INACT_H, (raw >> 8) & 0x03);
453
+ await this._writeReg(REG_THRESH_INACT_H, (raw >> 8) & 0x07);
454
454
  const aic = await this._readReg(REG_ACT_INACT_CTL);
455
455
  await this._writeReg(REG_ACT_INACT_CTL, referenced ? (aic | 0x08) : (aic & ~0x08));
456
456
  }
@@ -0,0 +1,419 @@
1
+ 'use strict';
2
+
3
+ const _REG_CHIP_ID = 0x00;
4
+ const _REG_VERSION = 0x01;
5
+ const _REG_ACC_X_LSB = 0x02;
6
+ const _REG_ACC_X_MSB = 0x03;
7
+ const _REG_ACC_Y_LSB = 0x04;
8
+ const _REG_ACC_Y_MSB = 0x05;
9
+ const _REG_ACC_Z_LSB = 0x06;
10
+ const _REG_ACC_Z_MSB = 0x07;
11
+ const _REG_TEMP = 0x08;
12
+ const _REG_STATUS = 0x09;
13
+ const _REG_CTRL = 0x0A;
14
+ const _REG_INT_CTRL = 0x0B;
15
+ const _REG_LG_THRES = 0x0C;
16
+ const _REG_LG_DUR = 0x0D;
17
+ const _REG_HG_THRES = 0x0E;
18
+ const _REG_HG_DUR = 0x0F;
19
+ const _REG_ANY_MOTION_THRES = 0x10;
20
+ const _REG_HYST_DUR = 0x11;
21
+ const _REG_CUSTOMER_1 = 0x12;
22
+ const _REG_CUSTOMER_2 = 0x13;
23
+ const _REG_RANGE_BW = 0x14;
24
+ const _REG_CONFIG = 0x15;
25
+
26
+ const _CHIP_ID_VALUE = 0x02;
27
+ const _CHIP_ID_MASK = 0x07;
28
+
29
+ const _RANGE_BITS = { 2: 0x00, 4: 0x08, 8: 0x10 };
30
+ const _BW_CODES = [25, 50, 100, 190, 375, 750, 1500].map((hz, i) => [hz, i]);
31
+ const _RANGE_SCALE = { 2: 256, 4: 128, 8: 64 };
32
+
33
+ const _WAKEUP_PAUSE_CODES = { 20: 0x00, 80: 0x02, 320: 0x04, 2560: 0x06 };
34
+ const _ANY_MOTION_DUR_CODES = { 1: 0x00, 3: 0x40, 5: 0x80, 7: 0xC0 };
35
+
36
+ function _nearestBandwidth(bwHz) {
37
+ let best = _BW_CODES[0];
38
+ let bestDiff = Math.abs(_BW_CODES[0][0] - bwHz);
39
+ for (const entry of _BW_CODES) {
40
+ const diff = Math.abs(entry[0] - bwHz);
41
+ if (diff < bestDiff) {
42
+ best = entry;
43
+ bestDiff = diff;
44
+ }
45
+ }
46
+ return best[1];
47
+ }
48
+
49
+ function _delayMs(ms) {
50
+ const end = Date.now() + ms;
51
+ while (Date.now() < end) { /* spin */ }
52
+ }
53
+
54
+ /**
55
+ * BMA150 3-axis MEMS accelerometer (Bosch Sensortec) — minimal interface.
56
+ *
57
+ * Triaxial low-g accelerometer with 10-bit digital output and ±2/±4/±8 *g*
58
+ * selectable full-scale range. Communicates over I²C at the fixed address
59
+ * 0x38 (the chip also supports 3-/4-wire SPI; out of scope here).
60
+ *
61
+ * Default configuration (written at construction):
62
+ * - Range ±2 *g* (256 LSB/g)
63
+ * - Bandwidth 100 Hz
64
+ * - Calibration bits 7:5 of `RANGE_BW` (0x14) preserved
65
+ * - `shadow_dis` = 0 (LSB-then-MSB ordering enforced)
66
+ *
67
+ * Constructor caveat: JS constructors cannot be async, but the original
68
+ * synchronous constructor validated CHIP_ID and threw synchronously on
69
+ * mismatch — that guarantee cannot be preserved exactly. The whole init
70
+ * sequence is fired off unawaited; a CHIP_ID mismatch now surfaces as an
71
+ * *unhandled promise rejection* shortly after construction rather than a
72
+ * synchronous throw from `new BMA150Minimal(...)`. Callers that need to
73
+ * detect "wrong or absent device" deterministically should call an async
74
+ * method (e.g. `await accel.read()`) right after construction and handle
75
+ * its rejection.
76
+ */
77
+ class BMA150Minimal {
78
+ /**
79
+ * @param {import('../../connection/register_connection').RegisterConnection} connection - Configured I²C connection.
80
+ */
81
+ constructor(connection) {
82
+ this._conn = connection;
83
+ this._rangeG = 2;
84
+ this._init();
85
+ }
86
+
87
+ async _init() {
88
+ const chipId = await this._readReg(_REG_CHIP_ID);
89
+ if ((chipId & _CHIP_ID_MASK) !== _CHIP_ID_VALUE) {
90
+ throw new Error('BMA150 CHIP_ID: expected 0x' + _CHIP_ID_VALUE.toString(16) +
91
+ ', got 0x' + (chipId & _CHIP_ID_MASK).toString(16));
92
+ }
93
+ const bwCode = _nearestBandwidth(100);
94
+ const rb = await this._readReg(_REG_RANGE_BW);
95
+ const out = (rb & 0xE0) | _RANGE_BITS[2] | bwCode;
96
+ await this._writeReg(_REG_RANGE_BW, out);
97
+ _delayMs(5);
98
+ }
99
+
100
+ async _writeReg(reg, value) {
101
+ await this._conn.writeReg(reg, value & 0xFF);
102
+ }
103
+
104
+ async _readReg(reg) {
105
+ return (await this._conn.readReg(reg, 1))[0];
106
+ }
107
+
108
+ /**
109
+ * Read 3-axis linear acceleration.
110
+ *
111
+ * Reads all six LSB-then-MSB data bytes (0x02..0x07) in one burst so the
112
+ * X, Y, Z samples are guaranteed to come from a single measurement with
113
+ * `shadow_dis=0` enforcing correct ordering.
114
+ *
115
+ * @returns {Promise<number[]>} [x, y, z] acceleration in *g*.
116
+ */
117
+ async read() {
118
+ const raw = await this._conn.readReg(_REG_ACC_X_LSB, 6);
119
+ const rx = ((((raw[1] << 2) | (raw[0] >> 6)) & 0x3FF) + 512) % 1024 - 512;
120
+ const ry = ((((raw[3] << 2) | (raw[2] >> 6)) & 0x3FF) + 512) % 1024 - 512;
121
+ const rz = ((((raw[5] << 2) | (raw[4] >> 6)) & 0x3FF) + 512) % 1024 - 512;
122
+ const scale = _RANGE_SCALE[this._rangeG];
123
+ return [rx / scale, ry / scale, rz / scale];
124
+ }
125
+ }
126
+
127
+ /**
128
+ * BMA150 full interface — extends BMA150Minimal with configuration,
129
+ * interrupt sources, low-g / high-g / any-motion / alert logic, sleep,
130
+ * soft reset, and self-test.
131
+ *
132
+ * Adds range (±2/±4/±8 *g*) and bandwidth (25..1500 Hz) selection, raw
133
+ * reading, temperature, low-g (free-fall), high-g (shock), any-motion and
134
+ * alert thresholds with duration, hysteresis and debounce counters,
135
+ * latched or self-resetting interrupts, self-wake-up mode, sleep and soft
136
+ * reset, electrostatic self-test, version register, and the two CUSTOMER
137
+ * scratch bytes.
138
+ */
139
+ class BMA150Full extends BMA150Minimal {
140
+ /**
141
+ * @param {import('../../connection/connection').Connection} connection - Configured I²C connection.
142
+ */
143
+ constructor(connection) {
144
+ super(connection);
145
+ this._enabledSources = 0;
146
+ this._sleeping = false;
147
+ }
148
+
149
+ /**
150
+ * Read 3-axis linear acceleration in *g*.
151
+ *
152
+ * Delegates to {@link BMA150Minimal#read}.
153
+ * @returns {Promise<number[]>}
154
+ */
155
+ async read() {
156
+ return super.read();
157
+ }
158
+
159
+ /** @param {number} rangeG - One of 2, 4, 8. */
160
+ async setRange(rangeG) {
161
+ if (!(rangeG in _RANGE_BITS)) {
162
+ throw new Error('rangeG must be one of 2, 4, 8');
163
+ }
164
+ this._rangeG = rangeG;
165
+ const rb = await this._readReg(_REG_RANGE_BW);
166
+ const out = (rb & 0xE0) | _RANGE_BITS[rangeG] | (rb & 0x07);
167
+ await this._writeReg(_REG_RANGE_BW, out);
168
+ }
169
+
170
+ /** @param {number} bandwidthHz - 25..1500 Hz. */
171
+ async setBandwidth(bandwidthHz) {
172
+ const bwCode = _nearestBandwidth(bandwidthHz);
173
+ const rb = await this._readReg(_REG_RANGE_BW);
174
+ const out = (rb & 0xF8) | bwCode;
175
+ await this._writeReg(_REG_RANGE_BW, out);
176
+ }
177
+
178
+ /** @returns {Promise<number[]>} Signed 10-bit counts. */
179
+ async readRaw() {
180
+ const raw = await this._conn.readReg(_REG_ACC_X_LSB, 6);
181
+ const rx = ((((raw[1] << 2) | (raw[0] >> 6)) & 0x3FF) + 512) % 1024 - 512;
182
+ const ry = ((((raw[3] << 2) | (raw[2] >> 6)) & 0x3FF) + 512) % 1024 - 512;
183
+ const rz = ((((raw[5] << 2) | (raw[4] >> 6)) & 0x3FF) + 512) % 1024 - 512;
184
+ return [rx, ry, rz];
185
+ }
186
+
187
+ /** @returns {Promise<number>} Temperature in °C. */
188
+ async readTemperature() {
189
+ const raw = await this._readReg(_REG_TEMP);
190
+ return raw * 0.5 - 30.0;
191
+ }
192
+
193
+ /** @returns {Promise<boolean>} True if all three new_data_X/Y/Z bits are set. */
194
+ async newDataAvailable() {
195
+ const x = await this._readReg(_REG_ACC_X_LSB);
196
+ const y = await this._readReg(_REG_ACC_Y_LSB);
197
+ const z = await this._readReg(_REG_ACC_Z_LSB);
198
+ return (x & 0x01) && (y & 0x01) && (z & 0x01);
199
+ }
200
+
201
+ /** @param {boolean} enabled - True to allow MSB-only reads. */
202
+ async setShadow(enabled) {
203
+ const cfg = await this._readReg(_REG_CONFIG);
204
+ const out = enabled ? (cfg | 0x08) : (cfg & ~0x08 & 0xFF);
205
+ await this._writeReg(_REG_CONFIG, out);
206
+ }
207
+
208
+ async setLowG(thresholdG, durationMs, hysteresisG = 0, counter = 0) {
209
+ await this._writeThreshold(_REG_LG_THRES, thresholdG);
210
+ await this._writeReg(_REG_LG_DUR, Math.max(0, Math.min(255, Math.round(durationMs))) & 0xFF);
211
+ await this._writeHyst('lg', hysteresisG);
212
+ await this._writeIntCounter('lg', counter);
213
+ await this._enableSource(BMA150Full.SOURCE_LOW_G);
214
+ }
215
+
216
+ async setHighG(thresholdG, durationMs, hysteresisG = 0, counter = 0) {
217
+ await this._writeThreshold(_REG_HG_THRES, thresholdG);
218
+ await this._writeReg(_REG_HG_DUR, Math.max(0, Math.min(255, Math.round(durationMs))) & 0xFF);
219
+ await this._writeHyst('hg', hysteresisG);
220
+ await this._writeIntCounter('hg', counter);
221
+ await this._enableSource(BMA150Full.SOURCE_HIGH_G);
222
+ }
223
+
224
+ async setAnyMotion(thresholdG, samples = 1) {
225
+ const scale = _RANGE_SCALE[this._rangeG] / 256.0;
226
+ const code = Math.max(0, Math.min(255, Math.round(thresholdG / (0.0156 * scale))));
227
+ await this._writeReg(_REG_ANY_MOTION_THRES, code);
228
+ if (!(samples in _ANY_MOTION_DUR_CODES)) {
229
+ throw new Error('samples must be 1, 3, 5, or 7');
230
+ }
231
+ const hd = await this._readReg(_REG_HYST_DUR);
232
+ await this._writeReg(_REG_HYST_DUR, (hd & 0x3F) | _ANY_MOTION_DUR_CODES[samples]);
233
+ const cfg = await this._readReg(_REG_CONFIG);
234
+ await this._writeReg(_REG_CONFIG, cfg | 0x40);
235
+ await this._enableSource(BMA150Full.SOURCE_ANY_MOTION);
236
+ }
237
+
238
+ async setAlert(enabled) {
239
+ if (enabled) {
240
+ this._enabledSources &= ~BMA150Full.SOURCE_ANY_MOTION;
241
+ const cfg = await this._readReg(_REG_CONFIG);
242
+ await this._writeReg(_REG_CONFIG, cfg | 0x40);
243
+ await this._enableSource(BMA150Full.SOURCE_ALERT);
244
+ } else {
245
+ await this._disableSource(BMA150Full.SOURCE_ALERT);
246
+ }
247
+ }
248
+
249
+ async setLatch(enabled) {
250
+ const cfg = await this._readReg(_REG_CONFIG);
251
+ const out = enabled ? (cfg | 0x10) : (cfg & ~0x10 & 0xFF);
252
+ await this._writeReg(_REG_CONFIG, out);
253
+ }
254
+
255
+ async clearInterrupt() {
256
+ if (this._sleeping) return;
257
+ const ctrl = await this._readReg(_REG_CTRL);
258
+ await this._writeReg(_REG_CTRL, ctrl | 0x40);
259
+ }
260
+
261
+ async enableInterrupt(source) {
262
+ if (source === BMA150Full.SOURCE_NEW_DATA) {
263
+ this._enabledSources &= 0x0F;
264
+ } else {
265
+ this._enabledSources &= ~BMA150Full.SOURCE_NEW_DATA;
266
+ if (source === BMA150Full.SOURCE_ANY_MOTION) {
267
+ this._enabledSources &= ~BMA150Full.SOURCE_ALERT;
268
+ } else if (source === BMA150Full.SOURCE_ALERT) {
269
+ this._enabledSources &= ~BMA150Full.SOURCE_ANY_MOTION;
270
+ }
271
+ }
272
+ await this._enableSource(source);
273
+ }
274
+
275
+ async disableInterrupt(source) {
276
+ await this._disableSource(source);
277
+ }
278
+
279
+ /** @returns {Promise<number>} STATUS byte. */
280
+ async pollInterrupt() {
281
+ return this._readReg(_REG_STATUS);
282
+ }
283
+
284
+ async setWakeUp(enabled, pauseMs = 20) {
285
+ if (!(pauseMs in _WAKEUP_PAUSE_CODES)) {
286
+ throw new Error('pauseMs must be 20, 80, 320, or 2560');
287
+ }
288
+ const cfg = await this._readReg(_REG_CONFIG);
289
+ const out = (cfg & 0xF8) | _WAKEUP_PAUSE_CODES[pauseMs] | (enabled ? 0x01 : 0x00);
290
+ await this._writeReg(_REG_CONFIG, out);
291
+ }
292
+
293
+ async sleep() {
294
+ if (this._sleeping) return;
295
+ const ctrl = await this._readReg(_REG_CTRL);
296
+ await this._writeReg(_REG_CTRL, ctrl | 0x01);
297
+ this._sleeping = true;
298
+ }
299
+
300
+ async wake() {
301
+ if (!this._sleeping) return;
302
+ const ctrl = await this._readReg(_REG_CTRL);
303
+ await this._writeReg(_REG_CTRL, ctrl & ~0x01 & 0xFF);
304
+ _delayMs(2);
305
+ this._sleeping = false;
306
+ }
307
+
308
+ async softReset() {
309
+ const ctrl = await this._readReg(_REG_CTRL);
310
+ await this._writeReg(_REG_CTRL, ctrl | 0x02);
311
+ _delayMs(30);
312
+ const bwCode = _nearestBandwidth(100);
313
+ const rb = await this._readReg(_REG_RANGE_BW);
314
+ await this._writeReg(_REG_RANGE_BW, (rb & 0xE0) | _RANGE_BITS[this._rangeG] | bwCode);
315
+ this._sleeping = false;
316
+ }
317
+
318
+ /** @returns {Promise<boolean>} True if self-test passed. */
319
+ async selfTest() {
320
+ const ctrl = await this._readReg(_REG_CTRL);
321
+ await this._writeReg(_REG_CTRL, ctrl | 0x04);
322
+ _delayMs(100);
323
+ const status = await this._readReg(_REG_STATUS);
324
+ await this._writeReg(_REG_CTRL, ctrl);
325
+ return (status & 0x80) !== 0;
326
+ }
327
+
328
+ /** @returns {Promise<number>} STATUS byte. */
329
+ async readStatus() {
330
+ return this._readReg(_REG_STATUS);
331
+ }
332
+
333
+ /** @returns {Promise<[number, number]>} (al_version, ml_version) from VERSION. */
334
+ async readVersion() {
335
+ const raw = await this._readReg(_REG_VERSION);
336
+ return [(raw >> 4) & 0x0F, raw & 0x0F];
337
+ }
338
+
339
+ /** @param {number} index - 0 or 1. */
340
+ async readCustomer(index) {
341
+ const reg = index === 0 ? _REG_CUSTOMER_1 : _REG_CUSTOMER_2;
342
+ return this._readReg(reg);
343
+ }
344
+
345
+ async writeCustomer(index, value) {
346
+ const reg = index === 0 ? _REG_CUSTOMER_1 : _REG_CUSTOMER_2;
347
+ await this._writeReg(reg, value & 0xFF);
348
+ }
349
+
350
+ async _writeThreshold(reg, thresholdG) {
351
+ let code = Math.round(thresholdG * 255.0 / this._rangeG);
352
+ if (code < 0) code = 0;
353
+ if (code > 255) code = 255;
354
+ await this._writeReg(reg, code);
355
+ }
356
+
357
+ async _writeHyst(kind, hysteresisG) {
358
+ if (hysteresisG < 0) return;
359
+ let code = Math.round(hysteresisG * 255.0 / this._rangeG / 32.0);
360
+ if (code < 0) code = 0;
361
+ if (code > 7) code = 7;
362
+ const hd = await this._readReg(_REG_HYST_DUR);
363
+ const out = kind === 'lg'
364
+ ? (hd & 0xF8) | code
365
+ : (hd & 0xC7) | ((code & 0x07) << 3);
366
+ await this._writeReg(_REG_HYST_DUR, out);
367
+ }
368
+
369
+ async _writeIntCounter(kind, counter) {
370
+ if (counter < 0 || counter > 3) return;
371
+ const code = (counter & 0x03) << 2; // LG bits 3:2; HG shifts 2 more (bits 5:4)
372
+ const ic = await this._readReg(_REG_INT_CTRL);
373
+ const out = kind === 'lg'
374
+ ? (ic & 0xF3) | code
375
+ : (ic & 0xCF) | (code << 2);
376
+ await this._writeReg(_REG_INT_CTRL, out);
377
+ }
378
+
379
+ async _enableSource(source) {
380
+ if (this._sleeping) return;
381
+ this._enabledSources |= source;
382
+ if (source === BMA150Full.SOURCE_NEW_DATA) {
383
+ const cfg = await this._readReg(_REG_CONFIG);
384
+ await this._writeReg(_REG_CONFIG, cfg | 0x20);
385
+ return;
386
+ }
387
+ const ic = await this._readReg(_REG_INT_CTRL);
388
+ let out = ic;
389
+ if (source === BMA150Full.SOURCE_LOW_G) out |= 0x01;
390
+ if (source === BMA150Full.SOURCE_HIGH_G) out |= 0x02;
391
+ if (source === BMA150Full.SOURCE_ANY_MOTION) out |= 0x40;
392
+ if (source === BMA150Full.SOURCE_ALERT) out |= 0x80;
393
+ await this._writeReg(_REG_INT_CTRL, out);
394
+ }
395
+
396
+ async _disableSource(source) {
397
+ this._enabledSources &= ~source & 0xFF;
398
+ if (source === BMA150Full.SOURCE_NEW_DATA) {
399
+ const cfg = await this._readReg(_REG_CONFIG);
400
+ await this._writeReg(_REG_CONFIG, cfg & ~0x20 & 0xFF);
401
+ return;
402
+ }
403
+ const ic = await this._readReg(_REG_INT_CTRL);
404
+ let out = ic;
405
+ if (source === BMA150Full.SOURCE_LOW_G) out &= ~0x01 & 0xFF;
406
+ if (source === BMA150Full.SOURCE_HIGH_G) out &= ~0x02 & 0xFF;
407
+ if (source === BMA150Full.SOURCE_ANY_MOTION) out &= ~0x40 & 0xFF;
408
+ if (source === BMA150Full.SOURCE_ALERT) out &= ~0x80 & 0xFF;
409
+ await this._writeReg(_REG_INT_CTRL, out);
410
+ }
411
+ }
412
+
413
+ BMA150Full.SOURCE_LOW_G = 0x01;
414
+ BMA150Full.SOURCE_HIGH_G = 0x02;
415
+ BMA150Full.SOURCE_ANY_MOTION = 0x04;
416
+ BMA150Full.SOURCE_ALERT = 0x08;
417
+ BMA150Full.SOURCE_NEW_DATA = 0x10;
418
+
419
+ module.exports = { BMA150Minimal, BMA150Full };