Compare commits

...
2 Commits
Author SHA1 Message Date
zipfriis af0c3b7946 basic player, wav 2026-11-29 10:57:22 +01:00
zipfriis 6d6a776e93 test works 2026-11-28 15:34:50 +01:00
3 changed files with 13648 additions and 43 deletions
+4 -3
View File
@@ -4,10 +4,11 @@ board = adafruit_feather
framework = arduino
board_build.core = earlephilhower
monitor_speed = 115200
build_flags =
-DUSE_TINYUSB
build_flags = -DUSE_TINYUSB
lib_deps =
adafruit/Adafruit SSD1306
adafruit/Adafruit GFX Library
adafruit/Adafruit SSD1306
adafruit/Adafruit BusIO
adafruit/Adafruit TinyUSB Library
adafruit/SdFat - Adafruit Fork
+13096
View File
File diff suppressed because it is too large Load Diff
+548 -40
View File
@@ -1,20 +1,100 @@
#include <Arduino.h>
#include <SPI.h>
#include <SdFat.h>
#include <Adafruit_TinyUSB.h>
#include <I2S.h>
#include <Adafruit_GFX.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"
// OLED on SPI1 (SCK = GP14, MOSI = GP15)
// If your display worked with other pins, change these three lines.
#define OLED_CS 9
// ---------- Pins ----------
// OLED on SPI1 (header pins SCK / MO)
#define OLED_CS 24
#define OLED_DC 6
#define OLED_RST 5
#define BAT_PIN A3 // GP29, battery voltage / 2
// 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_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 BAT_PIN A3
#define SAMPLES 16
Adafruit_SSD1306 display(128, 64, &SPI1, OLED_DC, OLED_RST, OLED_CS);
#define NUM_MIN 0
#define NUM_MAX 999
#define MAX_FILES 64
#define NAME_LEN 64
#define LONG_MS 600
// ---------- Objects ----------
Adafruit_SSD1306 display(128, 64, &SPI1, OLED_DC, OLED_RST, OLED_CS);
I2S i2s(OUTPUT);
SdFat sd;
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
};
void encISR() {
uint8_t newState = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT);
encPos += ENC_TABLE[(encState << 2) | newState];
encState = newState;
}
// ---------- App state ----------
bool usbMode = false;
int screenId = 0; // 0 player, 1 battery, 2 number
int number = 0;
float batVolts = 0;
int batPct = 0;
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;
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
int16_t inBuf[2048];
int16_t outBuf[4096];
// ---------- 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},
@@ -26,7 +106,7 @@ 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 * 3.55f;
return (sum / (float)SAMPLES) * 3.3f / 4095.0f * 2.0f; // divider unverified
}
int voltsToPercent(float v) {
@@ -41,6 +121,268 @@ int voltsToPercent(float v) {
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);
}
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
}
void scanDir() {
entryCount = 0;
if (strcmp(curDir, "/") != 0) { // ".." entry when not in root
strcpy(entries[0].name, "..");
entries[0].isDir = true;
entryCount = 1;
}
int first = entryCount;
File32 dir;
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 (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;
entries[entryCount].isDir = d;
entryCount++;
}
}
dir.close();
// insertion sort (keeps ".." on top)
for (int i = first + 1; i < entryCount; i++) {
Entry tmp = entries[i];
int j = i - 1;
while (j >= first && entryLess(tmp, entries[j])) { entries[j + 1] = entries[j]; j--; }
entries[j + 1] = tmp;
}
}
void changeDir(const char* name) {
char leaveName[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;
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, leaveName)) selected = i;
}
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); }
bool openWav(const char* path) {
wavFile = sd.open(path, O_RDONLY);
if (!wavFile) return false;
uint8_t hdr[12];
if (wavFile.read(hdr, 12) != 12 || memcmp(hdr, "RIFF", 4) || memcmp(hdr + 8, "WAVE", 4)) {
wavFile.close(); return false;
}
bool gotFmt = false;
while (true) {
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; }
uint16_t format = rd16(fmt);
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
}
gotFmt = true;
if (size > 16) wavFile.seekSet(wavFile.position() + (size - 16));
} else if (!memcmp(ch, "data", 4)) {
if (!gotFmt) { wavFile.close(); return false; }
dataTotal = dataLeft = size;
return true;
} else {
wavFile.seekSet(wavFile.position() + 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;
i2s.end();
i2s.begin(wavRate);
playing = true;
}
void stopPlay() {
playing = false;
if (flac) { drflac_close(flac); flac = nullptr; }
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;
if (next < entryCount && !entries[next].isDir) { selected = next; startPlay(); }
needRedraw = true;
}
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<uint32_t>(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;
}
uint32_t gain = (uint32_t)volume * volume; // 0..10000
int outSamples;
if (wavChannels == 2) {
for (int i = 0; i < samples; i++)
outBuf[i] = (int16_t)(((int32_t)inBuf[i] * (int32_t)gain) / 10000);
outSamples = samples;
} 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;
}
outSamples = samples * 2;
}
i2s.write((const uint8_t*)outBuf, outSamples * 2); // blocks until queued
}
// ---------- 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;
}
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();
}
void usbModeSetup() {
usb_msc.setID("Adalogger", "SD Card", "1.0");
usb_msc.setReadWriteCallback(msc_read_cb, msc_write_cb, msc_flush_cb);
usb_msc.setUnitReady(false);
usb_msc.begin();
bool ok = sd.begin(SD_CS, SD_SCK_MHZ(25));
if (ok) {
usb_msc.setCapacity(sd.card()->sectorCount(), 512);
usb_msc.setUnitReady(true);
}
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(2);
display.setCursor(0, 10);
display.print("USB MODE");
display.setTextSize(1);
display.setCursor(0, 40);
display.print(ok ? "SD is a USB drive" : "SD failed");
display.setCursor(0, 52);
display.print("Eject, then flip DIP");
display.display();
}
// ---------- 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);
@@ -48,56 +390,222 @@ void drawBatteryIcon(int x, int y, int pct) {
display.fillRect(x + 2, y + 2, w, 8, SSD1306_WHITE);
}
void drawPlayerScreen() {
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;
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() {
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
if (screenId == 0) drawPlayerScreen();
else if (screenId == 1) drawBatteryScreen();
else drawNumberScreen();
drawBatteryTop(); // <-- on every page
display.display();
}
// ---------- Setup ----------
void setup() {
Serial.begin(115200);
analogReadResolution(12);
pinMode(DIP1, INPUT_PULLUP);
pinMode(ENC_CLK, 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);
// OLED on SPI1
SPI1.setSCK(14);
SPI1.setTX(15);
if (!display.begin(SSD1306_SWITCHCAPVCC)) {
Serial.println("OLED init failed");
while (true);
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
}
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(2);
display.setCursor(0, 0);
display.print("Hello");
display.display();
delay(1500);
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
// I2S to PCM5100 (LRCK = BCK + 1 = GPIO11)
i2s.setBCLK(I2S_BCK);
i2s.setDATA(I2S_DIN);
i2s.setBitsPerSample(16);
batVolts = readVolts();
batPct = voltsToPercent(batVolts);
drawScreen();
}
// ---------- Loop ----------
void loop() {
float volts = readVolts();
int pct = voltsToPercent(volts);
// Flip the DIP switch -> reboot into the other mode
static uint32_t lastDip = 0;
if (millis() - lastDip > 200) {
lastDip = millis();
if ((digitalRead(DIP1) == LOW) != usbMode) {
delay(50);
if ((digitalRead(DIP1) == LOW) != usbMode) {
if (playing) stopPlay();
rp2040.reboot();
}
}
}
if (usbMode) return; // TinyUSB handles the drive
Serial.print(volts, 2);
Serial.print(" V ");
Serial.print(pct);
Serial.println(" %");
static int lastDetent = 0;
static bool lastBtn = HIGH;
static uint32_t pressStart = 0;
static uint32_t lastBat = 0;
static uint32_t lastDraw = 0;
bool redraw = false;
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
playStep();
display.setTextSize(1);
display.setCursor(0, 0);
display.print("Battery");
// Rotation
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;
}
}
display.setTextSize(3);
display.setCursor(0, 18);
display.print(pct);
display.print('%');
// Button: short = enter folder / play / stop, long = next screen
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();
}
redraw = true;
}
}
lastBtn = btn;
display.setTextSize(1);
display.setCursor(0, 54);
display.print(volts, 2);
display.print(" V");
// Battery once per second
if (millis() - lastBat >= 1000) {
lastBat = millis();
// low-pass filter so the percentage doesn't jitter
batVolts += (readVolts() - batVolts) * 0.2f;
int oldPct = batPct;
batPct = voltsToPercent(batVolts);
if (batPct != oldPct || screenId == 1) redraw = true;
}
drawBatteryIcon(96, 52, pct);
// Progress bar refresh while playing
if (playing && screenId == 0 && millis() - lastDraw >= 300) redraw = true;
display.display();
delay(1000);
// Track or album ended on its own (set by trackEnded())
if (needRedraw) { needRedraw = false; redraw = true; }
if (redraw) {
lastDraw = millis();
drawScreen();
}
}