Skip to content

A truly modular keyboard

C

firmware: battery level from the BQ25895 (BATT?)

Nathana25fb3539159
diff --git a/firmware/Core/Inc/batt.h b/firmware/Core/Inc/batt.h
new file mode 100644
index 0000000..4bbbaf8
--- /dev/null
+++ b/firmware/Core/Inc/batt.h
@@ -0,0 +1,35 @@
+/*
+ * Battery state from the BQ25895 charger (U8) on I2C3, address 0x6A.
+ * The only write is turning on its ADC (REG02 CONV_RATE, 1 s continuous);
+ * every charger setting stays as it is.
+ */
+#ifndef BATT_H
+#define BATT_H
+
+#include <stdint.h>
+
+#define BATT_POLL_MS 1000
+
+typedef struct
+{
+ uint8_t valid; /* 0 until the first real ADC reading */
+ uint8_t pct; /* 0-100, estimated from VBAT */
+ uint8_t chg; /* pre-charge or fast charge */
+ uint8_t usb; /* VBUS attached */
+ uint16_t mv; /* VBAT */
+} batt_t;
+
+/* Call often from the main loop or a sequencer task (never an ISR); it
+ * reads the charger every BATT_POLL_MS and sends BATT lines on change. */
+void BATT_Poll(uint32_t now);
+
+const batt_t *BATT_Get(void);
+
+/* LiPo state of charge from the resting cell voltage. Reads high while
+ * charging, since VBAT sits above the resting voltage then. */
+uint8_t BATT_Percent(uint16_t mv);
+
+/* REG0B..REG11 (7 bytes) into pct/chg/usb/mv, valid set. */
+void BATT_Decode(const uint8_t regs[7], batt_t *out);
+
+#endif /* BATT_H */
diff --git a/firmware/Core/Src/batt.c b/firmware/Core/Src/batt.c
new file mode 100644
index 0000000..3c56722
--- /dev/null
+++ b/firmware/Core/Src/batt.c
@@ -0,0 +1,102 @@
+#include "batt.h"
+#include "keybit_bus.h"
+#include "proto.h"
+
+/* Register map from TI's BQ25895 datasheet (SLUSC88C), section 8.4. */
+#define BQ_ADDR 0x6A
+#define REG02 0x02
+#define REG02_CONV_RATE 0x40 /* 1 s continuous ADC */
+#define REG02_TRIGGERS 0x82 /* CONV_START, FORCE_DPDM: self clearing, never write back a 1 */
+#define REG0B 0x0B /* VBUS_STAT[7:5] CHRG_STAT[4:3] PG_STAT[2] */
+#define REG0E_BATV(r) ((r) & 0x7F) /* 2.304 V + 20 mV/LSB */
+#define REG11_VBUS_GD 0x80
+
+#define PCT_STEP 5 /* send an unsolicited BATT line when pct moves this much */
+
+extern I2C_HandleTypeDef hi2c3;
+/* app_ble.c: feeds the BLE Battery Service, no-op until BLE is up. */
+void APP_BLE_SetBattery(uint8_t pct);
+
+static batt_t batt;
+static batt_t sent; /* last BATT line we broadcast */
+static uint32_t last_poll;
+static uint8_t polled, adc_was_on;
+
+/* ponytail: generic single cell LiPo curve at rest, a fuel gauge or a
+ * per-cell calibration would do better */
+static const struct { uint16_t mv; uint8_t pct; } curve[] = {
+ {4200, 100}, {4150, 95}, {4110, 90}, {4020, 80}, {3950, 70}, {3910, 60},
+ {3870, 50}, {3840, 40}, {3800, 30}, {3760, 20}, {3730, 10}, {3600, 5}, {3300, 0},
+};
+
+uint8_t BATT_Percent(uint16_t mv)
+{
+ if (mv >= curve[0].mv) return 100;
+ for (unsigned i = 1; i < sizeof(curve) / sizeof(curve[0]); i++)
+ {
+ if (mv >= curve[i].mv)
+ {
+ /* linear between the two points around mv */
+ uint32_t span = curve[i - 1].mv - curve[i].mv;
+ uint32_t up = mv - curve[i].mv;
+ return (uint8_t)(curve[i].pct + (up * (curve[i - 1].pct - curve[i].pct) + span / 2) / span);
+ }
+ }
+ return 0;
+}
+
+void BATT_Decode(const uint8_t regs[7], batt_t *out)
+{
+ uint8_t chrg = (regs[0] >> 3) & 3; /* REG0B */
+ out->mv = (uint16_t)(2304 + 20 * REG0E_BATV(regs[3])); /* REG0E */
+ out->pct = BATT_Percent(out->mv);
+ out->chg = chrg == 1 || chrg == 2; /* pre-charge, fast charge */
+ out->usb = (regs[6] & REG11_VBUS_GD) != 0; /* REG11 */
+ out->valid = 1;
+}
+
+const batt_t *BATT_Get(void)
+{
+ return &batt;
+}
+
+static int Diff(uint8_t a, uint8_t b)
+{
+ return a > b ? a - b : b - a;
+}
+
+void BATT_Poll(uint32_t now)
+{
+ if (polled && (uint32_t)(now - last_poll) < BATT_POLL_MS) return;
+ polled = 1;
+ last_poll = now;
+
+ /* CONV_RATE is cleared by a REG_RST or the charger's I2C watchdog, so
+ * check it every time and turn it back on. A reading taken right after
+ * turning it on is still the stale default, so skip that one. */
+ uint8_t r02;
+ if (!keybit_bus_read(&hi2c3, BQ_ADDR, REG02, &r02, 1)) return;
+ if (!(r02 & REG02_CONV_RATE))
+ {
+ r02 = (uint8_t)((r02 | REG02_CONV_RATE) & ~REG02_TRIGGERS);
+ keybit_bus_write(&hi2c3, BQ_ADDR, REG02, &r02, 1);
+ adc_was_on = 0;
+ return;
+ }
+ if (!adc_was_on)
+ {
+ adc_was_on = 1;
+ return;
+ }
+
+ uint8_t regs[7];
+ if (!keybit_bus_read(&hi2c3, BQ_ADDR, REG0B, regs, sizeof(regs))) return;
+ BATT_Decode(regs, &batt);
+ APP_BLE_SetBattery(batt.pct);
+
+ if (!sent.valid || Diff(batt.pct, sent.pct) >= PCT_STEP || batt.chg != sent.chg || batt.usb != sent.usb)
+ {
+ sent = batt;
+ PROTO_Send("BATT pct=%u chg=%u usb=%u", batt.pct, batt.chg, batt.usb);
+ }
+}
diff --git a/firmware/Core/Src/keymap.c b/firmware/Core/Src/keymap.c
index 6cf8bc7..1cee3f2 100644
--- a/firmware/Core/Src/keymap.c
+++ b/firmware/Core/Src/keymap.c
@@ -4,6 +4,7 @@
#include "shci.h"
#include "utilities_conf.h"
#include "hids_app.h"
+#include "batt.h"
#include "app_ble.h"
#include "proto.h"
#include "keymap.h"
@@ -311,6 +312,9 @@ static void Keys_Task(void)
KEYACT_Step(present_key, acts, present_count, HAL_GetTick(), report, &consumer);
HIDSAPP_SendKeyboard(report);
HIDSAPP_SendConsumer(consumer);
+
+ /* same task as the keys: the charger shares I2C3 with the Keybits */
+ BATT_Poll(HAL_GetTick());
}
static void Keys_Tick(void)
diff --git a/firmware/Core/Src/proto.c b/firmware/Core/Src/proto.c
index f7052d6..9c6c6f2 100644
--- a/firmware/Core/Src/proto.c
+++ b/firmware/Core/Src/proto.c
@@ -2,12 +2,13 @@
#include <stdio.h>
#include <string.h>
#include "keymap.h"
+#include "batt.h"
#include "proto.h"
/* Optional features the desktop app can use, only what's implemented.
* kb= (the embedded Keybit image version) waits for keybit_image.h to
* export one. */
-#define CAPS "hold,macro"
+#define CAPS "batt,hold,macro"
static proto_port_t *ports[PROTO_MAX_PORTS];
static int port_count;
@@ -156,6 +157,12 @@ static void Handle_Line(proto_port_t *port, char *cmd)
{
Reply(port, "KEYWORD v=%s proto=1 caps=%s", KEYWORD_FW_VERSION, CAPS);
}
+ else if (strcmp(cmd, "BATT?") == 0)
+ {
+ const batt_t *b = BATT_Get();
+ if (!b->valid) Reply(port, "ERR no battery reading yet");
+ else Reply(port, "BATT pct=%u chg=%u usb=%u", b->pct, b->chg, b->usb);
+ }
else if (strcmp(cmd, "SIDES?") == 0)
{
int n;
diff --git a/firmware/STM32Make.make b/firmware/STM32Make.make
index 0987446..953b523 100644
--- a/firmware/STM32Make.make
+++ b/firmware/STM32Make.make
@@ -102,6 +102,7 @@ Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_hal_rcc_ex.c \
Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_ll_rcc.c \
Drivers/STM32WBxx_HAL_Driver/Src/stm32wbxx_ll_usb.c \
Core/Src/app_entry.c \
+Core/Src/batt.c \
Core/Src/hw_timerserver.c \
Core/Src/keyact.c \
Core/Src/keymap.c \
diff --git a/firmware/STM32_WPAN/App/app_ble.c b/firmware/STM32_WPAN/App/app_ble.c
index 0a1f1ea..2de749c 100644
--- a/firmware/STM32_WPAN/App/app_ble.c
+++ b/firmware/STM32_WPAN/App/app_ble.c
@@ -30,6 +30,7 @@ static const uint8_t a_BLE_CfgErValue[16] = CFG_BLE_ER;
static uint16_t conn_handle = APP_BLE_NO_CONN;
static uint8_t ble_ready;
+static uint8_t battery_level = 100;
static uint8_t adv_timer_id;
static uint8_t a_BdAddr[6];
@@ -59,6 +60,13 @@ uint8_t APP_BLE_Ready(void)
return ble_ready;
}
+void APP_BLE_SetBattery(uint8_t pct)
+{
+ if (pct == battery_level) return;
+ battery_level = pct;
+ if (ble_ready) BAS_Update_Char(BATTERY_LEVEL_CHAR_UUID, 0, &battery_level);
+}
+
static void Adv_Slow(void)
{
if (conn_handle == APP_BLE_NO_CONN) Adv_Start(0);
@@ -139,9 +147,8 @@ void APP_BLE_Init(void)
dis.Length = sizeof(KEYWORD_FW_VERSION) - 1;
DIS_UpdateChar(FIRMWARE_REVISION_UUID, &dis);
- /* ponytail: fixed 100 %, the board has no battery gauge wired to the MCU yet */
- uint8_t level = 100;
- BAS_Update_Char(BATTERY_LEVEL_CHAR_UUID, 0, &level);
+ /* batt.c updates it from the charger's ADC once it has a reading */
+ BAS_Update_Char(BATTERY_LEVEL_CHAR_UUID, 0, &battery_level);
HIDSAPP_Init();
ble_ready = 1;
diff --git a/firmware/STM32_WPAN/App/app_ble.h b/firmware/STM32_WPAN/App/app_ble.h
index 6b361f0..a52a987 100644
--- a/firmware/STM32_WPAN/App/app_ble.h
+++ b/firmware/STM32_WPAN/App/app_ble.h
@@ -18,4 +18,7 @@ uint16_t APP_BLE_ConnHandle(void);
/* 1 once the CPU2 stack is up and the services exist. */
uint8_t APP_BLE_Ready(void);
+/* Battery Service level, 0-100. Safe to call before BLE is up. */
+void APP_BLE_SetBattery(uint8_t pct);
+
#endif /* APP_BLE_H */
diff --git a/firmware/test/batt_test.c b/firmware/test/batt_test.c
new file mode 100644
index 0000000..f66ce04
--- /dev/null
+++ b/firmware/test/batt_test.c
@@ -0,0 +1,126 @@
+/*
+ * Host check for Core/Src/batt.c: BQ25895 register decoding, the LiPo
+ * curve, turning on the ADC, and when BATT lines go out. The charger is a
+ * fake register file behind keybit_bus_read/keybit_bus_write.
+ * cc -std=c99 -Itest/stub -ICore/Inc test/batt_test.c Core/Src/batt.c -o /tmp/batt_test && /tmp/batt_test
+ */
+#include <assert.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include "batt.h"
+#include "keybit_bus.h"
+
+I2C_HandleTypeDef hi2c3;
+static uint8_t bq[0x15];
+static int writes, bus_ok = 1;
+static char sent[256];
+static uint8_t ble_level = 0xFF;
+
+int keybit_bus_read(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, uint8_t *buf, uint8_t len)
+{
+ assert(i2c == &hi2c3 && addr7 == 0x6A);
+ if (!bus_ok) return 0;
+ memcpy(buf, &bq[reg], len);
+ return 1;
+}
+
+int keybit_bus_write(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, const uint8_t *buf, uint8_t len)
+{
+ assert(i2c == &hi2c3 && addr7 == 0x6A && reg == 0x02 && len == 1);
+ bq[reg] = buf[0];
+ writes++;
+ return 1;
+}
+
+void PROTO_Send(const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(sent + strlen(sent), sizeof(sent) - strlen(sent), fmt, ap);
+ va_end(ap);
+ strcat(sent, "\n");
+}
+
+void APP_BLE_SetBattery(uint8_t pct) { ble_level = pct; }
+
+/* VBAT in mV to the REG0E code */
+static uint8_t batv(uint16_t mv) { return (uint8_t)((mv - 2304) / 20); }
+
+int main(void)
+{
+ /* curve ends, a table point, and between points */
+ assert(BATT_Percent(4300) == 100);
+ assert(BATT_Percent(4200) == 100);
+ assert(BATT_Percent(3870) == 50);
+ assert(BATT_Percent(3890) == 55);
+ assert(BATT_Percent(3300) == 0);
+ assert(BATT_Percent(3000) == 0);
+ for (uint16_t mv = 3000; mv < 4300; mv += 10) assert(BATT_Percent(mv) <= BATT_Percent(mv + 10));
+
+ /* REG0B..REG11: fast charging, VBAT 3.904 V, VBUS good */
+ uint8_t regs[7] = {0};
+ regs[0] = (2 << 3);
+ regs[3] = 80; /* 2304 + 80 * 20 = 3904 mV */
+ regs[6] = 0x80 | 24; /* VBUS_GD, 5.0 V */
+ batt_t b;
+ BATT_Decode(regs, &b);
+ assert(b.valid && b.mv == 3904 && b.chg && b.usb);
+ regs[0] = (3 << 3); /* charge done is not charging */
+ regs[6] = 0;
+ BATT_Decode(regs, &b);
+ assert(!b.chg && !b.usb);
+ regs[0] = (1 << 3); /* pre-charge is */
+ BATT_Decode(regs, &b);
+ assert(b.chg);
+
+ /* the charger at reset: ADC off, REG02 default 0x3D plus a FORCE_DPDM
+ * in progress. First poll turns the ADC on and changes nothing else. */
+ bq[0x02] = 0x3D | 0x02;
+ bq[0x0E] = batv(4024); /* on the 20 mV ADC grid */
+ bq[0x11] = 0x80;
+ BATT_Poll(0);
+ assert(writes == 1 && bq[0x02] == (0x3D | 0x40)); /* CONV_RATE on, FORCE_DPDM not re-sent */
+ assert(!BATT_Get()->valid && sent[0] == 0);
+ BATT_Poll(500); /* not a second yet */
+ assert(!BATT_Get()->valid);
+ BATT_Poll(1000); /* first poll with the ADC on still has the stale value: skipped */
+ assert(!BATT_Get()->valid && sent[0] == 0);
+ BATT_Poll(2000);
+ assert(BATT_Get()->valid && BATT_Get()->pct == 80 && BATT_Get()->usb && !BATT_Get()->chg);
+ assert(strcmp(sent, "BATT pct=80 chg=0 usb=1\n") == 0);
+ assert(ble_level == 80);
+ assert(writes == 1);
+
+ /* small drift: no line, but the BLE level follows */
+ sent[0] = 0;
+ bq[0x0E] = batv(4004); /* 78 % */
+ BATT_Poll(3000);
+ assert(sent[0] == 0 && BATT_Get()->pct < 80 && ble_level == BATT_Get()->pct);
+ bq[0x0E] = batv(3944); /* 69 %: 11 down from the last line */
+ BATT_Poll(4000);
+ assert(strcmp(sent, "BATT pct=69 chg=0 usb=1\n") == 0);
+
+ /* plugging in and charging send a line straight away */
+ sent[0] = 0;
+ bq[0x0B] = (2 << 3);
+ BATT_Poll(5000);
+ assert(strcmp(sent, "BATT pct=69 chg=1 usb=1\n") == 0);
+
+ /* the watchdog reset the charger: ADC back on, one reading skipped */
+ sent[0] = 0;
+ bq[0x02] = 0x3D;
+ BATT_Poll(6000);
+ assert(writes == 2 && (bq[0x02] & 0x40));
+ BATT_Poll(7000);
+ BATT_Poll(8000);
+ assert(BATT_Get()->valid && sent[0] == 0); /* unchanged: no line */
+
+ /* a bus error leaves the last reading alone */
+ bus_ok = 0;
+ BATT_Poll(9000);
+ assert(BATT_Get()->valid && BATT_Get()->pct == 69);
+
+ puts("batt_test: ok");
+ return 0;
+}
diff --git a/firmware/test/proto_test.c b/firmware/test/proto_test.c
index c3c782b..417d9df 100644
--- a/firmware/test/proto_test.c
+++ b/firmware/test/proto_test.c
@@ -7,6 +7,7 @@
#include <stdio.h>
#include <string.h>
#include "keymap.h"
+#include "batt.h"
#include "proto.h"
/* Two fake transports, like NUS and USB CDC. */
@@ -64,6 +65,8 @@ int KEYMAP_SetMacro(const uint8_t *uid, const uint8_t seq[][2], uint8_t len)
memcpy(a->macro, seq, (size_t)len * 2);
return 0;
}
+static batt_t batt_fake;
+const batt_t *BATT_Get(void) { return &batt_fake; }
const keyact_t *KEYMAP_Lookup(const uint8_t *uid) { int i = find(uid); return i < 0 ? NULL : &table[i].act; }
void KEYMAP_Unmap(const uint8_t *uid) { int i = find(uid); if (i >= 0) table[i] = table[--n]; }
void KEYMAP_Clear(void) { n = 0; }
@@ -90,11 +93,14 @@ int main(void)
memset(present[1].uid, 0xAB, UID_LEN);
present[1].at = 'T';
- expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=hold,macro\n");
- expect("HELLO\r\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=hold,macro\n");
- expect("HELLO\r", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=hold,macro\n"); /* terminal Enter */
+ expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro\n");
+ expect("HELLO\r\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro\n");
+ expect("HELLO\r", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro\n"); /* terminal Enter */
expect("\r\n\r\n", "");
expect("SIDES?\n", "SIDES L=1 R=0 T=1\n");
+ expect("BATT?\n", "ERR no battery reading yet\n");
+ batt_fake = (batt_t){.valid = 1, .pct = 73, .chg = 1, .usb = 1, .mv = 3970};
+ expect("BATT?\n", "BATT pct=73 chg=1 usb=1\n");
expect("KEYS?\n", "KEY+ uid=" U " at=L v=2\nKEY+ uid=ABABABABABABABABABABABAB at=T v=0\nKEYS END\n");
expect("MAP? uid=" U "\n", "MAP uid=" U " mods=00 key=00\n");
expect("MAP uid=" U " mods=02 key=04\n", "OK MAP uid=" U "\n");
@@ -196,7 +202,7 @@ int main(void)
longline[sizeof(longline) - 2] = '\n';
longline[sizeof(longline) - 1] = 0;
expect(longline, "ERR line too long\n");
- expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=hold,macro\n");
+ expect("HELLO\n", "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro\n");
/* Two transports at once: each has its own line buffer, so half a line
* on one doesn't mix with the other, and replies go back where they
@@ -207,7 +213,7 @@ int main(void)
assert(out[0] == 0);
assert(strcmp(out2, "SIDES L=1 R=0 T=1\n") == 0);
PROTO_Input(&port, (const uint8_t *)"LO\n", 3);
- assert(strcmp(out, "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=hold,macro\n") == 0);
+ assert(strcmp(out, "KEYWORD v=" KEYWORD_FW_VERSION " proto=1 caps=batt,hold,macro\n") == 0);
assert(strcmp(out2, "SIDES L=1 R=0 T=1\n") == 0);
/* Unsolicited events go to every connected port, and only those. */
diff --git a/firmware/test/stub/stm32wbxx_hal.h b/firmware/test/stub/stm32wbxx_hal.h
index d0cbf3c..8ac74aa 100644
--- a/firmware/test/stub/stm32wbxx_hal.h
+++ b/firmware/test/stub/stm32wbxx_hal.h
@@ -1,2 +1,5 @@
/* Host build stand-in: keybit_bus.h only needs the I2C handle type. */
+#ifndef STM32WBXX_HAL_H
+#define STM32WBXX_HAL_H
typedef struct { int unused; } I2C_HandleTypeDef;
+#endif