periph 1.1.0 → 1.2.1

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 (266) hide show
  1. package/README.md +61 -12
  2. package/examples/accelerometer/adxl345/complete.js +52 -0
  3. package/examples/accelerometer/adxl345/demo.js +34 -0
  4. package/examples/accelerometer/adxl345/minimal.js +18 -0
  5. package/examples/accelerometer/adxl362/complete.js +57 -0
  6. package/examples/accelerometer/adxl362/demo.js +51 -0
  7. package/examples/accelerometer/adxl362/minimal.js +21 -0
  8. package/examples/adc_dac/ad7705/complete.js +32 -0
  9. package/examples/adc_dac/ad7705/demo.js +42 -0
  10. package/examples/adc_dac/ad7705/minimal.js +16 -0
  11. package/examples/adc_dac/ad7706/complete.js +35 -0
  12. package/examples/adc_dac/ad7706/demo.js +44 -0
  13. package/examples/adc_dac/ad7706/minimal.js +16 -0
  14. package/examples/adc_dac/hx710a/complete.js +45 -0
  15. package/examples/adc_dac/hx710a/demo.js +52 -0
  16. package/examples/adc_dac/hx710a/minimal.js +16 -0
  17. package/examples/adc_dac/hx710b/complete.js +45 -0
  18. package/examples/adc_dac/hx710b/demo.js +64 -0
  19. package/examples/adc_dac/hx710b/minimal.js +16 -0
  20. package/examples/adc_dac/hx711/complete.js +7 -7
  21. package/examples/adc_dac/hx711/demo.js +6 -6
  22. package/examples/adc_dac/hx711/minimal.js +7 -7
  23. package/examples/adc_dac/mcp4725/complete.js +19 -17
  24. package/examples/adc_dac/mcp4725/demo.js +5 -5
  25. package/examples/adc_dac/mcp4725/minimal.js +8 -6
  26. package/examples/adc_dac/mcp4728/complete.js +24 -22
  27. package/examples/adc_dac/mcp4728/demo.js +22 -22
  28. package/examples/adc_dac/mcp4728/minimal.js +8 -6
  29. package/examples/adc_dac/pcf8591/complete.js +41 -0
  30. package/examples/adc_dac/pcf8591/demo.js +39 -0
  31. package/examples/adc_dac/pcf8591/minimal.js +19 -0
  32. package/examples/comms/mcp2515/complete.js +75 -0
  33. package/examples/comms/mcp2515/demo.js +66 -0
  34. package/examples/comms/mcp2515/minimal.js +27 -0
  35. package/examples/comms/rda5807m/complete.js +55 -0
  36. package/examples/comms/rda5807m/demo.js +68 -0
  37. package/examples/comms/rda5807m/minimal.js +15 -0
  38. package/examples/comms/rfm9x/complete.js +50 -0
  39. package/examples/comms/rfm9x/demo.js +55 -0
  40. package/examples/comms/rfm9x/minimal.js +20 -0
  41. package/examples/display/pcf8576/complete.js +18 -15
  42. package/examples/display/pcf8576/demo.js +6 -6
  43. package/examples/display/pcf8576/minimal.js +12 -10
  44. package/examples/environmental/aht21/complete.js +15 -13
  45. package/examples/environmental/aht21/demo.js +8 -6
  46. package/examples/environmental/aht21/minimal.js +5 -5
  47. package/examples/environmental/bme280/complete.js +23 -20
  48. package/examples/environmental/bme280/demo.js +14 -14
  49. package/examples/environmental/bme280/minimal.js +13 -11
  50. package/examples/environmental/bme680/complete.js +25 -22
  51. package/examples/environmental/bme680/demo.js +38 -36
  52. package/examples/environmental/bme680/minimal.js +14 -12
  53. package/examples/gas/ens160/complete.js +29 -27
  54. package/examples/gas/ens160/demo.js +39 -37
  55. package/examples/gas/ens160/minimal.js +17 -15
  56. package/examples/gnss/neo6/complete.js +49 -0
  57. package/examples/gnss/neo6/demo.js +54 -0
  58. package/examples/gnss/neo6/minimal.js +30 -0
  59. package/examples/gyroscope/l3g4200d/complete.js +56 -0
  60. package/examples/gyroscope/l3g4200d/demo.js +49 -0
  61. package/examples/gyroscope/l3g4200d/minimal.js +19 -0
  62. package/examples/gyroscope/l3gd20h/complete.js +42 -0
  63. package/examples/gyroscope/l3gd20h/demo.js +29 -0
  64. package/examples/gyroscope/l3gd20h/minimal.js +13 -0
  65. package/examples/humidity/dht11/complete.js +22 -0
  66. package/examples/humidity/dht11/demo.js +38 -0
  67. package/examples/humidity/dht11/minimal.js +18 -0
  68. package/examples/imu/mpu6050/complete.js +27 -25
  69. package/examples/imu/mpu6050/demo.js +29 -26
  70. package/examples/imu/mpu6050/minimal.js +6 -6
  71. package/examples/imu/mpu9250/complete.js +65 -0
  72. package/examples/imu/mpu9250/demo.js +53 -0
  73. package/examples/imu/mpu9250/minimal.js +21 -0
  74. package/examples/imu/mpu9255/complete.js +73 -0
  75. package/examples/imu/mpu9255/demo.js +73 -0
  76. package/examples/imu/mpu9255/minimal.js +21 -0
  77. package/examples/io_expander/mcp23017/complete.js +70 -77
  78. package/examples/io_expander/mcp23017/demo.js +37 -33
  79. package/examples/io_expander/mcp23017/minimal.js +15 -11
  80. package/examples/io_expander/pcf8574/complete.js +60 -65
  81. package/examples/io_expander/pcf8574/demo.js +30 -25
  82. package/examples/io_expander/pcf8574/minimal.js +15 -11
  83. package/examples/io_expander/pcf8575/complete.js +24 -20
  84. package/examples/io_expander/pcf8575/demo.js +27 -23
  85. package/examples/io_expander/pcf8575/minimal.js +16 -12
  86. package/examples/io_expander/tpic6b595/complete.js +57 -0
  87. package/examples/io_expander/tpic6b595/demo.js +75 -0
  88. package/examples/io_expander/tpic6b595/minimal.js +26 -0
  89. package/examples/led/apa102/complete.js +72 -0
  90. package/examples/led/apa102/demo.js +92 -0
  91. package/examples/led/apa102/minimal.js +21 -0
  92. package/examples/led/sk6812rgbw/complete.js +42 -40
  93. package/examples/led/sk6812rgbw/demo.js +16 -16
  94. package/examples/led/sk6812rgbw/minimal.js +15 -17
  95. package/examples/led/ws2812b/complete.js +40 -38
  96. package/examples/led/ws2812b/demo.js +16 -16
  97. package/examples/led/ws2812b/minimal.js +13 -14
  98. package/examples/led/ws2814/complete.js +71 -0
  99. package/examples/led/ws2814/demo.js +82 -0
  100. package/examples/led/ws2814/minimal.js +23 -0
  101. package/examples/light/apds-9930/complete.js +46 -0
  102. package/examples/light/apds-9930/demo.js +31 -0
  103. package/examples/light/apds-9930/minimal.js +20 -0
  104. package/examples/light/apds9960/complete.js +45 -43
  105. package/examples/light/apds9960/demo.js +11 -9
  106. package/examples/light/apds9960/minimal.js +5 -5
  107. package/examples/magnetometer/as5600/complete.js +31 -29
  108. package/examples/magnetometer/as5600/demo.js +35 -33
  109. package/examples/magnetometer/as5600/minimal.js +7 -7
  110. package/examples/magnetometer/hmc5883l/complete.js +47 -0
  111. package/examples/magnetometer/hmc5883l/demo.js +50 -0
  112. package/examples/magnetometer/hmc5883l/minimal.js +15 -0
  113. package/examples/memory/24aa02uid/complete.js +23 -21
  114. package/examples/memory/24aa02uid/demo.js +32 -30
  115. package/examples/memory/24aa02uid/minimal.js +5 -5
  116. package/examples/motor/drv8830/complete.js +50 -0
  117. package/examples/motor/drv8830/demo.js +57 -0
  118. package/examples/motor/drv8830/minimal.js +23 -0
  119. package/examples/other/mpr121/complete.js +50 -0
  120. package/examples/other/mpr121/demo.js +30 -0
  121. package/examples/other/mpr121/minimal.js +17 -0
  122. package/examples/power/ade7953/complete.js +44 -0
  123. package/examples/power/ade7953/demo.js +28 -0
  124. package/examples/power/ade7953/minimal.js +15 -0
  125. package/examples/power/ina219/complete.js +20 -18
  126. package/examples/power/ina219/demo.js +15 -13
  127. package/examples/power/ina219/minimal.js +8 -8
  128. package/examples/power/ina226/complete.js +24 -22
  129. package/examples/power/ina226/demo.js +22 -20
  130. package/examples/power/ina226/minimal.js +5 -5
  131. package/examples/power/ina3221/complete.js +51 -49
  132. package/examples/power/ina3221/demo.js +13 -13
  133. package/examples/power/ina3221/minimal.js +8 -8
  134. package/examples/pressure/bmp085/complete.js +29 -0
  135. package/examples/pressure/bmp085/demo.js +34 -0
  136. package/examples/pressure/bmp085/minimal.js +19 -0
  137. package/examples/pressure/bmp180/complete.js +20 -17
  138. package/examples/pressure/bmp180/demo.js +24 -22
  139. package/examples/pressure/bmp180/minimal.js +13 -11
  140. package/examples/pressure/bmp280/complete.js +23 -20
  141. package/examples/pressure/bmp280/demo.js +44 -41
  142. package/examples/pressure/bmp280/minimal.js +13 -11
  143. package/examples/pressure/bmp384/complete.js +29 -0
  144. package/examples/pressure/bmp384/demo.js +40 -0
  145. package/examples/pressure/bmp384/minimal.js +18 -0
  146. package/examples/pressure/bmp581/complete.js +34 -0
  147. package/examples/pressure/bmp581/demo.js +56 -0
  148. package/examples/pressure/bmp581/minimal.js +19 -0
  149. package/examples/pressure/lps22df/complete.js +50 -0
  150. package/examples/pressure/lps22df/demo.js +41 -0
  151. package/examples/pressure/lps22df/minimal.js +19 -0
  152. package/examples/pressure/lps28dfw/complete.js +37 -0
  153. package/examples/pressure/lps28dfw/demo.js +33 -0
  154. package/examples/pressure/lps28dfw/minimal.js +19 -0
  155. package/examples/pressure/lps33hw/complete.js +43 -0
  156. package/examples/pressure/lps33hw/demo.js +43 -0
  157. package/examples/pressure/lps33hw/minimal.js +19 -0
  158. package/examples/rfid/mfrc522/complete.js +44 -0
  159. package/examples/rfid/mfrc522/demo.js +70 -0
  160. package/examples/rfid/mfrc522/minimal.js +17 -0
  161. package/examples/rtc/ds3231/complete.js +77 -0
  162. package/examples/rtc/ds3231/demo.js +60 -0
  163. package/examples/rtc/ds3231/minimal.js +23 -0
  164. package/examples/rtc/pcf8523/complete.js +66 -0
  165. package/examples/rtc/pcf8523/demo.js +65 -0
  166. package/examples/rtc/pcf8523/minimal.js +20 -0
  167. package/examples/temperature/mcp9808/complete.js +89 -0
  168. package/examples/temperature/mcp9808/demo.js +62 -0
  169. package/examples/temperature/mcp9808/minimal.js +21 -0
  170. package/examples/temperature/tmp117/complete.js +90 -0
  171. package/examples/temperature/tmp117/demo.js +73 -0
  172. package/examples/temperature/tmp117/minimal.js +21 -0
  173. package/examples/tof/vl53l0x/complete.js +118 -0
  174. package/examples/tof/vl53l0x/demo.js +83 -0
  175. package/examples/tof/vl53l0x/minimal.js +25 -0
  176. package/examples/tof/vl53l1x/complete.js +151 -0
  177. package/examples/tof/vl53l1x/demo.js +100 -0
  178. package/examples/tof/vl53l1x/minimal.js +25 -0
  179. package/package.json +5 -1
  180. package/src/chips/accelerometer/adxl345.js +482 -0
  181. package/src/chips/accelerometer/adxl362.js +594 -0
  182. package/src/chips/adc_dac/ad7705.js +345 -0
  183. package/src/chips/adc_dac/ad7706.js +331 -0
  184. package/src/chips/adc_dac/hx710a.js +184 -0
  185. package/src/chips/adc_dac/hx710b.js +186 -0
  186. package/src/chips/adc_dac/hx711.js +15 -15
  187. package/src/chips/adc_dac/mcp4725.js +48 -40
  188. package/src/chips/adc_dac/mcp4728.js +57 -44
  189. package/src/chips/adc_dac/pcf8591.js +196 -0
  190. package/src/chips/comms/mcp2515.js +659 -0
  191. package/src/chips/comms/rda5807m.js +393 -0
  192. package/src/chips/comms/rfm9x.js +590 -0
  193. package/src/chips/display/pcf8576.js +42 -33
  194. package/src/chips/environmental/aht21.js +52 -37
  195. package/src/chips/environmental/bme280.js +85 -66
  196. package/src/chips/environmental/bme680.js +110 -87
  197. package/src/chips/gas/ens160.js +82 -64
  198. package/src/chips/gnss/neo6.js +438 -0
  199. package/src/chips/gyroscope/l3g4200d.js +366 -0
  200. package/src/chips/gyroscope/l3gd20h.js +314 -0
  201. package/src/chips/humidity/dht11.js +135 -0
  202. package/src/chips/imu/mpu6050.js +89 -66
  203. package/src/chips/imu/mpu9250.js +394 -0
  204. package/src/chips/imu/mpu9255.js +447 -0
  205. package/src/chips/io_expander/mcp23017.js +240 -157
  206. package/src/chips/io_expander/pcf8574.js +149 -124
  207. package/src/chips/io_expander/pcf8575.js +164 -135
  208. package/src/chips/io_expander/tpic6b595.js +242 -0
  209. package/src/chips/led/_NeoPixelRGBBase.js +204 -0
  210. package/src/chips/led/_NeoPixelRGBWBase.js +218 -0
  211. package/src/chips/led/apa102.js +236 -0
  212. package/src/chips/led/sk6812rgbw.js +15 -149
  213. package/src/chips/led/ws2812b.js +14 -139
  214. package/src/chips/led/ws2814.js +49 -0
  215. package/src/chips/light/apds-9930.js +342 -0
  216. package/src/chips/light/apds9960.js +158 -123
  217. package/src/chips/magnetometer/as5600.js +102 -82
  218. package/src/chips/magnetometer/hmc5883l.js +222 -0
  219. package/src/chips/memory/_24aa02uid.js +32 -29
  220. package/src/chips/motor/drv8830.js +239 -0
  221. package/src/chips/other/mpr121.js +375 -0
  222. package/src/chips/power/ade7953.js +427 -0
  223. package/src/chips/power/ina219.js +45 -40
  224. package/src/chips/power/ina226.js +50 -45
  225. package/src/chips/power/ina3221.js +95 -76
  226. package/src/chips/pressure/bmp085.js +251 -0
  227. package/src/chips/pressure/bmp180.js +54 -37
  228. package/src/chips/pressure/bmp280.js +72 -53
  229. package/src/chips/pressure/bmp384.js +410 -0
  230. package/src/chips/pressure/bmp581.js +489 -0
  231. package/src/chips/pressure/lps22df.js +341 -0
  232. package/src/chips/pressure/lps28dfw.js +314 -0
  233. package/src/chips/pressure/lps33hw.js +255 -0
  234. package/src/chips/rfid/mfrc522.js +674 -0
  235. package/src/chips/rtc/ds3231.js +504 -0
  236. package/src/chips/rtc/pcf8523.js +539 -0
  237. package/src/chips/temperature/mcp9808.js +488 -0
  238. package/src/chips/temperature/tmp117.js +471 -0
  239. package/src/chips/tof/_vl53_base.js +160 -0
  240. package/src/chips/tof/vl53l0x.js +816 -0
  241. package/src/chips/tof/vl53l1x.js +816 -0
  242. package/src/connection/connection.js +111 -0
  243. package/src/connection/dhtxx.js +138 -0
  244. package/src/connection/dhtxx_mock.js +39 -0
  245. package/src/{transport → connection}/hx711.js +49 -22
  246. package/src/connection/hx711_mock.js +52 -0
  247. package/src/{transport → connection}/i2c.js +13 -9
  248. package/src/connection/i2c_mock.js +91 -0
  249. package/src/connection/input_pin.js +156 -0
  250. package/src/connection/neo6_mock.js +45 -0
  251. package/src/{transport → connection}/neopixel.js +23 -4
  252. package/src/connection/output_pin.js +41 -0
  253. package/src/connection/sipo.js +159 -0
  254. package/src/{transport → connection}/smbus.js +14 -10
  255. package/src/{transport → connection}/spi.js +12 -8
  256. package/src/connection/spi_mock.js +151 -0
  257. package/src/{transport → connection}/uart.js +33 -26
  258. package/examples/gnss/.gitkeep +0 -0
  259. package/examples/humidity/.gitkeep +0 -0
  260. package/examples/motor/.gitkeep +0 -0
  261. package/examples/temperature/.gitkeep +0 -0
  262. package/examples/tof/.gitkeep +0 -0
  263. package/src/chips/gnss/.gitkeep +0 -0
  264. package/src/chips/motor/.gitkeep +0 -0
  265. package/src/chips/temperature/.gitkeep +0 -0
  266. package/src/chips/tof/.gitkeep +0 -0
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+ const { I2CConnection } = require('../../../src/connection/i2c');
3
+ const { LPS33HWFull } = require('../../../src/chips/pressure/lps33hw');
4
+
5
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
6
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x5C', 16);
7
+
8
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR);
9
+
10
+ // --- Altimeter preset: 10 Hz ODR with ODR/20 LPF ---
11
+ // 10 Hz gives a fresh pressure sample every 100 ms, and the on-chip low-pass
12
+ // filter at ODR/20 (~0.5 Hz cutoff) suppresses door-slam / ventilation noise.
13
+ const lps = new LPS33HWFull(connection); // Create LPS33HW driver, (connection)
14
+
15
+ (async () => {
16
+ await lps.configure(LPS33HWFull.ODR_10_HZ, 1, 1, LPS33HWFull.LPFP_BW_ODR_20, 0, 0); // Configure chip, (odr=10Hz, bdu=1, enLpfp=1, lpfpCfg=ODR/20, lcEn=0, sim=0) → undefined
17
+
18
+ // --- Settle, then log altitude at 1 Hz for 10 s ---
19
+ // The first AUTOZERO locks the local zero reference; later samples drift
20
+ // relative to it, giving floor-to-floor relative altitude changes.
21
+ await lps.setAutozero(); // Enable AUTOZERO, () → undefined
22
+ await new Promise((r) => setTimeout(r, 1000));
23
+
24
+ const alts = [];
25
+ for (let n = 0; n < 10; n++) {
26
+ const sample = await lps.oneShot(); // Single-shot read, () → {pressure_Pa: number, temperature_C: number}
27
+ const alt = 44330 * (1 - Math.pow(sample.pressure_Pa / 101325, 1 / 5.255));
28
+ alts.push(alt);
29
+ console.log(`${n}s: T=${sample.temperature_C.toFixed(2)} C, P=${sample.pressure_Pa.toFixed(1)} Pa, alt=${alt.toFixed(2)} m`);
30
+ await new Promise((r) => setTimeout(r, 1000));
31
+ }
32
+
33
+ // --- Refresh the AUTOZERO every 10 s to track weather drift ---
34
+ // Atmospheric pressure changes by ~1 hPa per 8 m of equivalent altitude,
35
+ // so an unattended sensor will wander several metres over 10 minutes if
36
+ // the reference isn't periodically re-zeroed.
37
+ await lps.setAutozero(); // Enable AUTOZERO, () → undefined
38
+
39
+ console.log(`Altimeter: min=${Math.min(...alts).toFixed(2)} max=${Math.max(...alts).toFixed(2)} span=${(Math.max(...alts) - Math.min(...alts)).toFixed(2)} m`);
40
+
41
+ await connection.close();
42
+ console.log('===DONE: 0 passed, 0 failed===');
43
+ })();
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+ const { I2CConnection } = require('../../../src/connection/i2c');
3
+ const { LPS33HWMinimal } = require('../../../src/chips/pressure/lps33hw');
4
+
5
+ const I2C_BUS = parseInt(process.env.I2C_BUS || '1', 10);
6
+ const I2C_ADDR = parseInt(process.env.I2C_ADDR || '0x5C', 16);
7
+
8
+ const connection = new I2CConnection(I2C_BUS, I2C_ADDR);
9
+ const lps = new LPS33HWMinimal(connection); // Create LPS33HW driver, (connection)
10
+
11
+ (async () => {
12
+ for (let i = 0; i < 5; i++) {
13
+ const t = await lps.temperature(); // Read temperature, () → number °C
14
+ const p = await lps.pressure(); // Read pressure, () → number Pa
15
+ console.log(`${t.toFixed(2)} C, ${p.toFixed(1)} Pa`);
16
+ }
17
+ await connection.close();
18
+ console.log('===DONE: 0 passed, 0 failed===');
19
+ })();
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('../../../src/connection/spi');
4
+ const { MFRC522Full } = require('../../../src/chips/rfid/mfrc522');
5
+
6
+ const connection = new SPIConnection(0, 0, { maxSpeedHz: 1_000_000, mode: 0 }); // Create SPI connection, (bus, device, options)
7
+ const mfrc = new MFRC522Full(connection); // Create MFRC522 driver, (connection, busType='spi')
8
+
9
+ (async () => {
10
+ const v = await mfrc.version(); // Read version register, () → {chipType, version}
11
+ // for MFRC522 chipType=0x09, version=1 (v1.0) or 2 (v2.0)
12
+ console.log(`MFRC522 chipType=0x${v.chipType.toString(16)} version=${v.version}`);
13
+
14
+ const ok = await mfrc.selfTest(); // Run digital self test, () → bool
15
+ // compares 64 FIFO bytes against the version-specific reference
16
+ console.log(`self_test: ${ok ? 'PASS' : 'FAIL'}`);
17
+
18
+ await mfrc.antennaOn(); // Enable antenna driver (TX1+TX2), () → void
19
+ await mfrc.setAntennaGain(38); // Set receiver gain, (dB=18/23/33/38/43/48) → void
20
+ // 38 dB gives better read range on most antennas
21
+ console.log(`current gain: ${await mfrc.antennaGain()} dB`); // Read receiver gain, () → int dB
22
+
23
+ await mfrc.reset(); // Soft reset and reinitialise, () → void
24
+ // re-runs the full initialization sequence
25
+
26
+ const uid = await mfrc.selectCard(); // Anticollision/Select (leaves card active), () → Buffer | null
27
+ if (uid) {
28
+ console.log(`UID: ${uid.toString('hex')}`);
29
+ const factoryKey = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); // well-known default key — see spec
30
+ if (await mfrc.authenticate(4, MFRC522Full.KEY_A, factoryKey, uid.subarray(0, 4))) { // Run MFAuthent, (block, keyType, key=6 B, uid=4 B) → bool
31
+ const block = await mfrc.readBlock(4); // Read 16-byte block, (blockAddress) → Buffer
32
+ // requires successful authenticate for the containing sector
33
+ if (block) console.log(`block 4: ${block.toString('hex')}`);
34
+ await mfrc.decrementValue(4, 1); // Decrement value block, (block, delta=uint32) → bool
35
+ // runs Decrement + Transfer to the same block
36
+ await mfrc.stopCrypto(); // Clear MFCrypto1On, () → void
37
+ // required before authenticating a different sector
38
+ }
39
+ await mfrc.haltCard(); // Send HLTA, () → void
40
+ }
41
+
42
+ await connection.close();
43
+ console.log('===DONE: 0 passed, 0 failed===');
44
+ })();
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('../../../src/connection/spi');
4
+ const { MFRC522Full } = require('../../../src/chips/rfid/mfrc522');
5
+
6
+ const connection = new SPIConnection(0, 0, { maxSpeedHz: 1_000_000, mode: 0 });
7
+ const mfrc = new MFRC522Full(connection);
8
+
9
+ // --- Prepaid-card credit counter ---
10
+ // Simulates a transit-gate / vending-machine credit system using a MIFARE
11
+ // Classic value block. The factory default key A (FF FF FF FF FF FF) is
12
+ // used for the demo only — replace with a per-deployment secret in any
13
+ // real access-control system.
14
+ const CREDITS_BLOCK = 4;
15
+ const INITIAL_CREDITS = 10;
16
+
17
+ (async () => {
18
+ // --- Detect a card and select it for authenticated access ---
19
+ const uid = await mfrc.selectCard(); // Anticollision/Select only, () → Buffer | null
20
+ if (!uid) {
21
+ console.log('no card in field');
22
+ } else {
23
+ // --- Authenticate with the well-known MIFARE factory default key A ---
24
+ // In a real deployment this would be a per-card key stored securely
25
+ // (e.g. diversified per card UID and held in an HSM or secure element).
26
+ const factoryKey = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
27
+ if (!(await mfrc.authenticate(CREDITS_BLOCK, MFRC522Full.KEY_A, factoryKey, uid.subarray(0, 4)))) { // MFAuthent, (block, key, uid) → bool
28
+ console.log('authentication failed');
29
+ } else {
30
+ // --- Read the current value block; initialise it if unprogrammed ---
31
+ let block = await mfrc.readBlock(CREDITS_BLOCK); // Read 16-byte block, (blockAddress) → Buffer
32
+ const allZero = block && block.every((b) => b === 0);
33
+ if (allZero) {
34
+ const valueBlock = Buffer.alloc(16);
35
+ valueBlock.writeUInt32LE(INITIAL_CREDITS, 0);
36
+ const v = INITIAL_CREDITS;
37
+ valueBlock.writeUInt32LE((~v) >>> 0, 4);
38
+ valueBlock.writeUInt32LE(INITIAL_CREDITS, 8);
39
+ valueBlock[12] = CREDITS_BLOCK;
40
+ valueBlock[13] = (~CREDITS_BLOCK) & 0xFF;
41
+ valueBlock[14] = CREDITS_BLOCK;
42
+ valueBlock[15] = (~CREDITS_BLOCK) & 0xFF;
43
+ await mfrc.writeBlock(CREDITS_BLOCK, valueBlock); // Write 16 bytes, (block, data=16 B) → bool
44
+ await mfrc.restoreValue(CREDITS_BLOCK); // Restore + Transfer, (block) → bool
45
+ // normalises the value-block layout
46
+ }
47
+
48
+ // --- "Spend" one credit; refuse if balance is zero ---
49
+ block = await mfrc.readBlock(CREDITS_BLOCK); // Read current value, (block) → Buffer
50
+ if (block) {
51
+ const credits = block.readUInt32LE(0);
52
+ if (credits <= 0) {
53
+ console.log('Access denied — no credits remaining');
54
+ } else {
55
+ await mfrc.decrementValue(CREDITS_BLOCK, 1); // Decrement + Transfer, (block, delta) → bool
56
+ const updated = await mfrc.readBlock(CREDITS_BLOCK); // Read updated value, (block) → Buffer
57
+ if (updated) {
58
+ const newBalance = updated.readUInt32LE(0);
59
+ console.log(`spent 1 credit — remaining: ${newBalance}`);
60
+ }
61
+ }
62
+ }
63
+ await mfrc.stopCrypto(); // Clear MFCrypto1On, () → void
64
+ }
65
+ await mfrc.haltCard(); // Send HLTA, () → void
66
+ }
67
+
68
+ await connection.close();
69
+ console.log('===DONE: 0 passed, 0 failed===');
70
+ })();
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ const { SPIConnection } = require('../../../src/connection/spi');
4
+ const { MFRC522Minimal } = require('../../../src/chips/rfid/mfrc522');
5
+
6
+ const connection = new SPIConnection(0, 0, { maxSpeedHz: 1_000_000, mode: 0 }); // Create SPI connection, (bus, device, options)
7
+ const mfrc = new MFRC522Minimal(connection); // Create MFRC522 driver, (connection, busType='spi')
8
+
9
+ (async () => {
10
+ for (let i = 0; i < 10; i++) {
11
+ const present = await mfrc.isCardPresent(); // Detect card in field, () → bool
12
+ const uid = await mfrc.readUid(); // Read card UID (REQA → anticollision → HLTA), () → Buffer | null
13
+ console.log(`present=${present} uid=${uid ? uid.toString('hex') : 'null'}`);
14
+ }
15
+ await connection.close();
16
+ console.log('===DONE: 0 passed, 0 failed===');
17
+ })();
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { DS3231Full } = require('periph/src/chips/rtc/ds3231');
5
+
6
+ (async () => {
7
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
8
+ const connection = new I2CConnection(bus, 0x68);
9
+ const rtc = new DS3231Full(connection); // Create DS3231 Full driver, (connection)
10
+ await rtc.init(); // Confirm device presence, () → None
11
+
12
+ if (await rtc.oscillatorStopped()) { // Query oscillator-stop flag, () → bool
13
+ // true means timekeeping data may be invalid since the last check
14
+ await rtc.setDatetime(2026, 9, 22, 2, 14, 30, 0); // Set the calendar clock, (year, month, day, weekday, hour, minute, second) → None
15
+ // also clears OSF, since the time is now known-good
16
+ }
17
+
18
+ const dt = await rtc.getDatetime(); // Read the calendar clock, () → {year, month, ..., second}
19
+ // inherited from DS3231Minimal
20
+ console.log(dt);
21
+
22
+ const tempC = await rtc.readTemperature(); // Read cached temperature, () → float C
23
+ // may be up to 64 s stale (autonomous conversion cycle)
24
+ console.log('cached temp:', tempC);
25
+
26
+ const freshTempC = await rtc.forceTemperatureConversion(); // Force a fresh conversion, () → float C
27
+ // sets CONV and polls BSY, max 200 ms
28
+ console.log('fresh temp:', freshTempC);
29
+
30
+ await rtc.setAlarm1(0, 0, 0, 1, false, DS3231Full.ALARM1_EVERY_SECOND); // Configure alarm 1, (second, minute, hour, day_or_date, is_day_of_week, match_mode) → None
31
+ // once-per-second match; day_or_date/is_day_of_week ignored for this mode
32
+ const alarm1 = await rtc.getAlarm1(); // Read alarm 1 config, () → {second, minute, ..., matchMode}
33
+ console.log('alarm1:', alarm1);
34
+
35
+ await rtc.setAlarm2(30, 0, 1, false, DS3231Full.ALARM2_MATCH_MINUTES); // Configure alarm 2, (minute, hour, day_or_date, is_day_of_week, match_mode) → None
36
+ // fires when minutes register reads 30
37
+ const alarm2 = await rtc.getAlarm2(); // Read alarm 2 config, () → {minute, hour, ..., matchMode}
38
+ console.log('alarm2:', alarm2);
39
+
40
+ await rtc.enableInterrupt(DS3231Full.SOURCE_ALARM1 | DS3231Full.SOURCE_ALARM2); // Enable alarm interrupts, (source) → None
41
+ // sets A1IE/A2IE and INTCN=1 (INT/SQW now carries alarm interrupts)
42
+
43
+ await rtc.onInterrupt((status) => { // Subscribe to alarm interrupts, (callback) → None
44
+ if (status & DS3231Full.SOURCE_ALARM1) console.log('alarm 1 fired');
45
+ if (status & DS3231Full.SOURCE_ALARM2) console.log('alarm 2 fired');
46
+ });
47
+ await new Promise((r) => setTimeout(r, 3000));
48
+ await rtc.offInterrupt(); // Unsubscribe, () → None
49
+
50
+ const status = await rtc.pollInterrupt(); // Poll & clear alarm flags, () → int
51
+ console.log('leftover status:', status);
52
+
53
+ await rtc.disableInterrupt(DS3231Full.SOURCE_ALARM1 | DS3231Full.SOURCE_ALARM2); // Disable alarm interrupts, (source) → None
54
+
55
+ await rtc.enableSquareWave(1024, false); // Enable square wave, (rate_hz=8192, battery_backed=false) → None
56
+ // 1.024 kHz on INT/SQW; mutually exclusive with alarm interrupts
57
+ await rtc.disableSquareWave(); // Disable square wave, () → None
58
+ // returns INT/SQW to interrupt mode
59
+
60
+ console.log('32kHz enabled:', await rtc.is32khzEnabled()); // Query 32kHz output, () → bool
61
+ await rtc.disable32khzOutput(); // Disable 32kHz output, () → None
62
+ await rtc.enable32khzOutput(); // Enable 32kHz output, () → None
63
+
64
+ await rtc.disableBatteryOscillator(); // Disable oscillator on VBAT, () → None
65
+ // saves battery current; oscillator resumes once VCC returns
66
+ await rtc.enableBatteryOscillator(); // Enable oscillator on VBAT, () → None
67
+ // power-on default
68
+
69
+ await rtc.clearOscillatorStopped(); // Clear oscillator-stop flag, () → None
70
+
71
+ const aging = await rtc.getAgingOffset(); // Read aging offset, () → int
72
+ // raw signed 8-bit trim code, no fixed physical unit
73
+ console.log('aging offset:', aging);
74
+ await rtc.setAgingOffset(0); // Set aging offset, (offset) → None
75
+
76
+ await connection.close();
77
+ })();
@@ -0,0 +1,60 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { DS3231Full } = require('periph/src/chips/rtc/ds3231');
5
+
6
+ (async () => {
7
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
8
+ const connection = new I2CConnection(bus, 0x68);
9
+ const rtc = new DS3231Full(connection); // Create DS3231 Full driver, (connection)
10
+ await rtc.init(); // Confirm device presence, () → None
11
+
12
+ // --- Backup-clock module for a data logger ---
13
+ // A fresh chip (or one whose coin cell just died and was replaced) reports
14
+ // OSF=1: its timekeeping registers cannot be trusted. Reseed from a known
15
+ // reference timestamp rather than logging garbage — setDatetime() also
16
+ // clears OSF, so this only runs once per real power/battery loss.
17
+ if (await rtc.oscillatorStopped()) {
18
+ const now = new Date();
19
+ const weekday = ((now.getUTCDay() + 6) % 7) + 1; // JS Sunday=0 -> ISO 8601 Monday=1..Sunday=7
20
+ await rtc.setDatetime(now.getUTCFullYear(), now.getUTCMonth() + 1, now.getUTCDate(),
21
+ weekday, now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
22
+ console.log('oscillator was stopped - reseeded clock from host time');
23
+ }
24
+
25
+ // --- Arm both alarms as periodic wake sources ---
26
+ // Alarm 1 matches once per minute (at :00 seconds); Alarm 2 matches once
27
+ // per hour (at :00 minutes). Neither register is ever rewritten, so once
28
+ // armed they repeat indefinitely without host intervention.
29
+ await rtc.setAlarm1(0, 0, 0, 1, false, DS3231Full.ALARM1_MATCH_SECONDS); // seconds==0 -> once per minute
30
+ await rtc.setAlarm2(0, 0, 1, false, DS3231Full.ALARM2_EVERY_MINUTE);
31
+ await rtc.enableInterrupt(DS3231Full.SOURCE_ALARM1 | DS3231Full.SOURCE_ALARM2);
32
+
33
+ let logEntries = 0;
34
+ const MAX_ENTRIES = 5;
35
+ let done;
36
+ const finished = new Promise((resolve) => { done = resolve; });
37
+
38
+ // --- Log one line per alarm match, tagged with which alarm(s) fired ---
39
+ await rtc.onInterrupt(async (status) => {
40
+ const dt = await rtc.getDatetime();
41
+ const tempC = await rtc.readTemperature();
42
+ const tags = [];
43
+ if (status & DS3231Full.SOURCE_ALARM1) tags.push('minute');
44
+ if (status & DS3231Full.SOURCE_ALARM2) tags.push('hour');
45
+ const stamp = `${dt.year}-${String(dt.month).padStart(2, '0')}-${String(dt.day).padStart(2, '0')} ` +
46
+ `${String(dt.hour).padStart(2, '0')}:${String(dt.minute).padStart(2, '0')}:${String(dt.second).padStart(2, '0')}`;
47
+ console.log(`[${tags.join('+')}] ${stamp} ${tempC.toFixed(2)} C`);
48
+
49
+ logEntries++;
50
+ if (logEntries >= MAX_ENTRIES) done();
51
+ });
52
+
53
+ await finished;
54
+
55
+ // --- Clean up: silence both alarms and unsubscribe ---
56
+ await rtc.disableInterrupt(DS3231Full.SOURCE_ALARM1 | DS3231Full.SOURCE_ALARM2);
57
+ await rtc.offInterrupt();
58
+
59
+ await connection.close();
60
+ })();
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { DS3231Minimal } = require('periph/src/chips/rtc/ds3231');
5
+
6
+ (async () => {
7
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
8
+ const connection = new I2CConnection(bus, 0x68);
9
+ const rtc = new DS3231Minimal(connection); // Create DS3231 driver, (connection)
10
+ await rtc.init(); // Confirm device presence, () → None
11
+
12
+ await rtc.setDatetime(2026, 9, 22, 2, 14, 30, 0); // Set the calendar clock, (year, month, day, weekday, hour, minute, second) → None
13
+
14
+ for (let i = 0; i < 10; i++) {
15
+ const dt = await rtc.getDatetime(); // Read the calendar clock, () → {year, month, ..., second}
16
+ const tempC = await rtc.readTemperature(); // Read temperature, () → float C
17
+ console.log(`${dt.year}-${String(dt.month).padStart(2, '0')}-${String(dt.day).padStart(2, '0')} ` +
18
+ `${String(dt.hour).padStart(2, '0')}:${String(dt.minute).padStart(2, '0')}:${String(dt.second).padStart(2, '0')} ${tempC.toFixed(2)} C`);
19
+ await new Promise((r) => setTimeout(r, 1000));
20
+ }
21
+
22
+ await connection.close();
23
+ })();
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { PCF8523Full } = require('periph/src/chips/rtc/pcf8523');
5
+
6
+ (async () => {
7
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
8
+ const connection = new I2CConnection(bus, 0x68);
9
+ const rtc = new PCF8523Full(connection); // Create PCF8523 Full driver, (connection)
10
+ await rtc.init(); // Confirm presence + enable battery backup, () → None
11
+ // writes PM=000: standard switch-over, low detection on
12
+
13
+ await rtc.setDatetime(2026, 9, 23, 3, 14, 30, 0); // Set the calendar clock, (year, month, day, weekday 0=Sun, hour, minute, second) → None
14
+ // STOP-bit precision start; forces 24-hour mode and clears OS
15
+ const dt = await rtc.getDatetime(); // Read the calendar clock, () → {year, month, day, weekday, hour, minute, second}
16
+ // decodes the seven BCD clock/calendar registers
17
+ const stopped = await rtc.oscillatorStopped(); // Query oscillator-stop flag, () → bool
18
+ // true means the time may be invalid until setDatetime
19
+
20
+ await rtc.setAlarm({ minute: 0, hour: 9 }); // Configure alarm, ({minute, hour, day, weekday}) → None
21
+ // fires daily at 09:00; omitted fields are ignored in the match
22
+ const alarm = await rtc.getAlarm(); // Read alarm, () → {minute, hour, day, weekday}
23
+ // disabled fields decode as null
24
+
25
+ await rtc.configureTimerA('countdown', 10, '1hz'); // Start Timer A, (mode, value 0–255, sourceClock, pulsed=false) → None
26
+ // counts down 10 s, then sets CTAF
27
+ const remainingA = await rtc.readTimerA(); // Read Timer A counter, () → int
28
+ // live value, not the loaded one
29
+ await rtc.disableTimerA(); // Stop Timer A, () → None
30
+
31
+ await rtc.configureTimerB(30, '1hz', 62.5, true); // Start Timer B, (value 0–255, sourceClock, pulseWidthMs=46.875 ms, pulsed=false) → None
32
+ // 30 s countdown, pulsed 62.5 ms low on INT1 and INT2
33
+ const remainingB = await rtc.readTimerB(); // Read Timer B counter, () → int
34
+ await rtc.disableTimerB(); // Stop Timer B, () → None
35
+
36
+ await rtc.setClockOutput(1); // Drive CLKOUT, (frequencyHz) → None
37
+ // 1 Hz square wave on the shared INT1/CLKOUT pin
38
+ await rtc.disableClockOutput(); // Disable CLKOUT, () → None
39
+ // frees INT1 for interrupts
40
+
41
+ await rtc.setOffset(-3, 'every_two_hours'); // Write offset calibration, (offset −64–63, mode='every_two_hours') → None
42
+ // −3 LSB × 4.34 ppm = −13.02 ppm correction
43
+ const offset = await rtc.getOffset(); // Read offset calibration, () → {offset, mode}
44
+
45
+ await rtc.configureBatteryBackup('standard', true); // Select battery switch-over, (mode, lowDetection=true) → None
46
+ // switches to VBAT when VDD < VBAT and VDD < 2.5 V
47
+ const switched = await rtc.isBatterySwitchedOver(); // Query switch-over flag, () → bool
48
+ await rtc.clearBatterySwitchover(); // Clear switch-over flag, () → None
49
+ const low = await rtc.isBatteryLow(); // Query battery-low flag, () → bool
50
+ // read-only; clears itself once the cell is replaced
51
+
52
+ await rtc.onInterrupt((status) => console.log('interrupt status=0x' + status.toString(16))); // Subscribe to interrupts, (callback) → None
53
+ // falls back to 5 ms polling when no INT pin is wired
54
+ await rtc.enableInterrupt(PCF8523Full.SOURCE_ALARM | PCF8523Full.SOURCE_TIMER_B | PCF8523Full.SOURCE_BATTERY_LOW); // Enable sources, (source) → None
55
+ // sets AIE, CTBIE and BLIE
56
+ const status = await rtc.pollInterrupt(); // Poll & clear flags, () → int
57
+ // clears CTAF/CTBF/SF/AF/BSF, returns the pre-clear mask
58
+ await rtc.disableInterrupt(PCF8523Full.SOURCE_ALARM | PCF8523Full.SOURCE_TIMER_A | PCF8523Full.SOURCE_TIMER_B | PCF8523Full.SOURCE_BATTERY_LOW); // Disable sources, (source) → None
59
+ await rtc.offInterrupt(); // Unsubscribe, () → None
60
+
61
+ await rtc.softwareReset(); // Software reset, () → None
62
+ // control registers back to POR (PM=111); time is kept
63
+
64
+ console.log(dt, { stopped }, alarm, { remainingA, remainingB }, offset, { switched, low, status });
65
+ await connection.close();
66
+ })();
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ // Scheduling core of a battery-backed logger: reseeds the clock after a
4
+ // power loss, checks the coin cell, then wakes on an hourly alarm to print
5
+ // a timestamp while Timer B pulses a 30-second "still running" heartbeat
6
+ // on INT2 that toggles an LED.
7
+
8
+ const { I2CConnection } = require('periph/src/connection/i2c');
9
+ const { PCF8523Full } = require('periph/src/chips/rtc/pcf8523');
10
+
11
+ (async () => {
12
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
13
+ const connection = new I2CConnection(bus, 0x68);
14
+ const rtc = new PCF8523Full(connection); // Create PCF8523 Full driver, (connection)
15
+ await rtc.init(); // Confirm presence + enable battery backup, () → None
16
+
17
+ // --- Detect a lost time reference and reseed if needed ---
18
+ // A fresh chip, or one whose backup cell was disconnected too long,
19
+ // reports the OS flag set: its calendar cannot be trusted until reseeded.
20
+ if (await rtc.oscillatorStopped()) { // Query oscillator-stop flag, () → bool
21
+ await rtc.setDatetime(2026, 1, 1, 4, 0, 0, 0); // Set the calendar clock, (year, month, day, weekday 0=Sun, hour, minute, second) → None
22
+ console.log('oscillator was stopped - reseeded from reference timestamp');
23
+ }
24
+
25
+ // --- Keep the clock alive through power cuts ---
26
+ // Standard switch-over is already the driver default; it is repeated here
27
+ // so the logger's power policy is explicit. A low coin cell is reported
28
+ // once so it can be replaced before the next outage.
29
+ await rtc.configureBatteryBackup('standard'); // Select battery switch-over, (mode, lowDetection=true) → None
30
+ if (await rtc.isBatteryLow()) { // Query battery-low flag, () → bool
31
+ console.log('warning: backup battery low - replace the coin cell');
32
+ }
33
+
34
+ // --- Hourly wake-up plus a 30 s heartbeat ---
35
+ // Only the minute field is enabled, so the alarm matches at hh:00 every
36
+ // hour. Timer B reloads automatically and has its own INT2 pin, so the
37
+ // heartbeat keeps running independently of the hourly alarm.
38
+ await rtc.disableClockOutput(); // Disable CLKOUT, () → None
39
+ await rtc.setAlarm({ minute: 0 }); // Configure alarm, ({minute, hour, day, weekday}) → None
40
+ await rtc.configureTimerB(30, '1hz'); // Start Timer B, (value 0–255, sourceClock, pulseWidthMs=46.875 ms, pulsed=false) → None
41
+
42
+ // --- Dispatch by source: log on the alarm, blink on the heartbeat ---
43
+ let alarms = 0;
44
+ let ledOn = false;
45
+ await new Promise((resolve) => {
46
+ rtc.onInterrupt(async (status) => { // Subscribe to interrupts, (callback) → None
47
+ if (status & PCF8523Full.SOURCE_ALARM) {
48
+ const dt = await rtc.getDatetime(); // Read the calendar clock, () → {year, month, day, weekday, hour, minute, second}
49
+ console.log('[hourly]', dt);
50
+ if (++alarms >= 3) resolve();
51
+ }
52
+ if (status & PCF8523Full.SOURCE_TIMER_B) {
53
+ ledOn = !ledOn;
54
+ console.log(`[heartbeat] LED ${ledOn ? 'on' : 'off'}`);
55
+ }
56
+ });
57
+ rtc.enableInterrupt(PCF8523Full.SOURCE_ALARM | PCF8523Full.SOURCE_TIMER_B); // Enable sources, (source) → None
58
+ });
59
+
60
+ // --- Leave the chip quiet on exit ---
61
+ await rtc.disableInterrupt(PCF8523Full.SOURCE_ALARM | PCF8523Full.SOURCE_TIMER_B); // Disable sources, (source) → None
62
+ await rtc.disableTimerB(); // Stop Timer B, () → None
63
+ await rtc.offInterrupt(); // Unsubscribe, () → None
64
+ await connection.close();
65
+ })();
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { PCF8523Minimal } = require('periph/src/chips/rtc/pcf8523');
5
+
6
+ (async () => {
7
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
8
+ const connection = new I2CConnection(bus, 0x68);
9
+ const rtc = new PCF8523Minimal(connection); // Create PCF8523 driver, (connection)
10
+ await rtc.init(); // Confirm presence + enable battery backup, () → None
11
+
12
+ const pad = (n) => String(n).padStart(2, '0');
13
+ for (let i = 0; i < 10; i++) {
14
+ const dt = await rtc.getDatetime(); // Read the calendar clock, () → {year, month, day, weekday, hour, minute, second}
15
+ console.log(`${dt.year}-${pad(dt.month)}-${pad(dt.day)} ${pad(dt.hour)}:${pad(dt.minute)}:${pad(dt.second)}`);
16
+ await new Promise((r) => setTimeout(r, 1000));
17
+ }
18
+
19
+ await connection.close();
20
+ })();
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ // Exercises every method in the MCP9808 public API: temperature, resolution,
4
+ // Shutdown mode, the three boundaries and hysteresis, the Alert output, and
5
+ // the boundary-status interrupt API. The one-way lock methods are shown but
6
+ // left commented out — they cannot be undone without a power-on reset.
7
+
8
+ const { I2CConnection } = require('periph/src/connection/i2c');
9
+ const { MCP9808Full } = require('periph/src/chips/temperature/mcp9808');
10
+
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
+
13
+ (async () => {
14
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
15
+ const connection = new I2CConnection(bus, MCP9808Full.I2C_ADDRESS);
16
+ const sensor = new MCP9808Full(connection); // Create MCP9808 Full driver, (connection)
17
+ // starts the MANUFACTURER_ID / DEVICE_ID check
18
+ await sensor.init(); // Confirm device identity, () → None
19
+ // rejects if the IDs are not 0x0054 / 0x04
20
+
21
+ const t = await sensor.readTemperature(); // Read ambient temperature, () → number °C
22
+ // masks TA's 3 status bits, decodes 1/16 °C two's complement
23
+ console.log(`temperature ${t.toFixed(4)} °C`);
24
+
25
+ await sensor.setResolution(0.25); // Set resolution, (celsius 0.5|0.25|0.125|0.0625) → None
26
+ // 0.25 °C step converts in ~65 ms instead of 250 ms
27
+ console.log('resolution', await sensor.getResolution(), '°C'); // Read resolution, () → number °C
28
+ // decodes the RESOLUTION register code
29
+
30
+ await sensor.shutdown(); // Enter Shutdown mode, () → None
31
+ // stops conversion; TA keeps its last value
32
+ console.log('shutdown', await sensor.isShutdown()); // Check Shutdown mode, () → boolean
33
+ // reads CONFIG.SHDN
34
+ await sensor.wake(); // Leave Shutdown mode, () → None
35
+ // resumes continuous conversion
36
+ await sleep(100);
37
+
38
+ await sensor.setUpperLimit(30.0); // Set TUPPER, (celsius °C) → None
39
+ // rounded to the nearest 0.25 °C step
40
+ await sensor.setLowerLimit(10.0); // Set TLOWER, (celsius °C) → None
41
+ // rounded to the nearest 0.25 °C step
42
+ await sensor.setCriticalLimit(45.0); // Set TCRIT, (celsius °C) → None
43
+ // rounded to the nearest 0.25 °C step
44
+ console.log('upper', await sensor.getUpperLimit()); // Read TUPPER, () → number °C
45
+ // decodes the 0.25 °C two's-complement boundary
46
+ console.log('lower', await sensor.getLowerLimit()); // Read TLOWER, () → number °C
47
+ // decodes the 0.25 °C two's-complement boundary
48
+ console.log('critical', await sensor.getCriticalLimit()); // Read TCRIT, () → number °C
49
+ // decodes the 0.25 °C two's-complement boundary
50
+
51
+ await sensor.setHysteresis(1.5); // Set hysteresis, (celsius 0|1.5|3.0|6.0) → None
52
+ // applied on the cooling edge of each boundary only
53
+ console.log('hysteresis', await sensor.getHysteresis()); // Read hysteresis, () → number °C
54
+ // decodes CONFIG.THYST
55
+
56
+ // await sensor.lockCriticalLimit(); // Lock TCRIT, () → None
57
+ // // irreversible until power-on reset
58
+ // await sensor.lockWindowLimits(); // Lock TUPPER/TLOWER, () → None
59
+ // // irreversible until power-on reset
60
+ console.log('crit locked', await sensor.isCriticalLimitLocked()); // Check TCRIT lock, () → boolean
61
+ // reads CONFIG.CRIT_LOCK
62
+ console.log('win locked', await sensor.isWindowLimitsLocked()); // Check TUPPER/TLOWER lock, () → boolean
63
+ // reads CONFIG.WIN_LOCK
64
+
65
+ await sensor.configureAlert('all', 'interrupt', 'active_low'); // Configure Alert, (mode='all', output='comparator', polarity='active_low') → None
66
+ // sets ALERT_SEL, ALERT_MOD and ALERT_POL together
67
+ await sensor.enableAlert(); // Enable Alert output, () → None
68
+ // sets CONFIG.ALERT_CNT
69
+ console.log('alert asserted', await sensor.isAlertAsserted()); // Check Alert output, () → boolean
70
+ // reads the read-only CONFIG.ALERT_STAT
71
+
72
+ const status = await sensor.pollInterrupt(); // Read boundary status, () → number mask
73
+ // TA's live bits: SOURCE_LOWER/UPPER/CRITICAL, nothing cleared
74
+ console.log('below lower', (status & MCP9808Full.SOURCE_LOWER) !== 0,
75
+ 'above upper', (status & MCP9808Full.SOURCE_UPPER) !== 0,
76
+ 'critical', (status & MCP9808Full.SOURCE_CRITICAL) !== 0);
77
+ await sensor.clearInterrupt(); // Clear interrupt-mode Alert, () → None
78
+ // writes CONFIG.INT_CLEAR=1; no effect in comparator mode
79
+
80
+ await sensor.onInterrupt((s) => console.log('alert, status mask', s)); // Subscribe to Alert, (callback) → None
81
+ // callback receives the pollInterrupt() mask
82
+ await sleep(5000);
83
+ await sensor.offInterrupt(); // Unsubscribe, () → None
84
+ // detaches the edge handler or stops the polling timer
85
+ await sensor.disableAlert(); // Disable Alert output, () → None
86
+ // clears CONFIG.ALERT_CNT
87
+
88
+ await connection.close();
89
+ })();