Compare commits

...
2 Commits
Author SHA1 Message Date
zipfriis d7d6568d67 new battery detect 2026-12-03 10:19:33 +01:00
zipfriis c92da3f11a simple player 2026-11-30 14:09:58 +01:00
2 changed files with 336 additions and 330 deletions
+8 -3
View File
@@ -4,11 +4,16 @@ board = adafruit_feather
framework = arduino framework = arduino
board_build.core = earlephilhower board_build.core = earlephilhower
monitor_speed = 115200 monitor_speed = 115200
build_flags = -DUSE_TINYUSB build_unflags = -Os
build_flags =
-DUSE_TINYUSB
-O2
lib_deps = lib_deps =
adafruit/Adafruit GFX Library adafruit/Adafruit GFX Library
adafruit/Adafruit SSD1306 adafruit/Adafruit SSD1306
adafruit/Adafruit BusIO adafruit/Adafruit BusIO
adafruit/Adafruit TinyUSB Library adafruit/Adafruit TinyUSB Library
adafruit/SdFat - Adafruit Fork adafruit/SdFat - Adafruit Fork
https://github.com/pschatzmann/arduino-libhelix
board_build.f_cpu = 200000000L
+328 -327
View File
@@ -1,3 +1,5 @@
// RP2040 WAV-only player (16-bit PCM, mono or stereo)
// Board: arduino-pico (earlephilhower)
#include <Arduino.h> #include <Arduino.h>
#include <SPI.h> #include <SPI.h>
#include <SdFat.h> #include <SdFat.h>
@@ -5,108 +7,96 @@
#include <I2S.h> #include <I2S.h>
#include <Adafruit_GFX.h> #include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h> #include <Adafruit_SSD1306.h>
#define DR_FLAC_IMPLEMENTATION
#define DR_FLAC_NO_STDIO
#define DR_FLAC_NO_OGG
#define DR_FLAC_NO_CRC // faster decoding, we don't need integrity checks
#include "dr_flac.h"
// ---------- Pins ---------- // ---------- Pins ----------
// OLED on SPI1 (header pins SCK / MO)
#define OLED_CS 24 #define OLED_CS 24
#define OLED_DC 6 #define OLED_DC 6
#define OLED_RST 5 #define OLED_RST 5
// SD card on SPI0 (on-board slot)
#define SD_SCK 18 #define SD_SCK 18
#define SD_MOSI 19 #define SD_MOSI 19
#define SD_MISO 20 #define SD_MISO 20
#define SD_CS 23 #define SD_CS 23
// PCM5100 (I2S): DIN = 9, BCK = 10, WSEL/LRCK = 11 (BCK + 1) #define I2S_DIN 9 // LRCK = BCK + 1 = GPIO11
#define I2S_DIN 9
#define I2S_BCK 10 #define I2S_BCK 10
// Encoder
#define ENC_CLK 26 #define ENC_CLK 26
#define ENC_DT 27 #define ENC_DT 27
#define ENC_SW 28 #define ENC_SW 28
// DIP switch 1: ON (LOW) = USB mode #define DIP1 25 // LOW = USB mode
#define DIP1 12
// Battery
#define BAT_PIN A3 #define BAT_PIN A3
#define SAMPLES 16
#define NUM_MIN 0
#define NUM_MAX 999
#define MAX_FILES 64 #define MAX_FILES 64
#define NAME_LEN 64 #define NAME_LEN 48
#define LONG_MS 600
// ---------- Objects ---------- // ---------- Objects ----------
Adafruit_SSD1306 display(128, 64, &SPI1, OLED_DC, OLED_RST, OLED_CS); Adafruit_SSD1306 display(128, 64, &SPI1, OLED_DC, OLED_RST, OLED_CS, 8000000UL);
I2S i2s(OUTPUT); I2S i2s(OUTPUT);
SdFat sd; SdFat sd;
File32 wavFile;
Adafruit_USBD_MSC usb_msc; Adafruit_USBD_MSC usb_msc;
// ---------- Encoder ---------- // ---------- Encoder ----------
volatile int encPos = 0; volatile int encPos = 0;
volatile uint8_t encState = 0; volatile uint8_t encState = 0;
const int8_t ENC_TABLE[16] = { const int8_t ENC_TABLE[16] = { 0,-1,1,0, 1,0,0,-1, -1,0,0,1, 0,1,-1,0 };
0, -1, 1, 0,
1, 0, 0, -1,
-1, 0, 0, 1,
0, 1, -1, 0
};
void encISR() { void encISR() {
uint8_t newState = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT); uint8_t s = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT);
encPos += ENC_TABLE[(encState << 2) | newState]; encPos -= ENC_TABLE[(encState << 2) | s];
encState = newState; encState = s;
} }
// ---------- App state ---------- // ---------- State ----------
bool usbMode = false; bool usbMode = false;
int screenId = 0; // 0 player, 1 battery, 2 number bool sdOk = false;
int number = 0; bool playing = false;
float batVolts = 0; bool needRedraw = true;
int batPct = 0;
struct Entry { char name[NAME_LEN]; bool isDir; }; struct Entry { char name[NAME_LEN]; bool isDir; };
Entry entries[MAX_FILES]; Entry entries[MAX_FILES];
int entryCount = 0; int entryCount = 0;
char curDir[128] = "/"; // "/" or "/Album" or "/Artist/Album"
int selected = 0; int selected = 0;
bool sdOk = false; char curDir[128] = "/";
enum { DEC_NONE, DEC_WAV, DEC_FLAC };
int decType = DEC_NONE;
drflac* flac = nullptr;
bool needRedraw = false;
// 1. global
File32 wavFile;
bool playing = false; // was: FsFile wavFile;bool playing = false;
uint16_t wavChannels = 2; uint16_t wavChannels = 2;
uint32_t wavRate = 44100; uint32_t wavRate = 44100;
uint32_t dataTotal = 0; uint32_t dataTotal = 0, dataLeft = 0;
uint32_t dataLeft = 0; int volume = 10; // 0..100
int volume = 50; // 0..100
int16_t inBuf[2048]; // 4096 bytes = 1024 stereo frames (~23 ms). Mono reads half and expands.
int16_t outBuf[4096]; static int16_t buf[2048];
static const uint8_t* pendPtr = nullptr; // part of buf not yet accepted by I2S
static int pendLeft = 0;
// ---------- Battery ---------- // ---------- 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;
struct BatPoint { float v; int pct; }; struct BatPoint { float v; int pct; };
const BatPoint CURVE[] = { const BatPoint CURVE[] = {
{4.20f, 100}, {4.10f, 90}, {4.00f, 80}, {3.92f, 70}, {3.87f, 60}, {4.20f,100},{4.10f,90},{4.00f,80},{3.92f,70},{3.87f,60},{3.82f,50},
{3.82f, 50}, {3.79f, 40}, {3.75f, 30}, {3.70f, 20}, {3.60f, 10}, {3.79f,40},{3.75f,30},{3.70f,20},{3.60f,10},{3.50f,5},{3.30f,0}
{3.50f, 5}, {3.30f, 0}
}; };
const int CURVE_N = sizeof(CURVE) / sizeof(CURVE[0]); const int CURVE_N = sizeof(CURVE) / sizeof(CURVE[0]);
float readVolts() { float readVolts() {
uint32_t sum = 0; uint16_t s[9];
for (int i = 0; i < SAMPLES; i++) sum += analogRead(BAT_PIN); for (int i = 0; i < 9; i++) s[i] = analogRead(BAT_PIN);
return (sum / (float)SAMPLES) * 3.3f / 4095.0f * 2.0f; // divider unverified 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) { int voltsToPercent(float v) {
@@ -114,99 +104,162 @@ int voltsToPercent(float v) {
if (v <= CURVE[CURVE_N - 1].v) return 0; if (v <= CURVE[CURVE_N - 1].v) return 0;
for (int i = 0; i < CURVE_N - 1; i++) { for (int i = 0; i < CURVE_N - 1; i++) {
if (v <= CURVE[i].v && v > CURVE[i + 1].v) { if (v <= CURVE[i].v && v > CURVE[i + 1].v) {
float frac = (v - CURVE[i + 1].v) / (CURVE[i].v - CURVE[i + 1].v); float f = (v - CURVE[i + 1].v) / (CURVE[i].v - CURVE[i + 1].v);
return CURVE[i + 1].pct + (int)(frac * (CURVE[i].pct - CURVE[i + 1].pct) + 0.5f); return CURVE[i + 1].pct + (int)(f * (CURVE[i].pct - CURVE[i + 1].pct) + 0.5f);
} }
} }
return 0; 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();
// Small battery icon + percentage, top-right, shown on every screen if (playing != lastPlayingBat) { // load changed: let it settle, no step detection
void drawBatteryTop() { lastPlayingBat = playing;
char t[6]; loadChangeAt = millis();
snprintf(t, sizeof(t), "%d%%", batPct); }
int tw = strlen(t) * 6; // 6 px per char at text size 1 bool blanking = (millis() - loadChangeAt) < 1000;
int total = 16 + 2 + 3 + tw; // body + nub + gap + text
int x = 128 - total;
display.drawRect(x, 0, 16, 8, SSD1306_WHITE); // body bool plugged;
display.fillRect(x + 16, 2, 2, 4, SSD1306_WHITE); // nub #if VBUS_PIN >= 0
int w = map(constrain(batPct, 0, 100), 0, 100, 0, 12); plugged = digitalRead(VBUS_PIN);
display.fillRect(x + 2, 2, w, 4, SSD1306_WHITE); // fill level (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
display.setTextSize(1); if (plugged != charging) {
display.setCursor(x + 21, 0); charging = plugged;
display.print(t); 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
} }
static bool hasExt(const char* nm, const char* ext) { // ---------- Files ----------
size_t L = strlen(nm), e = strlen(ext); static bool isWav(const char* nm) {
return L > e && strcasecmp(nm + L - e, ext) == 0; size_t L = strlen(nm);
return L > 4 && strcasecmp(nm + L - 4, ".wav") == 0;
} }
static bool isFlac(const char* nm) { return hasExt(nm, ".flac"); }
static bool isAudio(const char* nm) { return isFlac(nm) || hasExt(nm, ".wav"); }
static bool entryLess(const Entry& a, const Entry& b) { static bool entryLess(const Entry& a, const Entry& b) {
if (a.isDir != b.isDir) return a.isDir; // folders first if (a.isDir != b.isDir) return a.isDir;
return strcasecmp(a.name, b.name) < 0; // then A-Z return strcasecmp(a.name, b.name) < 0;
} }
void scanDir() { void scanDir() {
entryCount = 0; entryCount = 0;
if (strcmp(curDir, "/") != 0) { // ".." entry when not in root if (strcmp(curDir, "/") != 0) {
strcpy(entries[0].name, ".."); strcpy(entries[0].name, "..");
entries[0].isDir = true; entries[0].isDir = true;
entryCount = 1; entryCount = 1;
} }
int first = entryCount; int first = entryCount;
File32 dir; File32 dir, f;
if (!dir.open(curDir)) return; if (!dir.open(curDir)) return;
File32 f;
while (entryCount < MAX_FILES && f.openNext(&dir, O_RDONLY)) { while (entryCount < MAX_FILES && f.openNext(&dir, O_RDONLY)) {
char nm[NAME_LEN]; char nm[NAME_LEN];
size_t n = f.getName(nm, sizeof(nm)); size_t n = f.getName(nm, sizeof(nm));
bool d = f.isDir(); bool d = f.isDir();
f.close(); f.close();
if (n == 0 || nm[0] == '.') continue; // too long / hidden if (n == 0 || nm[0] == '.') continue;
if (d && !strcasecmp(nm, "System Volume Information")) continue; if (d && !strcasecmp(nm, "System Volume Information")) continue;
if (d || isAudio(nm)) { if (d || isWav(nm)) {
strncpy(entries[entryCount].name, nm, NAME_LEN - 1); strcpy(entries[entryCount].name, nm);
entries[entryCount].name[NAME_LEN - 1] = 0;
entries[entryCount].isDir = d; entries[entryCount].isDir = d;
entryCount++; entryCount++;
} }
} }
dir.close(); dir.close();
// insertion sort (keeps ".." on top) for (int i = first + 1; i < entryCount; i++) { // insertion sort
for (int i = first + 1; i < entryCount; i++) { Entry t = entries[i];
Entry tmp = entries[i];
int j = i - 1; int j = i - 1;
while (j >= first && entryLess(tmp, entries[j])) { entries[j + 1] = entries[j]; j--; } while (j >= first && entryLess(t, entries[j])) { entries[j + 1] = entries[j]; j--; }
entries[j + 1] = tmp; entries[j + 1] = t;
} }
} }
void startPlay();
void changeDir(const char* name) { void changeDir(const char* name) {
char leaveName[NAME_LEN] = ""; char leave[NAME_LEN] = "";
if (!strcmp(name, "..")) { bool enteringFolder = strcmp(name, "..") != 0;
if (!enteringFolder) {
char* slash = strrchr(curDir, '/'); char* slash = strrchr(curDir, '/');
strncpy(leaveName, slash + 1, NAME_LEN - 1); // remember where we came from strncpy(leave, slash + 1, NAME_LEN - 1);
leaveName[NAME_LEN - 1] = 0;
if (slash == curDir) curDir[1] = 0; else *slash = 0; if (slash == curDir) curDir[1] = 0;
else *slash = 0;
} else { } else {
if (strlen(curDir) + strlen(name) + 2 > sizeof(curDir)) return; if (strlen(curDir) + strlen(name) + 2 > sizeof(curDir)) return;
if (strcmp(curDir, "/")) strcat(curDir, "/"); if (strcmp(curDir, "/")) strcat(curDir, "/");
strcat(curDir, name); strcat(curDir, name);
} }
scanDir(); scanDir();
selected = 0; selected = 0;
for (int i = 0; i < entryCount; i++)
if (!strcmp(entries[i].name, leaveName)) 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 ----------
static uint32_t rd32(const uint8_t* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24); } static uint32_t rd32(const uint8_t* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24); }
static uint16_t rd16(const uint8_t* p) { return p[0] | (p[1] << 8); } static uint16_t rd16(const uint8_t* p) { return p[0] | (p[1] << 8); }
@@ -224,6 +277,7 @@ bool openWav(const char* path) {
uint8_t ch[8]; uint8_t ch[8];
if (wavFile.read(ch, 8) != 8) { wavFile.close(); return false; } if (wavFile.read(ch, 8) != 8) { wavFile.close(); return false; }
uint32_t size = rd32(ch + 4); uint32_t size = rd32(ch + 4);
if (!memcmp(ch, "fmt ", 4)) { if (!memcmp(ch, "fmt ", 4)) {
uint8_t fmt[16]; uint8_t fmt[16];
if (size < 16 || wavFile.read(fmt, 16) != 16) { wavFile.close(); return false; } if (size < 16 || wavFile.read(fmt, 16) != 16) { wavFile.close(); return false; }
@@ -231,64 +285,29 @@ bool openWav(const char* path) {
wavChannels = rd16(fmt + 2); wavChannels = rd16(fmt + 2);
wavRate = rd32(fmt + 4); wavRate = rd32(fmt + 4);
uint16_t bits = rd16(fmt + 14); uint16_t bits = rd16(fmt + 14);
if (format != 1 || bits != 16 || wavChannels < 1 || wavChannels > 2) { bool fmtOk = (format == 1 || format == 0xFFFE); // PCM or extensible
wavFile.close(); return false; // only 16-bit PCM mono/stereo if (!fmtOk || bits != 16 || wavChannels < 1 || wavChannels > 2) {
wavFile.close(); return false;
} }
gotFmt = true; gotFmt = true;
if (size > 16) wavFile.seekSet(wavFile.position() + (size - 16)); if (size > 16) wavFile.seekSet(wavFile.curPosition() + (size - 16));
} else if (!memcmp(ch, "data", 4)) { } else if (!memcmp(ch, "data", 4)) {
if (!gotFmt) { wavFile.close(); return false; } if (!gotFmt) { wavFile.close(); return false; }
uint32_t avail = wavFile.fileSize() - wavFile.curPosition();
if (size == 0 || size > avail) size = avail; // bad/streamed header
dataTotal = dataLeft = size; dataTotal = dataLeft = size;
return true; return true;
} else { } else {
wavFile.seekSet(wavFile.position() + size + (size & 1)); wavFile.seekSet(wavFile.curPosition() + size + (size & 1));
} }
} }
} }
static size_t flacRead(void* ud, void* buf, size_t n) {
int r = ((File32*)ud)->read(buf, n);
return r > 0 ? (size_t)r : 0;
}
static drflac_bool32 flacSeek(void* ud, int off, drflac_seek_origin origin) {
File32* f = (File32*)ud;
bool ok;
if (origin == DRFLAC_SEEK_SET) ok = f->seekSet(off);
else if (origin == DRFLAC_SEEK_CUR) ok = f->seekCur(off);
else ok = f->seekEnd(off);
return ok ? DRFLAC_TRUE : DRFLAC_FALSE;
}
static drflac_bool32 flacTell(void* ud, drflac_int64* pCursor) {
*pCursor = (drflac_int64)((File32*)ud)->curPosition();
return DRFLAC_TRUE;
}
bool openFlac(const char* path) {
wavFile = sd.open(path, O_RDONLY); // reuse the same file handle
if (!wavFile) return false;
flac = drflac_open(flacRead, flacSeek, flacTell, &wavFile, NULL);
if (!flac) { wavFile.close(); return false; }
if (flac->channels < 1 || flac->channels > 2) {
drflac_close(flac); flac = nullptr; wavFile.close(); return false;
}
wavChannels = flac->channels;
wavRate = flac->sampleRate;
dataTotal = dataLeft = (uint32_t)flac->totalPCMFrameCount; // frames, only used as a ratio
return true;
}
void startPlay() { void startPlay() {
if (!sdOk || entryCount == 0 || entries[selected].isDir) return; if (!sdOk || entryCount == 0 || entries[selected].isDir) return;
const char* name = entries[selected].name;
char path[192]; char path[192];
snprintf(path, sizeof(path), "%s%s%s", curDir, strcmp(curDir, "/") ? "/" : "", name); snprintf(path, sizeof(path), "%s%s%s", curDir, strcmp(curDir, "/") ? "/" : "", entries[selected].name);
if (!openWav(path)) { Serial.printf("open failed: %s\n", path); return; }
bool flacFile = isFlac(name);
if (!(flacFile ? openFlac(path) : openWav(path))) return;
decType = flacFile ? DEC_FLAC : DEC_WAV;
i2s.end(); i2s.end();
i2s.begin(wavRate); i2s.begin(wavRate);
playing = true; playing = true;
@@ -296,66 +315,92 @@ void startPlay() {
void stopPlay() { void stopPlay() {
playing = false; playing = false;
if (flac) { drflac_close(flac); flac = nullptr; } pendLeft = 0;
if (wavFile) wavFile.close(); if (wavFile) wavFile.close();
decType = DEC_NONE;
i2s.end(); i2s.end();
} }
// Track finished: continue with the next file in the folder (album behaviour)
void trackEnded() { void trackEnded() {
stopPlay(); 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; 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() { void playStep() {
if (!playing) return; if (!playing) return;
int samples; // interleaved int16 samples now in inBuf // Finish handing the previous chunk to I2S before reading a new one.
if (decType == DEC_FLAC) { // Writes only what fits, so no samples are ever silently dropped.
uint32_t frames = (uint32_t)drflac_read_pcm_frames_s16(flac, 1024, inBuf); if (pendLeft > 0) {
if (frames == 0) { trackEnded(); return; } int room = i2s.availableForWrite() & ~3; // whole stereo frames
dataLeft = frames > dataLeft ? 0 : dataLeft - frames; if (room <= 0) return;
samples = frames * wavChannels; int n = pendLeft < room ? pendLeft : room;
} else { size_t w = i2s.write(pendPtr, n);
if (dataLeft == 0) { trackEnded(); return; } pendPtr += w;
uint32_t want = min<uint32_t>(dataLeft, wavChannels == 2 ? sizeof(inBuf) : sizeof(inBuf) / 2); pendLeft -= (int)w;
int n = wavFile.read((uint8_t*)inBuf, want); return;
if (n <= 0) { trackEnded(); return; }
dataLeft -= n;
samples = n / 2;
} }
uint32_t gain = (uint32_t)volume * volume; // 0..10000 if (dataLeft == 0) { trackEnded(); return; }
int outSamples;
// stereo: read up to 4096 bytes; mono: read 2048 into the first half, expand after
uint32_t maxBytes = (wavChannels == 2) ? sizeof(buf) : sizeof(buf) / 2;
uint32_t want = dataLeft < maxBytes ? dataLeft : maxBytes;
int n = wavFile.read((uint8_t*)buf, want);
if (n <= 0) { trackEnded(); return; }
dataLeft -= n;
int samples = n / 2;
// Q15 gain, squared curve for a more natural volume feel
int32_t gain = ((int32_t)volume * volume * 32768) / 10000;
int outBytes;
if (wavChannels == 2) { if (wavChannels == 2) {
for (int i = 0; i < samples; i++) for (int i = 0; i < samples; i++) buf[i] = (int16_t)(((int32_t)buf[i] * gain) >> 15);
outBuf[i] = (int16_t)(((int32_t)inBuf[i] * (int32_t)gain) / 10000); outBytes = samples * 2;
outSamples = samples;
} else { } else {
for (int i = 0; i < samples; i++) { for (int i = samples - 1; i >= 0; i--) { // expand backwards, in place
int16_t s = (int16_t)(((int32_t)inBuf[i] * (int32_t)gain) / 10000); int16_t s = (int16_t)(((int32_t)buf[i] * gain) >> 15);
outBuf[2 * i] = s; buf[2 * i] = s;
outBuf[2 * i + 1] = s; buf[2 * i + 1] = s;
} }
outSamples = samples * 2; outBytes = samples * 4;
} }
i2s.write((const uint8_t*)outBuf, outSamples * 2); // blocks until queued pendPtr = (const uint8_t*)buf; // written on the next passes
pendLeft = outBytes;
} }
// ---------- USB mass storage (SD as USB drive) ---------- // ---------- USB mass storage ----------
int32_t msc_read_cb(uint32_t lba, void* buf, uint32_t bufsize) { int32_t msc_read_cb(uint32_t lba, void* b, uint32_t sz) {
return sd.card()->readSectors(lba, (uint8_t*)buf, bufsize / 512) ? (int32_t)bufsize : -1; return sd.card()->readSectors(lba, (uint8_t*)b, sz / 512) ? (int32_t)sz : -1;
} }
int32_t msc_write_cb(uint32_t lba, uint8_t* buf, uint32_t bufsize) { int32_t msc_write_cb(uint32_t lba, uint8_t* b, uint32_t sz) {
return sd.card()->writeSectors(lba, buf, bufsize / 512) ? (int32_t)bufsize : -1; return sd.card()->writeSectors(lba, b, sz / 512) ? (int32_t)sz : -1;
}
void msc_flush_cb() {
sd.card()->syncDevice();
sd.cacheClear();
} }
void msc_flush_cb() { sd.card()->syncDevice(); sd.cacheClear(); }
void usbModeSetup() { void usbModeSetup() {
usb_msc.setID("Adalogger", "SD Card", "1.0"); usb_msc.setID("Adalogger", "SD Card", "1.0");
@@ -363,7 +408,7 @@ void usbModeSetup() {
usb_msc.setUnitReady(false); usb_msc.setUnitReady(false);
usb_msc.begin(); usb_msc.begin();
bool ok = sd.begin(SD_CS, SD_SCK_MHZ(25)); bool ok = sd.begin(SdSpiConfig(SD_CS, SHARED_SPI, SD_SCK_MHZ(25)));
if (ok) { if (ok) {
usb_msc.setCapacity(sd.card()->sectorCount(), 512); usb_msc.setCapacity(sd.card()->sectorCount(), 512);
usb_msc.setUnitReady(true); usb_msc.setUnitReady(true);
@@ -383,151 +428,120 @@ void usbModeSetup() {
} }
// ---------- Drawing ---------- // ---------- Drawing ----------
void drawBatteryIcon(int x, int y, int pct) { void drawBatteryTop() {
display.drawRect(x, y, 26, 12, SSD1306_WHITE); char t[7];
display.fillRect(x + 26, y + 3, 3, 6, SSD1306_WHITE); snprintf(t, sizeof(t), "%c%d%%", charging ? '+' : '-', batPct);
int w = map(constrain(pct, 0, 100), 0, 100, 0, 22); int x = 128 - (16 + 2 + 3 + (int)strlen(t) * 6);
display.fillRect(x + 2, y + 2, w, 8, SSD1306_WHITE); display.drawRect(x, 0, 16, 8, SSD1306_WHITE);
} display.fillRect(x + 16, 2, 2, 4, SSD1306_WHITE);
display.fillRect(x + 2, 2, map(constrain(batPct, 0, 100), 0, 100, 0, 12), 4, SSD1306_WHITE);
void drawPlayerScreen() { display.setCursor(x + 21, 0);
display.setTextSize(1); display.print(t);
display.setCursor(0, 0);
if (!sdOk) display.print("No SD card");
else if (playing) {
display.print("Playing ");
display.print(selected + 1);
display.print('/');
display.print(entryCount);
} else if (!strcmp(curDir, "/")) {
display.print("SD root");
} else {
const char* base = strrchr(curDir, '/') + 1; // album name
char hdr[13];
strncpy(hdr, base, 12);
hdr[12] = 0;
display.print(hdr);
}
if (playing) {
display.setCursor(0, 48);
display.print("Vol ");
display.print(volume);
}
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++) {
int idx = top + row;
if (idx >= entryCount) break;
display.setCursor(0, 12 + row * 9);
display.print(idx == selected ? "> " : " ");
char line[20];
if (entries[idx].isDir) snprintf(line, sizeof(line), "/%.18s", entries[idx].name);
else snprintf(line, sizeof(line), "%.19s", entries[idx].name);
display.print(line);
}
if (playing && dataTotal > 0) {
display.drawRect(0, 56, 128, 8, SSD1306_WHITE);
uint32_t done = dataTotal - dataLeft;
int w = (int)((uint64_t)done * 124 / dataTotal);
display.fillRect(2, 58, w, 4, SSD1306_WHITE);
}
}
void drawBatteryScreen() {
display.setTextSize(1);
display.setCursor(0, 0);
display.print("Battery");
display.setTextSize(3);
display.setCursor(0, 18);
display.print(batPct);
display.print('%');
display.setTextSize(1);
display.setCursor(0, 54);
display.print(batVolts, 2);
display.print(" V");
drawBatteryIcon(96, 52, batPct);
}
void drawNumberScreen() {
display.setTextSize(1);
display.setCursor(0, 0);
display.print("Number");
char buf[8];
snprintf(buf, sizeof(buf), "%d", number);
display.setTextSize(4);
display.setCursor((128 - (int)strlen(buf) * 24) / 2, 20);
display.print(buf);
display.drawRect(0, 56, 128, 8, SSD1306_WHITE);
display.fillRect(2, 58, map(number, NUM_MIN, NUM_MAX, 0, 124), 4, SSD1306_WHITE);
} }
void drawScreen() { void drawScreen() {
display.clearDisplay(); display.clearDisplay();
display.setTextColor(SSD1306_WHITE); display.setTextColor(SSD1306_WHITE);
if (screenId == 0) drawPlayerScreen(); display.setTextSize(1);
else if (screenId == 1) drawBatteryScreen();
else drawNumberScreen(); display.setCursor(0, 0);
drawBatteryTop(); // <-- on every page if (!sdOk) display.print("No SD card");
else if (playing) display.printf("V%d %lu %uch", volume, (unsigned long)wavRate, (unsigned)wavChannels);
else if (!strcmp(curDir, "/")) display.print("SD root");
else {
char hdr[11];
strncpy(hdr, strrchr(curDir, '/') + 1, 10);
hdr[10] = 0;
display.print(hdr);
}
if (sdOk && entryCount == 0) { display.setCursor(0, 20); display.print("Empty folder"); }
// 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);
display.print(idx == selected ? "> " : " ");
char line[20];
snprintf(line, sizeof(line), entries[idx].isDir ? "/%.18s" : "%.19s", entries[idx].name);
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);
}
drawBatteryTop();
display.display(); display.display();
} }
// ---------- Setup ---------- // ---------- Setup ----------
void setup() { void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200); Serial.begin(115200);
analogReadResolution(12); analogReadResolution(12);
pinMode(DIP1, INPUT_PULLUP); pinMode(DIP1, INPUT_PULLUP);
pinMode(ENC_CLK, INPUT_PULLUP); pinMode(ENC_CLK, INPUT_PULLUP);
pinMode(ENC_DT, INPUT_PULLUP); pinMode(ENC_DT, INPUT_PULLUP);
pinMode(ENC_SW, INPUT_PULLUP); pinMode(ENC_SW, INPUT_PULLUP);
encState = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT); encState = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT);
attachInterrupt(digitalPinToInterrupt(ENC_CLK), encISR, CHANGE); attachInterrupt(digitalPinToInterrupt(ENC_CLK), encISR, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENC_DT), encISR, CHANGE); attachInterrupt(digitalPinToInterrupt(ENC_DT), encISR, CHANGE);
// OLED on SPI1
SPI1.setSCK(14); SPI1.setSCK(14);
SPI1.setTX(15); SPI1.setTX(15);
display.begin(SSD1306_SWITCHCAPVCC); display.begin(SSD1306_SWITCHCAPVCC);
// SD on SPI0 (on-board slot)
SPI.setSCK(SD_SCK); SPI.setSCK(SD_SCK);
SPI.setTX(SD_MOSI); SPI.setTX(SD_MOSI);
SPI.setRX(SD_MISO); SPI.setRX(SD_MISO);
// DIP switch 1 ON = USB mode
delay(5); delay(5);
usbMode = (digitalRead(DIP1) == LOW); usbMode = (digitalRead(DIP1) == LOW);
if (usbMode) { if (usbMode) { usbModeSetup(); return; }
usbModeSetup();
return; // skip player setup
}
sdOk = sd.begin(SD_CS, SD_SCK_MHZ(25)); // Dedicated SPI + higher clock = much faster, steadier SD reads
Serial.println(sdOk ? "SD ok" : "SD failed"); sdOk = sd.begin(SdSpiConfig(SD_CS, DEDICATED_SPI, SD_SCK_MHZ(20)));
if (sdOk) scanDir(); // was scanFiles() if (sdOk) scanDir();
i2s.setBuffers(8, 128); // ~23 ms of audio buffered, helps FLAC avoid underruns
// I2S to PCM5100 (LRCK = BCK + 1 = GPIO11) // 8 buffers x 512 words (one word = one L/R pair) = 4096 frames, ~93 ms at 44.1 kHz
i2s.setBuffers(8, 512);
i2s.setBCLK(I2S_BCK); i2s.setBCLK(I2S_BCK);
i2s.setDATA(I2S_DIN); i2s.setDATA(I2S_DIN);
i2s.setBitsPerSample(16); i2s.setBitsPerSample(16);
// Initial battery state
#if VBUS_PIN >= 0
pinMode(VBUS_PIN, INPUT);
#endif
batVolts = readVolts(); batVolts = readVolts();
slowV = chgV = batVolts;
batPct = voltsToPercent(batVolts); batPct = voltsToPercent(batVolts);
charging = stepCharging = TinyUSBDevice.mounted();
#if VBUS_PIN >= 0
charging = digitalRead(VBUS_PIN);
#endif
needReseed = false;
drawScreen(); drawScreen();
} }
// ---------- Loop ---------- // ---------- Loop ----------
void loop() { void loop() {
// Flip the DIP switch -> reboot into the other mode // DIP flip -> reboot into the other mode
static uint32_t lastDip = 0; static uint32_t lastDip = 0;
if (millis() - lastDip > 200) { if (millis() - lastDip > 200) {
lastDip = millis(); lastDip = millis();
@@ -539,69 +553,56 @@ void loop() {
} }
} }
} }
if (usbMode) return; // TinyUSB handles the drive if (usbMode) return;
static int lastDetent = 0; static int lastDetent = 0;
static bool lastBtn = HIGH; static bool lastBtn = HIGH;
static uint32_t pressStart = 0; static bool longHandled = false;
static uint32_t lastBat = 0; static uint32_t pressStart = 0, lastBat = 0, lastDraw = 0;
static uint32_t lastDraw = 0;
bool redraw = false; bool redraw = false;
playStep(); playStep(); // keep audio fed first, every pass
// Rotation // Rotation: volume while playing, list scroll otherwise
noInterrupts(); noInterrupts(); int pos = encPos; interrupts();
int pos = encPos;
interrupts();
int detent = pos / 4; // use /2 if one click gives 2 counts int detent = pos / 4; // use /2 if one click gives 2 counts
if (detent != lastDetent) { if (detent != lastDetent) {
int delta = detent - lastDetent; int delta = detent - lastDetent;
lastDetent = detent; lastDetent = detent;
if (screenId == 0) { if (playing) volume = constrain(volume - delta * 2, 0, 100);
if (playing) volume = constrain(volume + delta * 2, 0, 100); else if (entryCount > 0) selected = ((selected + delta) % entryCount + entryCount) % entryCount;
else if (entryCount > 0) selected = constrain(selected + delta, 0, entryCount - 1); redraw = true;
redraw = true;
} else if (screenId == 2) {
number = constrain(number + delta, NUM_MIN, NUM_MAX);
redraw = true;
}
} }
// Button: short = enter folder / play / stop, long = next screen // Encoder button: short = enter folder / play / stop, long (while playing) = next song
bool btn = digitalRead(ENC_SW); bool btn = digitalRead(ENC_SW);
if (btn == LOW && lastBtn == HIGH) pressStart = millis(); if (btn == LOW && lastBtn == HIGH) { pressStart = millis(); longHandled = false; }
if (btn == HIGH && lastBtn == LOW) {
uint32_t held = millis() - pressStart; if (btn == LOW && playing && !longHandled && millis() - pressStart >= 600) {
if (held >= LONG_MS) { longHandled = true;
screenId = (screenId + 1) % 3; skipNext();
redraw = true; redraw = true;
} else if (held > 30 && screenId == 0) { }
if (playing) {
stopPlay(); if (btn == HIGH && lastBtn == LOW && !longHandled && millis() - pressStart > 30) {
} else if (entryCount > 0) { if (playing) stopPlay();
if (entries[selected].isDir) changeDir(entries[selected].name); else if (entryCount > 0) {
else startPlay(); if (entries[selected].isDir) changeDir(entries[selected].name);
} else startPlay();
redraw = true;
} }
redraw = true;
} }
lastBtn = btn; lastBtn = btn;
// Battery once per second // Battery 4x per second (charger-aware, ratcheted)
if (millis() - lastBat >= 1000) { if (millis() - lastBat >= 250) {
lastBat = millis(); lastBat = millis();
// low-pass filter so the percentage doesn't jitter updateBattery(redraw);
batVolts += (readVolts() - batVolts) * 0.2f;
int oldPct = batPct;
batPct = voltsToPercent(batVolts);
if (batPct != oldPct || screenId == 1) redraw = true;
} }
// Progress bar refresh while playing // Progress bar refresh (slow, so the OLED doesn't steal audio time)
if (playing && screenId == 0 && millis() - lastDraw >= 300) redraw = true; if (playing && millis() - lastDraw >= 500) redraw = true;
// Track or album ended on its own (set by trackEnded())
if (needRedraw) { needRedraw = false; redraw = true; } if (needRedraw) { needRedraw = false; redraw = true; }
if (redraw) { if (redraw) {