Copy Files USB to SD & SD to USB. from 2 inputs in (Simple-MSC-Example)???

charnjit

Well-known member
i want to use two different inputs to get copy all files usb to Sd and all files copy sd to usb .
as i got working skecth from wwatson. (Simple-MSC-Example)
Code:
/*
  MSC Drive and SD card multiple file copy example.
 
 This example shows how to read and write data to and from an SD card file
 and USB MSC drive.   

 The SD card circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11, pin 7 on Teensy with audio board
 ** MISO - pin 12
 ** CLK - pin 13, pin 14 on Teensy with audio board
 ** CS - pin 4, pin 10 on Teensy with audio board
 
 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 Modified 2017-2025 Warren Watson
 This example code is in the public domain.
    
 */
 
#include <USBHost_t36.h>
#include <SD.h>

//********************************************************
// Uncomment this define to copy from USB drive to SDCARD.
// Comment out this define to copy from SDCARD to USB drive.
#define USB_TO_SD 1
//********************************************************

// Setup USBHost_t36 and as many HUB ports as needed.
USBHost myusb;
USBHub hub1(myusb);
USBHub hub2(myusb);
USBHub hub3(myusb);
USBHub hub4(myusb);

// Setup MSC for the number of USB Drives you are using. (Two for this example)
// Mutiple  USB drives can be used. Hot plugging is supported. There is a slight
// delay after a USB MSC device is plugged in. This is waiting for initialization
// but after it is initialized ther should be no delay.
// ********* mscController is now USBDrive. *************
USBDrive msDrive1(myusb);
USBDrive msDrive2(myusb);

// USBFilesystem is a class based on claimed partitions discovered during
// initialization. We are using the first discovered partition here. More
// discovered partitions can be used by adding more instances of the
// 'USBFilesystem' class.
USBFilesystem partition1(myusb); // Up to four partions per device supported.

const int chipSelect = BUILTIN_SDCARD; // Using the built in SD slot.

// Create a copy from File instance (USB).
File myFile;
// Create a copy to File instance (SD).
File myFile1;

char fname[256]; // String buffer for filename to copy.


void setup(){
 
}
       void DO_COPY ()      {  {
// Wait for Serial port to open (up to 5 milliseconds):
   while (!Serial && (millis() < 5000)) {
    ; // wait for serial port to connect.
  }

  Serial.printf("%c***** USB to SD or SD to USB multiple file copy example *****\n\n",12);

  Serial.println("This sketch will copy all files in the root directory of");
  Serial.println("a USB drive to SDCARD or from an SDCARD to USB drive.");
  Serial.println("\nThere is define at the beginning of the sketch that can");
  Serial.println("you can change to determine the source and destination devices.");
  Serial.println("'#define USB_TO_SD 1'. The default is uncommented for USB to SDCARD.");
  Serial.println("Comment out this define to copy files from SDCARD to the USB drive\n");


  // Start USBHost_t36, HUB(s) and USB devices.
  myusb.begin();
  delay(500);  // give drives a little time to startup
  myusb.Task();  // Refresh USBHost_t36.

  // Detect and initialize USB drive.
  Serial.print("Initializing USB MSC drive.\n");
  Serial.print("*** NOTE: If no USB drive is connected, sketch will hang here forever ***\n");
  Serial.print("Connect USB drive now if not connected and sketch will resume running...");
  while (!partition1) { myusb.Task(); }
  Serial.println("initialization done.\n");

  // Detect and initialize SDCARD.
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    Serial.println("*** Insert SDCARD and restart program ***\n");
  }
  Serial.println("initialization done.\n");

#if defined(USB_TO_SD)
  // Open the root directory on the USB drive.
  File root = partition1.open("/"); // Source is root directory on USB drive.
#else
  // Open the root directory on the SDCARD.
  File root = SD.open("/"); // Source it root directory on SDCARD.
#endif

  while(true) {
    File entry = root.openNextFile(); // Get next file entry.
    if (! entry) break; // If entry is NULL then we are at the end of the dirrectory.
    if(!entry.isDirectory()) { // Skip over directories Only
                               // copy files in root directory.
      strcpy(fname, entry.name()); // Copy filename to "fname" buffer.
      // Now copy file to SDCARD or USB drive.
#if defined(USB_TO_SD)
      Serial.printf("\nCopying '%s' from USB drive to SD card\n",fname);
#else
      Serial.printf("\nCopying '%s' from SD card to USB drive\n",fname);
#endif
      if(copyFile(fname) < 0) { // Check for copy error (-1).
        Serial.printf("An error occured while copying file %s to the SD drive!!\n",fname);
      }
      entry.close(); // Close thiss file entry.
    }
  }
#if defined(USB_TO_SD)
  Serial.println("\nAll files in USB root directory have been copied to the SDCARD.");
#else
  Serial.println("\nAll files in SDCARD root directory have been copied to the USB drive.");
#endif
  Serial.println("**** FINISHED ****");
    
}
}

void loop()
{
    if (Serial.available() > 0) {
    int incomingByte = Serial.read();           
      if (incomingByte == '1') 
    {     DO_COPY ();   }  // USB to SD
}
}
// *********************************************************
// This is the function that copies one file to the SD card
// or USB drive.
// filnam: Filename of file to copy.
// *********************************************************
int copyFile(char *filnam) {

  int32_t br = 0, bw = 0;          // File read/write count
  uint32_t bufferSize = 16*1024; // Buffer size. Play with this:)
  uint8_t buffer[bufferSize];  // File copy buffer
  uint32_t bytesRW = 0; // Accumulation of total file size.
  float MegaBytes = 0;
 
#if defined(USB_TO_SD) // USB_TO_SD == 1 then copy from USB drive to SDCARD.
  myFile = partition1.open(filnam); // Open USB drive source file for read op.
  myFile1 = SD.open(filnam, FILE_WRITE_BEGIN); // Open "filnam" file on SD card for writing.
#else // USB_TO_SD == 0 then copy from SDCARD drive to USB drive.
  myFile1 = SD.open(filnam); // Open SD card source file for read op.
  myFile = partition1.open(filnam, FILE_WRITE_BEGIN); // Open "filnam" file on USB drive for writing.
#endif

  // if the write file opened okay, write to it:
#if defined(USB_TO_SD)
  if (myFile) {
#else
  if (myFile1) {
#endif
  
    /* Copy source to destination */
    uint32_t start = micros();
    for(;;) {
      // Read from USB file and write to SD file.
#if defined(USB_TO_SD)
      br = myFile.read(buffer, bufferSize); // Read a 'BUF_SIZE' chunk of file.
#else
      br = myFile1.read(buffer, bufferSize); // Read a 'BUF_SIZE' chunk of file.
#endif
      if (br <= 0) break; // Error or EOF
        // Write chunk to SD drive.
#if defined(USB_TO_SD)
      bw = myFile1.write(buffer, br); // Write buffer full to destnation drive.
#else
      bw = myFile.write(buffer, br); // Write buffer full to destnation drive.
#endif
      if (bw < br) break; // Error or disk is full
      bytesRW += (uint64_t)bw;  // Keep track of total bytes written.
    }
    // close the files:
    myFile.close();
    myFile1.close();
    // Proccess posible errors.
    if(br < 0) {
      Serial.println("**** A read error occured!! ****");
      return -1; // Return failure.
    } else if(bw < br) {
      Serial.println("**** A write error occured!! ****"); // Can also be disk full error.
      return -1; // Return failure.
    }

#if 1 // Set to 1 to turn on copy speed display.
    uint32_t finish = (micros() - start); // Get total copy time.
    MegaBytes = (bytesRW*1.0f)/(1.0f*finish); // Compute MB/s.
    Serial.printf("Copied %lu bytes in %f seconds. Speed: %f MB/s\n",
                   bytesRW,(1.0*finish)/1000000.0,MegaBytes);
#endif

  }
  return 0; // 0 = success.
}
here i want to get :
if
Code:
void loop()
{
    if (Serial.available() > 0) {
    int incomingByte = Serial.read();           
      if (incomingByte == '1')
should be copy from usb to SD
and if
Code:
void loop()
{
    if (Serial.available() > 0) {
    int incomingByte = Serial.read();           
      if (incomingByte == '0')
should be copy from Sd to USB.
what code modification should be in sketch.
:- after delete line
Code:
#define USB_TO_SD 1
i have tried for copy Usb to SD
Code:
#define USB_TO_SD 1
DO_COPY ();
and for copy SD to usb
Code:
DO_COPY ();
it did not work..
i am getting copy (usb to sd) if line
Code:
#define USB_TO_SD 1
exist in sketch before void setup.
i am getting copy (sd to usb) if i delete line
Code:
#define USB_TO_SD 1
from void setup.
please reply how to get both process from different inputs ( buttons or serial input) in
Code:
void loop () {

}
thank you.....
 
@charnjit - First of all your opening and closing braces are all wrong although it still compiles:confused: You lucked out I guess.
Code:
void DO_COPY ()  {

}

void setup()  { // This starts the setup function.
// } -----------> wrong 
 //      void DO_COPY ()     {  { ------------> wrong
// Wait for Serial port to open (up to 5 milliseconds):
   while (!Serial && (millis() < 5000)) {
    ; // wait for serial port to connect.
} // This ends the setup
There were also extra braces elsewhere to eliminate.
Setup function should look like:
Code:
void setup() {
 
//       void DO_COPY ()      {  {
// Wait for Serial port to open (up to 5 milliseconds):
   while (!Serial && (millis() < 5000)) {
    ; // wait for serial port to connect.
   }

  Serial.printf("%c***** USB to SD or SD to USB multiple file copy example *****\n\n",12);

  Serial.println("This sketch will copy all files in the root directory of");
  Serial.println("a USB drive to SDCARD or from an SDCARD to USB drive.");
  Serial.println("\nThere is define at the beginning of the sketch that can");
  Serial.println("you can change to determine the source and destination devices.");
  Serial.println("'#define USB_TO_SD 1'. The default is uncommented for USB to SDCARD.");
  Serial.println("Comment out this define to copy files from SDCARD to the USB drive\n");


  // Start USBHost_t36, HUB(s) and USB devices.
  myusb.begin();
  delay(500);  // give drives a little time to startup
  myusb.Task();  // Refresh USBHost_t36.

  // Detect and initialize USB drive.
  Serial.print("Initializing USB MSC drive.\n");
  Serial.print("*** NOTE: If no USB drive is connected, sketch will hang here forever ***\n");
  Serial.print("Connect USB drive now if not connected and sketch will resume running...");
  while (!partition1) { myusb.Task(); }
  Serial.println("initialization done.\n");

  // Detect and initialize SDCARD.
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    Serial.println("*** Insert SDCARD and restart program ***\n");
  }
  Serial.println("initialization done.\n");

#if defined(USB_TO_SD)
  // Open the root directory on the USB drive.
  File root = partition1.open("/"); // Source is root directory on USB drive.
#else
  // Open the root directory on the SDCARD.
  File root = SD.open("/"); // Source it root directory on SDCARD.
#endif

  while(true) {
    File entry = root.openNextFile(); // Get next file entry.
    if (! entry) break; // If entry is NULL then we are at the end of the dirrectory.
    if(!entry.isDirectory()) { // Skip over directories Only
                               // copy files in root directory.
      strcpy(fname, entry.name()); // Copy filename to "fname" buffer.
      // Now copy file to SDCARD or USB drive.
#if defined(USB_TO_SD)
      Serial.printf("\nCopying '%s' from USB drive to SD card\n",fname);
#else
      Serial.printf("\nCopying '%s' from SD card to USB drive\n",fname);
#endif
      if(copyFile(fname) < 0) { // Check for copy error (-1).
        Serial.printf("An error occured while copying file %s to the SD drive!!\n",fname);
      }
      entry.close(); // Close this file entry.
    }
  }
#if defined(USB_TO_SD)
  Serial.println("\nAll files in USB root directory have been copied to the SDCARD.");
#else
  Serial.println("\nAll files in SDCARD root directory have been copied to the USB drive.");
#endif
  Serial.println("**** FINISHED ****");
    
}

The do_Copy() function is not defined any where in the sketch except in the setup() function?? I moved it out side of the setup() function to just before the setup() function. As far as I know you cannot define a function inside of a function. Then I was able to compile and run your sketch although it just did a single file copy.

So if I understand what you are trying to do is to copy all files in the root directory of the USB drive to the root directory of an SD card and the same for SD card to USB drive. Correct?? I have been wanting to do an example of that as well, so I will do it. Give me a liitle time and I will write the sketch and add it to GitHub repo. In the meen time you can work with your original sketch...
 
@charnjit - I have created a simple sketch as an example of multi file copies between USB to SD and SD to USB. Hopefully this was the example you are looking for. It has a simple menu with four functions available.
Code:
------------------------------------------------------------------
Select:
   1)  to copy all files from USB drive 1 to SDIO card.
   2)  to copy all files from SDIO card to USB drive 1.
   3)  List USB Drive 1 Directory
   4)  List SD card Directory
------------------------------------------------------------------
Note that it uses the root directory only. I have not setup recursive sub directory diving yet. That is next. The sketch checks to make sure both the USB drive and the SD card is attached. If either the USB drive and/or the SD card are not attached you will see one or both of these messages:
Code:
Initializing USB MSC drive 1...No drive connected yet!!!!
Connect a drive to continue.
The sketch will actually wait for you to plug in a USB drive and then continue.
Code:
Initializing SDIO card...begin() failed
Do not reformat the SD.
SdError: 0X17,0X0
Halting
You cannot hot-plug the SD card so you will have to attach the SD card and power cycle the Teensy.
Enter 1 to copy all files from the USB drive to the SD card.
Enter 2 to copy all files from the SD card to the USB drive.
Enter 3 to display the USB drive root directory contents.
Enter 4 to display the SD card root directory contents.
You can find the sketch called "copyAllfilesUSB_SD" here.
This is a listing of that sketch:
Code:
/*
  Multi MSC USB Drive and SD card filecopy testing.
 
 This example shows how use the mscfs and SD libraries to copy file(s)
 between USB and SDIO card devices. It also demonstrates hot plugging
 USB drive. Plugged in or replugged devices are auto mounted.
 
 Created 10-24-2025
 Modified 10-25-2025
 by Warren Watson
*/

#include "SPI.h"
#include "Arduino.h"
#include <USBHost_t36.h>
#include "SD.h"

// USB and SD card numeric identifiers.
#define USB1 3
#define SD1  4

// Change to false to NOT display copy progresss bar and stats for each
// file copied.
#define USE_STATS true

// Setup USBHost_t36 and as many HUB ports as needed.
USBHost myusb;
USBHub hub1(myusb);
USBHub hub2(myusb);
USBHub hub3(myusb);
USBHub hub4(myusb);

// Setup MSC for the number of USB Drives you are using. (one for this
// example). Hot plugging is supported.
USBDrive msDrive1(myusb);

// SDIO card chipselect pin def. (254)
const int chipSelect = BUILTIN_SDCARD;

// Create USB instances. Two USB drives.
USBFilesystem msc1(myusb);

// Create file copy source and destination file pointers.
File file1; // src file
File file2; // dest file
File USBroot; // File pointer to USB root directory.
File SDroot; // File pointer to SDIO root directory.

// Used to check for USB drives connection.
elapsedMillis mscTimeOut;

// Copy a file from one drive to another.
// Set 'stats' to true to display a progress bar, copy speed and copy time.
int fileCopy(File *src, File *dest, bool stats) {
    int br = 0, bw = 0;          // File read/write count
    uint32_t bufferSize = 32*1024; // Buffer size. *** Play with this:) ***
    uint8_t buffer[bufferSize];  // File copy buffer
    uint32_t cntr = 0;
    uint32_t start = 0, finish = 0;
    uint32_t bytesRW = 0;
    int copyError = 0;
   
    /* Copy source to destination */
    start = micros();
    for (;;) {
        if(stats) { // If true, display progress bar.
            cntr++;
            if(!(cntr % 10)) Serial.printf("*");
            if(!(cntr % 640)) Serial.printf("\n");
        }
        br = src->read(buffer, sizeof(buffer));  // Read buffer size of source file (USB Type)
        if (br <= 0) {
            copyError = br;
            break; // Error or EOF
        }
        bw = dest->write(buffer, br); // Write it to the destination file (USB Type)
        if (bw < br) {
            copyError = bw; // Error or disk is full
            break;
        }
        bytesRW += (uint32_t)bw; // Update bytes transfered count.
    }
    dest->flush(); // Flush write buffer.
    // Close open files
    src->close(); // Source
    dest->close(); // Desstination
    finish = (micros() - start); // Get total copy time.
    float MegaBytes = (bytesRW*1.0f)/(1.0f*finish); // Convert to float.
   
    if(stats) // If true, display time stats.
        Serial.printf("\nCopied %u bytes in %f seconds. Speed: %3.1f MB/s\n",
                         bytesRW,(1.0*finish)/1000000.0,MegaBytes);
    return copyError; // Return any errors or success.
}

// This function scans through the root directory for every occurence of
// a regular file on the source drive then copies it to the destination
// drive. It opens the source file for reading and opens the destination
// file for writing. (bails on error).
//   File dir: is the source directory for source file(s) to read.
//   uint8_t source: is the source drive identifier (USB1 or SD1).
// Then it calls the fileCopy(&file1,&file2,stats) function.
//   &file1: Address of source file pointer.
//   &file2: Address of desination file pointer.
//   bool stats: TRUE = print progress bar and copy stats. False = quiet.
int copyDirectory(File dir, uint8_t source) {
   int copyResult = 0;
   while(true) {
     File entry = dir.openNextFile(); // Get next directory entry.
     if (! entry) { // No more enries, we are done.
       //Serial.println("** no more files **");
       break; // Break out of while loop and close the directory.
     }
     Serial.println(); Serial.println(entry.name());  // Show name of file we are copying.
     if (entry.isDirectory()) { // Not doing recursive copy in sub dirs.
       break; // Skip over directories.
     } else {
       if(source == USB1) { // Copy from USB to SD. (USB is src and SD is dest)
         file1 = msc1.open(entry.name(), FILE_READ); // Open source file.
         if(!file1) { // Did not open. Return error.
           Serial.printf("\nERROR: could not open source file: %s\n",entry.name());
           return -1;
         }
         file2 = SD.open(entry.name(), FILE_WRITE_BEGIN); // Open destination file.
         if(!file2) { // Did not open. Return error.
           Serial.printf("\nERROR: could not open destination file: %s\n",entry.name());
           return -1;
         }
         copyResult = fileCopy(&file1, &file2, USE_STATS); // Do the actual file copy.
         if(copyResult != 0) { // Copy failed. Return error.
           Serial.printf("File Copy Failed with code: %d\n",entry.name());
           return -1;
         }
      } else { // Copy from SD to USB. (SD is src and USB is dest)
         file1 = SD.open(entry.name(), FILE_READ); // Open source file.
         if(!file1) { // Did not open. Return error.
           Serial.printf("\nERROR: could not open source file: %s\n",entry.name());
           return -1;
         }
         file2 = msc1.open(entry.name(), FILE_WRITE_BEGIN); // Open destination file.
         if(!file2) { // Did not open. Return error.
           Serial.printf("\nERROR: could not open destination file: %s\n",entry.name());
           return -1;
         }
         copyResult = fileCopy(&file1, &file2, USE_STATS);
         if(copyResult != 0) { // Copy failed. Return error.
           Serial.printf("File Copy Failed with code: %d\n",copyResult);
           return -1;
         }
       }
     }
     entry.close();  // Close directory.
   }
   return 0;
}

// List Directories using SdFat "ls()" call.
void listDirectories(uint8_t device) {
    Serial.printf("-------------------------------------------------\n");
    switch(device) {
        case USB1:
            Serial.printf("\nUSB drive 1 directory listing:\n");
            msc1.mscfs.ls("/", LS_R | LS_DATE | LS_SIZE);
            break;
        case SD1:
            Serial.printf("\nSDIO card directory listing:\n");
            SD.sdfs.ls("/", LS_R | LS_DATE | LS_SIZE);
        default:
            Serial.printf("-------------------------------------------------\n");
            return;
    }
    Serial.printf("-------------------------------------------------\n");
}

// Check for connected USB drives.
bool checkConnected(USBDrive &drive) {
  mscTimeOut = 0;
  while(!drive.msDriveInfo.connected && (mscTimeOut < MSC_CONNECT_TIMEOUT))
    delay(1);
  if(!drive.msDriveInfo.connected) { // If nothing turns up, nothing connected.
    Serial.println("No drive connected yet!!!!");
    Serial.println("Connect a drive to continue.");
    while(!drive.msDriveInfo.connected) delay(1000); // Wait for a device to be plugged in.
  }
  return true; // Always return true.
}

// Setup USB and SDIO and mount them.
void setup()
{
  // Wait for port to open:
  while (!Serial) {
    yield(); // wait for serial port to connect.
  }

  Serial.printf("%cUSB DRIVE AND SD CARD MULTI FILE COPY TESTING\n\n",12);
 
  // Start USBHost_t36, HUB(s) and USB devices.
  myusb.begin();

  // There is a slight delay after a USB MSC device is plugged in which
  // varys with the device being used. The device is internally initializing.
  // Initialize USB drive 1
  Serial.print("Initializing USB MSC drive 1...");
  checkConnected(msDrive1); //See if this device is plugged in.
  Serial.println("USB drive 1 is present.");
  //Check for supported filesystem.
  myusb.Task();
  if(msc1.partitionType == 0) { // 0 indicates an unrecognized filesystem.
    Serial.println("Unrecognized filesystem error...");
    Serial.printf("partitionType = %d\n",msc1.partitionType);
    Serial.println("Halting"); // For now require a reset.
    while(1);
  }

  // Initialize SDIO card
  Serial.print("Initializing SDIO card...");
  if (!SD.begin(chipSelect)) {
    SD.sdfs.initErrorPrint(&Serial);
    Serial.println("Halting"); // For now require a reset.
    while(1);
  } else {
     Serial.println("SDIO card is present.");
  }
}

// Display menu and process user selection.
void loop(void) {
    uint8_t c = 0;

    Serial.printf("\n------------------------------------------------------------------\n");
    Serial.printf("Select:\n");
    Serial.printf("   1)  to copy all files from USB drive 1 to SDIO card.\n");
    Serial.printf("   2)  to copy all files from SDIO card to USB drive 1.\n");
    Serial.printf("   3)  List USB Drive 1 Directory\n");
    Serial.printf("   4)  List SD card Directory\n");

    Serial.printf("------------------------------------------------------------------\n");

    while(!Serial.available()) myusb.Task(); // Support hot plugging.
    c = Serial.read();
    while(Serial.available()) Serial.read(); // Get rid of CR and/or LF if there.
    // Process input 1 to 4.
    switch(c) {
        case '1':
            Serial.printf("\n1) Copying all files from USB drive 1 to SDIO card\n");
            USBroot = msc1.open("/"); // Open USB device USB1 root directory.
            copyDirectory(USBroot, USB1); // Copy all files from USB to SD card.
            break;
        case '2':
            Serial.printf("\n2) Copying all files from SDIO card to USB drive 1 \n");
            SDroot = SD.open("/"); // Open SD card device SD1 root directory.
            copyDirectory(SDroot, SD1); // Copy all files from SD card to USB.
            break;
        case '3':
            listDirectories(3); // List USB drive files.
            break;
        case '4':
            listDirectories(4); // List SD card files.
            break;
        default:
            break;
    }
}
Hopefully this helps with your project. I tried to keep it as simple as possible :D
 
Thank you wwatson ...
yes it is exact what i want . your given code alone working well.
i will try it mix display+keypad code & report if any error occur.
thank you....
 
is any example to copy
All files ,folder, subfolder (usb to sd /sd to usb).
means all data on root copying (usb to sd /sd to usb). ???
to get complete backup of sd to usb. & usb to sd.
 
Back
Top