diff --git a/platformio.ini b/platformio.ini index 51b31fa..ea657f0 100644 --- a/platformio.ini +++ b/platformio.ini @@ -4,11 +4,16 @@ board = adafruit_feather framework = arduino board_build.core = earlephilhower monitor_speed = 115200 -build_flags = -DUSE_TINYUSB - +build_unflags = -Os +build_flags = + -DUSE_TINYUSB + -O2 lib_deps = adafruit/Adafruit GFX Library adafruit/Adafruit SSD1306 adafruit/Adafruit BusIO adafruit/Adafruit TinyUSB Library - adafruit/SdFat - Adafruit Fork \ No newline at end of file + adafruit/SdFat - Adafruit Fork + https://github.com/pschatzmann/arduino-libhelix + +board_build.f_cpu = 200000000L \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 5ec04de..38cfc43 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,3 +1,5 @@ +// RP2040 WAV-only player (16-bit PCM, mono or stereo) +// Board: arduino-pico (earlephilhower) #include #include #include @@ -5,108 +7,81 @@ #include #include #include -#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 ---------- -// OLED on SPI1 (header pins SCK / MO) #define OLED_CS 24 #define OLED_DC 6 #define OLED_RST 5 -// SD card on SPI0 (on-board slot) #define SD_SCK 18 #define SD_MOSI 19 #define SD_MISO 20 #define SD_CS 23 -// PCM5100 (I2S): DIN = 9, BCK = 10, WSEL/LRCK = 11 (BCK + 1) -#define I2S_DIN 9 +#define I2S_DIN 9 // LRCK = BCK + 1 = GPIO11 #define I2S_BCK 10 -// Encoder #define ENC_CLK 26 #define ENC_DT 27 #define ENC_SW 28 -// DIP switch 1: ON (LOW) = USB mode -#define DIP1 12 -// Battery +#define DIP1 12 // LOW = USB mode #define BAT_PIN A3 -#define SAMPLES 16 - -#define NUM_MIN 0 -#define NUM_MAX 999 #define MAX_FILES 64 -#define NAME_LEN 64 -#define LONG_MS 600 +#define NAME_LEN 48 // ---------- 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); SdFat sd; +File32 wavFile; Adafruit_USBD_MSC usb_msc; // ---------- Encoder ---------- volatile int encPos = 0; volatile uint8_t encState = 0; -const int8_t ENC_TABLE[16] = { - 0, -1, 1, 0, - 1, 0, 0, -1, - -1, 0, 0, 1, - 0, 1, -1, 0 -}; +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 newState = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT); - encPos += ENC_TABLE[(encState << 2) | newState]; - encState = newState; + uint8_t s = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT); + encPos += ENC_TABLE[(encState << 2) | s]; + encState = s; } -// ---------- App state ---------- +// ---------- State ---------- bool usbMode = false; -int screenId = 0; // 0 player, 1 battery, 2 number -int number = 0; -float batVolts = 0; -int batPct = 0; +bool sdOk = false; +bool playing = false; +bool needRedraw = true; struct Entry { char name[NAME_LEN]; bool isDir; }; Entry entries[MAX_FILES]; int entryCount = 0; -char curDir[128] = "/"; // "/" or "/Album" or "/Artist/Album" 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; uint32_t wavRate = 44100; -uint32_t dataTotal = 0; -uint32_t dataLeft = 0; -int volume = 50; // 0..100 +uint32_t dataTotal = 0, dataLeft = 0; +int volume = 50; // 0..100 -int16_t inBuf[2048]; -int16_t outBuf[4096]; +// 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; + +float batVolts = 0; +int batPct = 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}, {3.79f, 40}, {3.75f, 30}, {3.70f, 20}, {3.60f, 10}, - {3.50f, 5}, {3.30f, 0} + {4.20f,100},{4.10f,90},{4.00f,80},{3.92f,70},{3.87f,60},{3.82f,50}, + {3.79f,40},{3.75f,30},{3.70f,20},{3.60f,10},{3.50f,5},{3.30f,0} }; const int CURVE_N = sizeof(CURVE) / sizeof(CURVE[0]); float readVolts() { uint32_t sum = 0; - for (int i = 0; i < SAMPLES; i++) sum += analogRead(BAT_PIN); - return (sum / (float)SAMPLES) * 3.3f / 4095.0f * 2.0f; // divider unverified + for (int i = 0; i < 8; i++) sum += analogRead(BAT_PIN); + return (sum / 8.0f) * 3.3f / 4095.0f * 2.0f; // divider ratio unverified } int voltsToPercent(float v) { @@ -114,87 +89,63 @@ int voltsToPercent(float v) { if (v <= CURVE[CURVE_N - 1].v) return 0; for (int i = 0; i < CURVE_N - 1; i++) { if (v <= CURVE[i].v && v > CURVE[i + 1].v) { - float frac = (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); + float f = (v - CURVE[i + 1].v) / (CURVE[i].v - CURVE[i + 1].v); + return CURVE[i + 1].pct + (int)(f * (CURVE[i].pct - CURVE[i + 1].pct) + 0.5f); } } return 0; } - -// Small battery icon + percentage, top-right, shown on every screen -void drawBatteryTop() { - char t[6]; - snprintf(t, sizeof(t), "%d%%", batPct); - int tw = strlen(t) * 6; // 6 px per char at text size 1 - int total = 16 + 2 + 3 + tw; // body + nub + gap + text - int x = 128 - total; - - display.drawRect(x, 0, 16, 8, SSD1306_WHITE); // body - display.fillRect(x + 16, 2, 2, 4, SSD1306_WHITE); // nub - int w = map(constrain(batPct, 0, 100), 0, 100, 0, 12); - display.fillRect(x + 2, 2, w, 4, SSD1306_WHITE); // fill level - - display.setTextSize(1); - display.setCursor(x + 21, 0); - display.print(t); +// ---------- Files ---------- +static bool isWav(const char* nm) { + size_t L = strlen(nm); + return L > 4 && strcasecmp(nm + L - 4, ".wav") == 0; } -static bool hasExt(const char* nm, const char* ext) { - size_t L = strlen(nm), e = strlen(ext); - return L > e && strcasecmp(nm + L - e, ext) == 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) { - if (a.isDir != b.isDir) return a.isDir; // folders first - return strcasecmp(a.name, b.name) < 0; // then A-Z + if (a.isDir != b.isDir) return a.isDir; + return strcasecmp(a.name, b.name) < 0; } void scanDir() { entryCount = 0; - if (strcmp(curDir, "/") != 0) { // ".." entry when not in root + if (strcmp(curDir, "/") != 0) { strcpy(entries[0].name, ".."); entries[0].isDir = true; entryCount = 1; } int first = entryCount; - File32 dir; + File32 dir, f; if (!dir.open(curDir)) return; - File32 f; while (entryCount < MAX_FILES && f.openNext(&dir, O_RDONLY)) { char nm[NAME_LEN]; size_t n = f.getName(nm, sizeof(nm)); bool d = f.isDir(); 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 || isAudio(nm)) { - strncpy(entries[entryCount].name, nm, NAME_LEN - 1); - entries[entryCount].name[NAME_LEN - 1] = 0; + if (d || isWav(nm)) { + strcpy(entries[entryCount].name, nm); entries[entryCount].isDir = d; entryCount++; } } dir.close(); - // insertion sort (keeps ".." on top) - for (int i = first + 1; i < entryCount; i++) { - Entry tmp = entries[i]; + for (int i = first + 1; i < entryCount; i++) { // insertion sort + Entry t = entries[i]; int j = i - 1; - while (j >= first && entryLess(tmp, entries[j])) { entries[j + 1] = entries[j]; j--; } - entries[j + 1] = tmp; + while (j >= first && entryLess(t, entries[j])) { entries[j + 1] = entries[j]; j--; } + entries[j + 1] = t; } } void changeDir(const char* name) { - char leaveName[NAME_LEN] = ""; + char leave[NAME_LEN] = ""; if (!strcmp(name, "..")) { char* slash = strrchr(curDir, '/'); - strncpy(leaveName, slash + 1, NAME_LEN - 1); // remember where we came from - leaveName[NAME_LEN - 1] = 0; + strncpy(leave, slash + 1, NAME_LEN - 1); if (slash == curDir) curDir[1] = 0; else *slash = 0; } else { if (strlen(curDir) + strlen(name) + 2 > sizeof(curDir)) return; @@ -204,9 +155,10 @@ void changeDir(const char* name) { scanDir(); selected = 0; for (int i = 0; i < entryCount; i++) - if (!strcmp(entries[i].name, leaveName)) selected = i; + if (!strcmp(entries[i].name, leave)) selected = i; } +// ---------- WAV ---------- 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); } @@ -224,6 +176,7 @@ bool openWav(const char* path) { uint8_t ch[8]; if (wavFile.read(ch, 8) != 8) { wavFile.close(); return false; } uint32_t size = rd32(ch + 4); + if (!memcmp(ch, "fmt ", 4)) { uint8_t fmt[16]; if (size < 16 || wavFile.read(fmt, 16) != 16) { wavFile.close(); return false; } @@ -231,64 +184,29 @@ bool openWav(const char* path) { wavChannels = rd16(fmt + 2); wavRate = rd32(fmt + 4); uint16_t bits = rd16(fmt + 14); - if (format != 1 || bits != 16 || wavChannels < 1 || wavChannels > 2) { - wavFile.close(); return false; // only 16-bit PCM mono/stereo + bool fmtOk = (format == 1 || format == 0xFFFE); // PCM or extensible + if (!fmtOk || bits != 16 || wavChannels < 1 || wavChannels > 2) { + wavFile.close(); return false; } 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)) { 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; return true; } 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() { if (!sdOk || entryCount == 0 || entries[selected].isDir) return; - const char* name = entries[selected].name; char path[192]; - snprintf(path, sizeof(path), "%s%s%s", curDir, strcmp(curDir, "/") ? "/" : "", name); - - bool flacFile = isFlac(name); - if (!(flacFile ? openFlac(path) : openWav(path))) return; - decType = flacFile ? DEC_FLAC : DEC_WAV; + snprintf(path, sizeof(path), "%s%s%s", curDir, strcmp(curDir, "/") ? "/" : "", entries[selected].name); + if (!openWav(path)) { Serial.printf("open failed: %s\n", path); return; } i2s.end(); i2s.begin(wavRate); playing = true; @@ -296,13 +214,11 @@ void startPlay() { void stopPlay() { playing = false; - if (flac) { drflac_close(flac); flac = nullptr; } + pendLeft = 0; if (wavFile) wavFile.close(); - decType = DEC_NONE; i2s.end(); } -// Track finished: continue with the next file in the folder (album behaviour) void trackEnded() { stopPlay(); int next = selected + 1; @@ -313,49 +229,54 @@ void trackEnded() { void playStep() { if (!playing) return; - int samples; // interleaved int16 samples now in inBuf - if (decType == DEC_FLAC) { - uint32_t frames = (uint32_t)drflac_read_pcm_frames_s16(flac, 1024, inBuf); - if (frames == 0) { trackEnded(); return; } - dataLeft = frames > dataLeft ? 0 : dataLeft - frames; - samples = frames * wavChannels; - } else { - if (dataLeft == 0) { trackEnded(); return; } - uint32_t want = min(dataLeft, wavChannels == 2 ? sizeof(inBuf) : sizeof(inBuf) / 2); - int n = wavFile.read((uint8_t*)inBuf, want); - if (n <= 0) { trackEnded(); return; } - dataLeft -= n; - samples = n / 2; + // Finish handing the previous chunk to I2S before reading a new one. + // Writes only what fits, so no samples are ever silently dropped. + if (pendLeft > 0) { + int room = i2s.availableForWrite() & ~3; // whole stereo frames + if (room <= 0) return; + int n = pendLeft < room ? pendLeft : room; + size_t w = i2s.write(pendPtr, n); + pendPtr += w; + pendLeft -= (int)w; + return; } - uint32_t gain = (uint32_t)volume * volume; // 0..10000 - int outSamples; + if (dataLeft == 0) { trackEnded(); return; } + + // 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) { - for (int i = 0; i < samples; i++) - outBuf[i] = (int16_t)(((int32_t)inBuf[i] * (int32_t)gain) / 10000); - outSamples = samples; + for (int i = 0; i < samples; i++) buf[i] = (int16_t)(((int32_t)buf[i] * gain) >> 15); + outBytes = samples * 2; } else { - for (int i = 0; i < samples; i++) { - int16_t s = (int16_t)(((int32_t)inBuf[i] * (int32_t)gain) / 10000); - outBuf[2 * i] = s; - outBuf[2 * i + 1] = s; + for (int i = samples - 1; i >= 0; i--) { // expand backwards, in place + int16_t s = (int16_t)(((int32_t)buf[i] * gain) >> 15); + buf[2 * i] = 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) ---------- -int32_t msc_read_cb(uint32_t lba, void* buf, uint32_t bufsize) { - return sd.card()->readSectors(lba, (uint8_t*)buf, bufsize / 512) ? (int32_t)bufsize : -1; +// ---------- USB mass storage ---------- +int32_t msc_read_cb(uint32_t lba, void* b, uint32_t sz) { + 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) { - return sd.card()->writeSectors(lba, buf, bufsize / 512) ? (int32_t)bufsize : -1; -} -void msc_flush_cb() { - sd.card()->syncDevice(); - sd.cacheClear(); +int32_t msc_write_cb(uint32_t lba, uint8_t* b, uint32_t sz) { + return sd.card()->writeSectors(lba, b, sz / 512) ? (int32_t)sz : -1; } +void msc_flush_cb() { sd.card()->syncDevice(); sd.cacheClear(); } void usbModeSetup() { usb_msc.setID("Adalogger", "SD Card", "1.0"); @@ -363,7 +284,7 @@ void usbModeSetup() { usb_msc.setUnitReady(false); 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) { usb_msc.setCapacity(sd.card()->sectorCount(), 512); usb_msc.setUnitReady(true); @@ -383,41 +304,35 @@ void usbModeSetup() { } // ---------- Drawing ---------- -void drawBatteryIcon(int x, int y, int pct) { - display.drawRect(x, y, 26, 12, SSD1306_WHITE); - display.fillRect(x + 26, y + 3, 3, 6, SSD1306_WHITE); - int w = map(constrain(pct, 0, 100), 0, 100, 0, 22); - display.fillRect(x + 2, y + 2, w, 8, SSD1306_WHITE); +void drawBatteryTop() { + char t[6]; + snprintf(t, sizeof(t), "%d%%", 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); + display.fillRect(x + 2, 2, map(constrain(batPct, 0, 100), 0, 100, 0, 12), 4, SSD1306_WHITE); + display.setCursor(x + 21, 0); + display.print(t); } -void drawPlayerScreen() { +void drawScreen() { + display.clearDisplay(); + display.setTextColor(SSD1306_WHITE); display.setTextSize(1); + 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; + 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 (playing) { - display.setCursor(0, 48); - display.print("Vol "); - display.print(volume); - } - if (sdOk && entryCount == 0) { - display.setCursor(0, 20); - display.print("Empty folder"); - } + 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; @@ -425,97 +340,52 @@ void drawPlayerScreen() { 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); + snprintf(line, sizeof(line), entries[idx].isDir ? "/%.18s" : "%.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); + int w = (int)((uint64_t)(dataTotal - dataLeft) * 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() { - display.clearDisplay(); - display.setTextColor(SSD1306_WHITE); - if (screenId == 0) drawPlayerScreen(); - else if (screenId == 1) drawBatteryScreen(); - else drawNumberScreen(); - drawBatteryTop(); // <-- on every page + drawBatteryTop(); display.display(); } // ---------- Setup ---------- void setup() { + pinMode(LED_BUILTIN, OUTPUT); Serial.begin(115200); analogReadResolution(12); pinMode(DIP1, INPUT_PULLUP); - pinMode(ENC_CLK, INPUT_PULLUP); - pinMode(ENC_DT, INPUT_PULLUP); - pinMode(ENC_SW, INPUT_PULLUP); + pinMode(ENC_DT, INPUT_PULLUP); + pinMode(ENC_SW, INPUT_PULLUP); encState = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT); 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.setTX(15); display.begin(SSD1306_SWITCHCAPVCC); - // SD on SPI0 (on-board slot) SPI.setSCK(SD_SCK); SPI.setTX(SD_MOSI); SPI.setRX(SD_MISO); - // DIP switch 1 ON = USB mode delay(5); usbMode = (digitalRead(DIP1) == LOW); - if (usbMode) { - usbModeSetup(); - return; // skip player setup - } + if (usbMode) { usbModeSetup(); return; } - sdOk = sd.begin(SD_CS, SD_SCK_MHZ(25)); - Serial.println(sdOk ? "SD ok" : "SD failed"); - if (sdOk) scanDir(); // was scanFiles() - i2s.setBuffers(8, 128); // ~23 ms of audio buffered, helps FLAC avoid underruns + // Dedicated SPI + higher clock = much faster, steadier SD reads + sdOk = sd.begin(SdSpiConfig(SD_CS, DEDICATED_SPI, SD_SCK_MHZ(20))); + if (sdOk) scanDir(); - // 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.setDATA(I2S_DIN); i2s.setBitsPerSample(16); @@ -524,10 +394,18 @@ void setup() { batPct = voltsToPercent(batVolts); drawScreen(); } +void blinkScreen() { + display.clearDisplay(); + display.display(); + delay(300); + + drawScreen(); + delay(300); +} // ---------- Loop ---------- void loop() { - // Flip the DIP switch -> reboot into the other mode + // DIP flip -> reboot into the other mode static uint32_t lastDip = 0; if (millis() - lastDip > 200) { lastDip = millis(); @@ -539,73 +417,67 @@ void loop() { } } } - if (usbMode) return; // TinyUSB handles the drive + if (usbMode) return; static int lastDetent = 0; static bool lastBtn = HIGH; - static uint32_t pressStart = 0; - static uint32_t lastBat = 0; - static uint32_t lastDraw = 0; + static uint32_t pressStart = 0, lastBat = 0, lastDraw = 0; bool redraw = false; - playStep(); + playStep(); // keep audio fed first, every pass - // Rotation - noInterrupts(); - int pos = encPos; - interrupts(); + // Rotation: volume while playing, list scroll otherwise + noInterrupts(); int pos = encPos; interrupts(); int detent = pos / 4; // use /2 if one click gives 2 counts if (detent != lastDetent) { int delta = detent - lastDetent; lastDetent = detent; - if (screenId == 0) { - if (playing) volume = constrain(volume + delta * 2, 0, 100); - else if (entryCount > 0) selected = constrain(selected + delta, 0, entryCount - 1); - redraw = true; - } else if (screenId == 2) { - number = constrain(number + delta, NUM_MIN, NUM_MAX); - redraw = true; - } + if (playing) volume = constrain(volume + delta * 2, 0, 100); + else if (entryCount > 0) selected = constrain(selected + delta, 0, entryCount - 1); + redraw = true; } - // Button: short = enter folder / play / stop, long = next screen + // Button: enter folder / play / stop bool btn = digitalRead(ENC_SW); if (btn == LOW && lastBtn == HIGH) pressStart = millis(); - if (btn == HIGH && lastBtn == LOW) { - uint32_t held = millis() - pressStart; - if (held >= LONG_MS) { - screenId = (screenId + 1) % 3; - redraw = true; - } else if (held > 30 && screenId == 0) { - if (playing) { - stopPlay(); - } else if (entryCount > 0) { - if (entries[selected].isDir) changeDir(entries[selected].name); - else startPlay(); + if (btn == HIGH && lastBtn == LOW && millis() - pressStart > 30) { + if (playing) stopPlay(); + else if (entryCount > 0) { + if (entries[selected].isDir) changeDir(entries[selected].name); + else { + startPlay(); + blinkScreen(); } - redraw = true; } + redraw = true; } lastBtn = btn; - // Battery once per second + // Battery once per second (low-pass filtered) if (millis() - lastBat >= 1000) { lastBat = millis(); - // low-pass filter so the percentage doesn't jitter batVolts += (readVolts() - batVolts) * 0.2f; - int oldPct = batPct; + int old = batPct; batPct = voltsToPercent(batVolts); - if (batPct != oldPct || screenId == 1) redraw = true; + if (batPct != old) redraw = true; } - // Progress bar refresh while playing - if (playing && screenId == 0 && millis() - lastDraw >= 300) redraw = true; + // Progress bar refresh (slow, so the OLED doesn't steal audio time) + if (playing && millis() - lastDraw >= 500) redraw = true; - // Track or album ended on its own (set by trackEnded()) if (needRedraw) { needRedraw = false; redraw = true; } if (redraw) { lastDraw = millis(); drawScreen(); } + + static unsigned long lastBlink = 0; +static bool ledState = false; + +if (millis() - lastBlink >= 500) { + lastBlink = millis(); + ledState = !ledState; + digitalWrite(LED_BUILTIN, ledState); +} } \ No newline at end of file