periph 1.2.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 (39) hide show
  1. package/README.md +7 -0
  2. package/examples/motor/drv8830/complete.js +50 -0
  3. package/examples/motor/drv8830/demo.js +57 -0
  4. package/examples/motor/drv8830/minimal.js +23 -0
  5. package/examples/rtc/ds3231/complete.js +77 -0
  6. package/examples/rtc/ds3231/demo.js +60 -0
  7. package/examples/rtc/ds3231/minimal.js +23 -0
  8. package/examples/rtc/pcf8523/complete.js +66 -0
  9. package/examples/rtc/pcf8523/demo.js +65 -0
  10. package/examples/rtc/pcf8523/minimal.js +20 -0
  11. package/examples/temperature/mcp9808/complete.js +89 -0
  12. package/examples/temperature/mcp9808/demo.js +62 -0
  13. package/examples/temperature/mcp9808/minimal.js +21 -0
  14. package/examples/temperature/tmp117/complete.js +90 -0
  15. package/examples/temperature/tmp117/demo.js +73 -0
  16. package/examples/temperature/tmp117/minimal.js +21 -0
  17. package/examples/tof/vl53l0x/complete.js +118 -0
  18. package/examples/tof/vl53l0x/demo.js +83 -0
  19. package/examples/tof/vl53l0x/minimal.js +25 -0
  20. package/examples/tof/vl53l1x/complete.js +151 -0
  21. package/examples/tof/vl53l1x/demo.js +100 -0
  22. package/examples/tof/vl53l1x/minimal.js +25 -0
  23. package/package.json +1 -1
  24. package/src/chips/imu/mpu9250.js +4 -4
  25. package/src/chips/imu/mpu9255.js +5 -5
  26. package/src/chips/motor/drv8830.js +239 -0
  27. package/src/chips/rtc/ds3231.js +504 -0
  28. package/src/chips/rtc/pcf8523.js +539 -0
  29. package/src/chips/temperature/mcp9808.js +488 -0
  30. package/src/chips/temperature/tmp117.js +471 -0
  31. package/src/chips/tof/_vl53_base.js +160 -0
  32. package/src/chips/tof/vl53l0x.js +816 -0
  33. package/src/chips/tof/vl53l1x.js +816 -0
  34. package/examples/motor/.gitkeep +0 -0
  35. package/examples/temperature/.gitkeep +0 -0
  36. package/examples/tof/.gitkeep +0 -0
  37. package/src/chips/motor/.gitkeep +0 -0
  38. package/src/chips/temperature/.gitkeep +0 -0
  39. package/src/chips/tof/.gitkeep +0 -0
package/README.md CHANGED
@@ -49,6 +49,8 @@ Each chip exposes two classes:
49
49
  | BMP384 | Pressure sensor | `periph/src/chips/pressure/bmp384` |
50
50
  | BMP581 | Pressure sensor | `periph/src/chips/pressure/bmp581` |
51
51
  | DHT11 | Humidity sensor | `periph/src/chips/humidity/dht11` |
52
+ | DRV8830 | Motor driver | `periph/src/chips/motor/drv8830` |
53
+ | DS3231 | RTC | `periph/src/chips/rtc/ds3231` |
52
54
  | ENS160 | Gas sensor | `periph/src/chips/gas/ens160` |
53
55
  | HMC5883L | Magnetometer | `periph/src/chips/magnetometer/hmc5883l` |
54
56
  | HX710A | ADC/DAC | `periph/src/chips/adc_dac/hx710a` |
@@ -66,6 +68,7 @@ Each chip exposes two classes:
66
68
  | MCP2515 | Comms | `periph/src/chips/comms/mcp2515` |
67
69
  | MCP4725 | ADC/DAC | `periph/src/chips/adc_dac/mcp4725` |
68
70
  | MCP4728 | ADC/DAC | `periph/src/chips/adc_dac/mcp4728` |
71
+ | MCP9808 | Temperature sensor | `periph/src/chips/temperature/mcp9808` |
69
72
  | MFRC522 | RFID/NFC | `periph/src/chips/rfid/mfrc522` |
70
73
  | MPR121 | Other | `periph/src/chips/other/mpr121` |
71
74
  | MPU6050 | IMU | `periph/src/chips/imu/mpu6050` |
@@ -74,6 +77,7 @@ Each chip exposes two classes:
74
77
  | NEO6 | GNSS/GPS | `periph/src/chips/gnss/neo6` |
75
78
  | NEOPIXELRGBBASE | LED driver | `periph/src/chips/led/_NeoPixelRGBBase` |
76
79
  | NEOPIXELRGBWBASE | LED driver | `periph/src/chips/led/_NeoPixelRGBWBase` |
80
+ | PCF8523 | RTC | `periph/src/chips/rtc/pcf8523` |
77
81
  | PCF8574 | IO expander | `periph/src/chips/io_expander/pcf8574` |
78
82
  | PCF8575 | IO expander | `periph/src/chips/io_expander/pcf8575` |
79
83
  | PCF8576 | Display driver | `periph/src/chips/display/pcf8576` |
@@ -81,7 +85,10 @@ Each chip exposes two classes:
81
85
  | RDA5807M | Comms | `periph/src/chips/comms/rda5807m` |
82
86
  | RFM9X | Comms | `periph/src/chips/comms/rfm9x` |
83
87
  | SK6812RGBW | LED driver | `periph/src/chips/led/sk6812rgbw` |
88
+ | TMP117 | Temperature sensor | `periph/src/chips/temperature/tmp117` |
84
89
  | TPIC6B595 | IO expander | `periph/src/chips/io_expander/tpic6b595` |
90
+ | VL53L0X | Time-of-flight | `periph/src/chips/tof/vl53l0x` |
91
+ | VL53L1X | Time-of-flight | `periph/src/chips/tof/vl53l1x` |
85
92
  | WS2812B | LED driver | `periph/src/chips/led/ws2812b` |
86
93
  | WS2814 | LED driver | `periph/src/chips/led/ws2814` |
87
94
 
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { DRV8830Full } = require('periph/src/chips/motor/drv8830');
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, DRV8830Full.I2C_ADDRESS);
11
+ const motor = new DRV8830Full(connection); // Create DRV8830 Full driver, (connection)
12
+ await motor.init(); // Confirm device presence, () → None
13
+ // plain CONTROL read; the chip has no identity register
14
+
15
+ await motor.drive(2.5); // Drive at regulated voltage, (voltage V, + = forward) → None
16
+ // maps 2.5 V to the nearest VSET code and sets IN1=1, IN2=0
17
+ await sleep(1000);
18
+ const out = await motor.readOutput(); // Read back CONTROL, () → {voltage V, direction}
19
+ // decodes VSET to volts and IN1/IN2 to a direction name
20
+ console.log(`commanded ${out.voltage.toFixed(2)} V ${out.direction}`);
21
+
22
+ await motor.drive(-1.5); // Drive at regulated voltage, (voltage V, - = reverse) → None
23
+ // a negative voltage sets IN1=0, IN2=1
24
+ await sleep(1000);
25
+
26
+ await motor.setOutput(37, true, false); // Write raw CONTROL fields, (vset 6–63, in1, in2) → None
27
+ // VSET 37 is ~2.97 V forward; codes 0–5 throw RangeError
28
+ await sleep(1000);
29
+
30
+ await motor.brake(); // Short-brake, () → None
31
+ // IN1=IN2=1 drives both outputs high
32
+ await sleep(500);
33
+ await motor.stop(); // Coast to standby, () → None
34
+ // IN1=IN2=0 leaves both outputs high-impedance
35
+
36
+ const fault = await motor.readFault(); // Read fault status, () → {fault, ocp, uvlo, ots, ilimit}
37
+ // does not clear — latched OCP/ILIMIT keep the bridge off
38
+ console.log('fault', fault);
39
+ await motor.clearFault(); // Clear fault bits, () → None
40
+ // writes CLEAR=1; re-enables a latched-off bridge
41
+
42
+ await motor.onInterrupt((status) => console.log('fault interrupt', status)); // Subscribe to FAULTn, (callback) → None
43
+ // falls back to 5 ms polling when no intPin is wired
44
+ const status = await motor.pollInterrupt(); // Poll fault status, () → {fault, ocp, uvlo, ots, ilimit}
45
+ // same as readFault(); never clears implicitly
46
+ await motor.offInterrupt(); // Unsubscribe, () → None
47
+ console.log('poll', status);
48
+
49
+ await connection.close();
50
+ })();
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+
3
+ // Battery-powered toy motor controller: holds a regulated 3.0 V forward, then
4
+ // 2.0 V reverse, printing the commanded output every second — the DRV8830
5
+ // keeps that average voltage constant as the battery sags. Brakes, then
6
+ // coasts. After every drive() call the fault register is checked; a fault
7
+ // (e.g. a stalled motor tripping ILIMIT) stops the motor and clears it.
8
+
9
+ const { I2CConnection } = require('periph/src/connection/i2c');
10
+ const { DRV8830Full } = require('periph/src/chips/motor/drv8830');
11
+
12
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13
+
14
+ (async () => {
15
+ const bus = parseInt(process.env.I2C_BUS || '1', 10);
16
+ const connection = new I2CConnection(bus, DRV8830Full.I2C_ADDRESS);
17
+ const motor = new DRV8830Full(connection); // Create DRV8830 Full driver, (connection)
18
+ await motor.init(); // Confirm device presence, () → None
19
+
20
+ async function checkFault() {
21
+ // --- Recover from a fault instead of leaving the bridge latched off ---
22
+ // OCP and ILIMIT disable the H-bridge until CLEAR is written; stop first
23
+ // so the motor does not lurch back to the old command on clear.
24
+ const f = await motor.readFault(); // Read fault status, () → {fault, ocp, uvlo, ots, ilimit}
25
+ if (f.fault) {
26
+ const names = ['ocp', 'uvlo', 'ots', 'ilimit'].filter((k) => f[k]).map((k) => k.toUpperCase());
27
+ console.log('fault:', names.join(', '));
28
+ await motor.stop(); // Coast to standby, () → None
29
+ await motor.clearFault(); // Clear fault bits, () → None
30
+ }
31
+ }
32
+
33
+ async function run(voltage, seconds) {
34
+ // --- Hold a regulated voltage and watch it stay put ---
35
+ // The chip PWM-regulates the bridge against VCC internally, so the
36
+ // commanded voltage (and motor speed) holds while the battery discharges.
37
+ await motor.drive(voltage); // Drive at regulated voltage, (voltage V, signed) → None
38
+ await checkFault();
39
+ for (let i = 0; i < seconds; i++) {
40
+ await sleep(1000);
41
+ const out = await motor.readOutput(); // Read back CONTROL, () → {voltage V, direction}
42
+ console.log(`${out.direction.padEnd(7)} ${out.voltage.toFixed(2)} V`);
43
+ }
44
+ }
45
+
46
+ await run(3.0, 5);
47
+ await run(-2.0, 5);
48
+
49
+ // --- Stop quickly, then release ---
50
+ // Braking shorts the winding for a fast stop; coasting afterwards removes
51
+ // the load so the motor does not sit shorted indefinitely.
52
+ await motor.brake(); // Short-brake, () → None
53
+ await sleep(500);
54
+ await motor.stop(); // Coast to standby, () → None
55
+
56
+ await connection.close();
57
+ })();
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const { I2CConnection } = require('periph/src/connection/i2c');
4
+ const { DRV8830Minimal } = require('periph/src/chips/motor/drv8830');
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, DRV8830Minimal.I2C_ADDRESS);
11
+ const motor = new DRV8830Minimal(connection); // Create DRV8830 driver, (connection)
12
+ await motor.init(); // Confirm device presence, () → None
13
+
14
+ for (let i = 0; i < 5; i++) {
15
+ await motor.drive(3.0); // Drive at regulated voltage, (voltage V, + = forward) → None
16
+ await sleep(2000);
17
+ await motor.drive(-3.0); // Drive at regulated voltage, (voltage V, - = reverse) → None
18
+ await sleep(2000);
19
+ }
20
+
21
+ await motor.stop(); // Coast to standby, () → None
22
+ await connection.close();
23
+ })();
@@ -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
+ })();