A hotswap compatible USB drive example with USBHost_t36

yeahtuna

Well-known member
Code:
#include <USBHost_t36.h>

USBHost usbHost;
USBHub usbHub(usbHost);

USBDrive usbDrive(usbHost);
USBFilesystem usbPart(usbHost);
File root;

void setup() {
  Serial.begin(9600);
  while (!Serial && millis() < 5000) {
    // wait for serial port to connect.
  }
  usbHost.begin();
}


void loop() {
  delay(3000);

  // if a partition isn't currently connected
  if (!usbPart) {

    // In case it was previously opened and the disc was removed.
    root.close();

    // Is there are disk available?
    if (usbDrive) {
      
      Serial.print("\nInitializing USB MSC drive...");
      if (!usbPart.begin(&usbDrive)) {
        Serial.println("Failed!");
        return;
      }
      Serial.println("Success!");
    }

    // No disk is available.
    else {
      Serial.println("Insert a USB drive / memory stick...");
      return;
    }
  }

  // Partition is connected, but the filesystem hasn't been opened.
  else if (!root){
    root = usbPart.open("/");
    if (root) { 
      Serial.println("------------------------------------------");
      printDirectory(root, 0);
      Serial.println("-------------------------------------------");
    }
  }
}


void printDirectory(File dir, int numSpaces) {
  while(true) {
    File entry = dir.openNextFile();
    if (! entry) {
      //Serial.println("** no more files **");
      break;
    }
    printSpaces(numSpaces);
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numSpaces+2);
    } else {
      // files have sizes, directories do not
      printSpaces(48 - numSpaces - strlen(entry.name()));
      Serial.print("  ");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

void printSpaces(int num) {
  for (int i=0; i < num; i++) {
    Serial.print(" ");
  }
}


Notes: I'm actually surprised that I needed to call root.close() after the drive is removed from the USB host port. I would expect this method to be called automatically when the drive was removed. Perhaps this is a bug?
 
Back
Top