new battery detect

This commit is contained in:
zipfriis
2026-12-03 10:19:33 +01:00
parent c92da3f11a
commit d7d6568d67
+179 -50
View File
@@ -21,9 +21,8 @@
#define ENC_CLK 26
#define ENC_DT 27
#define ENC_SW 28
#define DIP1 12 // LOW = USB mode
#define DIP1 25 // LOW = USB mode
#define BAT_PIN A3
#define MAX_FILES 64
#define NAME_LEN 48
@@ -41,7 +40,7 @@ const int8_t ENC_TABLE[16] = { 0,-1,1,0, 1,0,0,-1, -1,0,0,1, 0,1,-1,0 };
void encISR() {
uint8_t s = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT);
encPos += ENC_TABLE[(encState << 2) | s];
encPos -= ENC_TABLE[(encState << 2) | s];
encState = s;
}
@@ -60,17 +59,27 @@ char curDir[128] = "/";
uint16_t wavChannels = 2;
uint32_t wavRate = 44100;
uint32_t dataTotal = 0, dataLeft = 0;
int volume = 50; // 0..100
int volume = 10; // 0..100
// 4096 bytes = 1024 stereo frames (~23 ms). Mono reads half and expands.
static int16_t buf[2048];
static const uint8_t* pendPtr = nullptr; // part of buf not yet accepted by I2S
static int pendLeft = 0;
// ---------- Battery ----------
float batVolts = 0;
int batPct = 0;
#define VBUS_PIN -1 // set to a GPIO that reads HIGH when USB is present (best option)
const float STEP_V = 0.06f; // plug/unplug voltage step that counts as an event
bool charging = false; // true = shown as "+", false = shown as "-"
bool stepCharging = false; // latched by a voltage step (no VBUS pin)
float slowV = 0; // slow reference for step detection
float chgV = 0; // filtered voltage while charging
uint32_t unplugAt = 0;
bool needReseed = false;
bool lastPlayingBat = false;
uint32_t loadChangeAt = 0;
// ---------- Battery ----------
struct BatPoint { float v; int pct; };
const BatPoint CURVE[] = {
{4.20f,100},{4.10f,90},{4.00f,80},{3.92f,70},{3.87f,60},{3.82f,50},
@@ -79,9 +88,15 @@ const BatPoint CURVE[] = {
const int CURVE_N = sizeof(CURVE) / sizeof(CURVE[0]);
float readVolts() {
uint32_t sum = 0;
for (int i = 0; i < 8; i++) sum += analogRead(BAT_PIN);
return (sum / 8.0f) * 3.3f / 4095.0f * 2.0f; // divider ratio unverified
uint16_t s[9];
for (int i = 0; i < 9; i++) s[i] = analogRead(BAT_PIN);
for (int i = 1; i < 9; i++) { // insertion sort, take median
uint16_t t = s[i];
int j = i - 1;
while (j >= 0 && s[j] > t) { s[j + 1] = s[j]; j--; }
s[j + 1] = t;
}
return s[4] * 3.3f / 4095.0f * 2.0f; // divider ratio unverified
}
int voltsToPercent(float v) {
@@ -96,6 +111,66 @@ int voltsToPercent(float v) {
return 0;
}
// Plugged-in detection:
// 1) VBUS pin if you have one
// 2) USB host enumerated us
// 3) otherwise a sudden voltage step: up = charger connected, down = removed
// Load changes (play/stop) also move the voltage, so steps are ignored for 1 s after them.
void updateBattery(bool &redraw) {
float v = readVolts();
if (playing != lastPlayingBat) { // load changed: let it settle, no step detection
lastPlayingBat = playing;
loadChangeAt = millis();
}
bool blanking = (millis() - loadChangeAt) < 1000;
bool plugged;
#if VBUS_PIN >= 0
plugged = digitalRead(VBUS_PIN);
(void)blanking;
#else
float dv = v - slowV;
if (blanking) {
slowV = v;
} else if (!stepCharging && dv > STEP_V) {
stepCharging = true; slowV = v;
} else if (stepCharging && dv < -STEP_V) {
stepCharging = false; slowV = v;
} else {
slowV += dv * 0.05f;
}
plugged = TinyUSBDevice.mounted() || stepCharging;
#endif
if (plugged != charging) {
charging = plugged;
redraw = true;
if (charging) chgV = v;
else { unplugAt = millis(); needReseed = true; } // just unplugged
}
if (charging) { // show the live (inflated) percentage with "+"
chgV += (v - chgV) * 0.2f;
int p = voltsToPercent(chgV);
if (p != batPct) { batPct = p; redraw = true; }
return;
}
if (needReseed) { // keep old number for 2 s, then re-seed honestly
if (millis() - unplugAt < 2000) return;
batVolts = v;
batPct = voltsToPercent(v);
needReseed = false;
redraw = true;
return;
}
batVolts += (v - batVolts) * 0.03f; // slow filter
int p = voltsToPercent(batVolts);
if (p < batPct) { batPct = p; redraw = true; } // ratchet: only goes down
}
// ---------- Files ----------
static bool isWav(const char* nm) {
size_t L = strlen(nm);
@@ -141,21 +216,47 @@ void scanDir() {
}
}
void startPlay();
void changeDir(const char* name) {
char leave[NAME_LEN] = "";
if (!strcmp(name, "..")) {
bool enteringFolder = strcmp(name, "..") != 0;
if (!enteringFolder) {
char* slash = strrchr(curDir, '/');
strncpy(leave, slash + 1, NAME_LEN - 1);
if (slash == curDir) curDir[1] = 0; else *slash = 0;
if (slash == curDir) curDir[1] = 0;
else *slash = 0;
} else {
if (strlen(curDir) + strlen(name) + 2 > sizeof(curDir)) return;
if (strcmp(curDir, "/")) strcat(curDir, "/");
strcat(curDir, name);
}
scanDir();
selected = 0;
for (int i = 0; i < entryCount; i++)
if (!strcmp(entries[i].name, leave)) selected = i;
if (enteringFolder) {
// Automatically start the first WAV file in this folder
for (int i = 0; i < entryCount; i++) {
if (!entries[i].isDir) {
selected = i;
startPlay();
break;
}
}
} else {
for (int i = 0; i < entryCount; i++) {
if (!strcmp(entries[i].name, leave)) {
selected = i;
break;
}
}
}
needRedraw = true;
}
// ---------- WAV ----------
@@ -221,9 +322,32 @@ void stopPlay() {
void trackEnded() {
stopPlay();
int next = selected + 1;
if (next < entryCount && !entries[next].isDir) { selected = next; startPlay(); }
// Find the next WAV file in this album folder
for (int i = selected + 1; i < entryCount; i++) {
if (!entries[i].isDir) {
selected = i;
startPlay();
needRedraw = true;
return;
}
}
// No more WAV files: album finished
playing = false;
needRedraw = true;
}
void skipNext() {
int next = -1;
for (int i = 1; i <= entryCount; i++) { // wraps, skips folders
int idx = (selected + i) % entryCount;
if (!entries[idx].isDir) { next = idx; break; }
}
if (next < 0) return;
stopPlay();
selected = next;
startPlay();
}
void playStep() {
@@ -305,8 +429,8 @@ void usbModeSetup() {
// ---------- Drawing ----------
void drawBatteryTop() {
char t[6];
snprintf(t, sizeof(t), "%d%%", batPct);
char t[7];
snprintf(t, sizeof(t), "%c%d%%", charging ? '+' : '-', batPct);
int x = 128 - (16 + 2 + 3 + (int)strlen(t) * 6);
display.drawRect(x, 0, 16, 8, SSD1306_WHITE);
display.fillRect(x + 16, 2, 2, 4, SSD1306_WHITE);
@@ -333,8 +457,10 @@ void drawScreen() {
if (sdOk && entryCount == 0) { display.setCursor(0, 20); display.print("Empty folder"); }
int top = constrain(selected - 1, 0, max(0, entryCount - 4));
for (int row = 0; row < 4; row++) {
// List: 3 rows while playing (room for the player bar), 4 rows otherwise
int rows = playing ? 3 : 4;
int top = constrain(selected - 1, 0, max(0, entryCount - rows));
for (int row = 0; row < rows; row++) {
int idx = top + row;
if (idx >= entryCount) break;
display.setCursor(0, 12 + row * 9);
@@ -344,7 +470,15 @@ void drawScreen() {
display.print(line);
}
// Now-playing bar at the bottom
if (playing && dataTotal > 0) {
display.drawFastHLine(0, 40, 128, SSD1306_WHITE); // separator
display.fillTriangle(0, 44, 0, 50, 5, 47, SSD1306_WHITE); // play icon
display.setCursor(9, 43);
char title[20];
snprintf(title, sizeof(title), "%.19s", entries[selected].name);
display.print(title);
display.drawRect(0, 56, 128, 8, SSD1306_WHITE);
int w = (int)((uint64_t)(dataTotal - dataLeft) * 124 / dataTotal);
display.fillRect(2, 58, w, 4, SSD1306_WHITE);
@@ -390,18 +524,20 @@ void setup() {
i2s.setDATA(I2S_DIN);
i2s.setBitsPerSample(16);
// Initial battery state
#if VBUS_PIN >= 0
pinMode(VBUS_PIN, INPUT);
#endif
batVolts = readVolts();
slowV = chgV = batVolts;
batPct = voltsToPercent(batVolts);
charging = stepCharging = TinyUSBDevice.mounted();
#if VBUS_PIN >= 0
charging = digitalRead(VBUS_PIN);
#endif
needReseed = false;
drawScreen();
}
void blinkScreen() {
display.clearDisplay();
display.display();
delay(300);
drawScreen();
delay(300);
}
// ---------- Loop ----------
void loop() {
@@ -421,6 +557,7 @@ void loop() {
static int lastDetent = 0;
static bool lastBtn = HIGH;
static bool longHandled = false;
static uint32_t pressStart = 0, lastBat = 0, lastDraw = 0;
bool redraw = false;
@@ -432,34 +569,35 @@ void loop() {
if (detent != lastDetent) {
int delta = detent - lastDetent;
lastDetent = detent;
if (playing) volume = constrain(volume + delta * 2, 0, 100);
else if (entryCount > 0) selected = constrain(selected + delta, 0, entryCount - 1);
if (playing) volume = constrain(volume - delta * 2, 0, 100);
else if (entryCount > 0) selected = ((selected + delta) % entryCount + entryCount) % entryCount;
redraw = true;
}
// Button: enter folder / play / stop
// Encoder button: short = enter folder / play / stop, long (while playing) = next song
bool btn = digitalRead(ENC_SW);
if (btn == LOW && lastBtn == HIGH) pressStart = millis();
if (btn == HIGH && lastBtn == LOW && millis() - pressStart > 30) {
if (btn == LOW && lastBtn == HIGH) { pressStart = millis(); longHandled = false; }
if (btn == LOW && playing && !longHandled && millis() - pressStart >= 600) {
longHandled = true;
skipNext();
redraw = true;
}
if (btn == HIGH && lastBtn == LOW && !longHandled && millis() - pressStart > 30) {
if (playing) stopPlay();
else if (entryCount > 0) {
if (entries[selected].isDir) changeDir(entries[selected].name);
else {
startPlay();
blinkScreen();
}
else startPlay();
}
redraw = true;
}
lastBtn = btn;
// Battery once per second (low-pass filtered)
if (millis() - lastBat >= 1000) {
// Battery 4x per second (charger-aware, ratcheted)
if (millis() - lastBat >= 250) {
lastBat = millis();
batVolts += (readVolts() - batVolts) * 0.2f;
int old = batPct;
batPct = voltsToPercent(batVolts);
if (batPct != old) redraw = true;
updateBattery(redraw);
}
// Progress bar refresh (slow, so the OLED doesn't steal audio time)
@@ -471,13 +609,4 @@ void loop() {
lastDraw = millis();
drawScreen();
}
static unsigned long lastBlink = 0;
static bool ledState = false;
if (millis() - lastBlink >= 500) {
lastBlink = millis();
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
}