Skip to content

Instantly share code, notes, and snippets.

@jaryl
Created January 2, 2024 03:26
Show Gist options
  • Save jaryl/26beb5fbb1e7cc754608764431bb0aeb to your computer and use it in GitHub Desktop.
Save jaryl/26beb5fbb1e7cc754608764431bb0aeb to your computer and use it in GitHub Desktop.
Mount TinyUSB mass storage device using an SD card on a Pico W via SPI
#include <SdFat.h>
#include <Adafruit_TinyUSB.h>
const int _CS = 17;
#define SD_CONFIG SdSpiConfig(_CS, DEDICATED_SPI, SD_SCK_MHZ(12)) // max 50, but may result in read/write errors
Adafruit_USBD_MSC usb_msc;
SdFat sd;
SdFile root;
SdFile file;
bool fs_changed;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
usb_msc.setID("Adafruit", "SD Card", "1.0");
usb_msc.setUnitReady(false);
usb_msc.begin();
Serial.begin(115200);
Serial.print("Initializing SD card... ");
if (!sd.cardBegin(SD_CONFIG)) {
Serial.println("failed");
}
Serial.println("success");
#if SD_FAT_VERSION >= 20000
uint32_t block_count = sd.card()->sectorCount();
#else
uint32_t block_count = sd.card()->cardSize();
#endif
Serial.print("Volume size (MB): ");
Serial.println((block_count/2) / 1024);
usb_msc.setReadWriteCallback(msc_read_cb, msc_write_cb, msc_flush_cb);
usb_msc.setCapacity(block_count, 512);
usb_msc.setUnitReady(true);
Serial.print("Mass storage device: ready\n");
fs_changed = true;
while (!Serial) delay(10);
}
void loop()
{
}
int32_t msc_read_cb(uint32_t lba, void* buffer, uint32_t bufsize)
{
bool rc;
#if SD_FAT_VERSION >= 20000
rc = sd.card()->readSectors(lba, (uint8_t*) buffer, bufsize/512);
#else
rc = sd.card()->readBlocks(lba, (uint8_t*) buffer, bufsize/512);
#endif
return rc ? bufsize : -1;
}
int32_t msc_write_cb(uint32_t lba, uint8_t* buffer, uint32_t bufsize)
{
bool rc;
digitalWrite(LED_BUILTIN, HIGH);
#if SD_FAT_VERSION >= 20000
rc = sd.card()->writeSectors(lba, buffer, bufsize/512);
#else
rc = sd.card()->writeBlocks(lba, buffer, bufsize/512);
#endif
return rc ? bufsize : -1;
}
void msc_flush_cb(void)
{
#if SD_FAT_VERSION >= 20000
sd.card()->syncDevice();
#else
sd.card()->syncBlocks();
#endif
// clear file system's cache to force refresh
sd.cacheClear();
fs_changed = true;
digitalWrite(LED_BUILTIN, LOW);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment