Any Easy library copy files from usb to built in Sd card.

charnjit

Well-known member
I was searching any Library For teensy to copy?paste files between Usb & Built-in sd card. i have solder Female usb Jack to Teensy as it.
T 4.1 Usb host.jpg

I Found UsbMscFat Library by wwatson4506. as in Study , I went into example, I Saw copyFilesUSB.ino Example . it is about 500+ line code . before compile , I am trying to study it . I could not understand difficult code in example
is there any Another easy Library than above , in which at least line are to write . for copying All file to Built in Sd card(directly from connected usb Drive to Built-in SD card)???
 
Last edited:
@charnjit - As it says at the beginning of the readme for the "UsbMscFat" repository is OUTDATED and will not work with the newer Teesnyduinos! Use at least the stable version 1.59 or versions 1.60B1 to version 1.60B4. The latest driver for MSC is included in the USBHost_t36 library. And a few examples are given in the "/storage" folder.

I have a library Simple-MSC-Examples that work with the latest versions of Teensyduino. In this library I have a sketch that creates a file "test.txt" on the USB drive. Then it checks for a file named "copy.txt" on the SD drive. If it exists then it deletes it. Finally it copies "test.txt" from the USB drive to "copy.txt" on the the SD drive. Copy times are shown. Also the "printDirectory()' function shows how to test for an existing directory entry and use the (entry.name()) to open and copy the file to the SD card. At this time I do not have an example of multiple file copy.

Hope this helps you. Let me know if you have other questions:)
 
@charnjit - I decided to create a multi file copy sketch (MultiFileCopy.ino) to add to Simple MSC-Examples library. It demonstrates copying all the files in the root directory of a USB drive to an SDCARD or SDcard to USB drive. You can switch the source and destination devices by commenting or un-commenting a simple define at the beginning of the sketch:
Code:
//********************************************************
// 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
//********************************************************
Here is the sketch:
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()
{
// 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");
  waitforInput();

  // 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()
{
    // nothing happens after setup
}

// *********************************************************
// 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.
}

void waitforInput()
{
  Serial.println("Press anykey to continue");
  while (Serial.read() == -1) ;
  while (Serial.read() != -1) ;
}
I have tried to comment the code as much as possible to make it easier to understand. Example output (USB to SDCARD):
Code:
This sketch will copy all files in the root directory of
a USB drive to SDCARD or from an SDCARD to USB drive.

There is define at the beginning of the sketch that can
you can change to determine the source and destination devices.
'#define USB_TO_SD 1'. The default is uncommented for USB to SDCARD.
Comment out this define to copy files from SDCARD to the USB drive

Press anykey to continue
Initializing USB MSC drive.
*** NOTE: If no USB drive is connected, sketch will hang here forever ***
Connect USB drive now if not connected and sketch will resume running...initialization done.

Initializing SD card...initialization done.


Copying 'MSCtesting.bas' from USB drive to SD card
Copied 534 bytes in 0.006737 seconds. Speed: 0.079264 MB/s

Copying '32MEGfile.dat' from USB drive to SD card
Copied 32768000 bytes in 2.835241 seconds. Speed: 11.557395 MB/s

Copying 'bench.dat' from USB drive to SD card
Copied 32768000 bytes in 2.847960 seconds. Speed: 11.505779 MB/s

Copying 'datalog.txt' from USB drive to SD card
Copied 380 bytes in 0.008897 seconds. Speed: 0.042711 MB/s

Copying 'copy.txt' from USB drive to SD card
Copied 32768000 bytes in 2.862385 seconds. Speed: 11.447796 MB/s

Copying 'test.txt' from USB drive to SD card
Copied 32768000 bytes in 2.849697 seconds. Speed: 11.498766 MB/s

Copying 'fail.jpg' from USB drive to SD card
Copied 45123 bytes in 0.010115 seconds. Speed: 4.460999 MB/s

Copying 'fontcnvt' from USB drive to SD card
Copied 16688 bytes in 0.008261 seconds. Speed: 2.020094 MB/s

Copying 'fontcnvt.c' from USB drive to SD card
Copied 955 bytes in 0.006548 seconds. Speed: 0.145846 MB/s

Copying 'sansurf.fnt' from USB drive to SD card
Copied 4096 bytes in 0.006246 seconds. Speed: 0.655780 MB/s

Copying 'sansurf.h' from USB drive to SD card
Copied 22050 bytes in 0.010354 seconds. Speed: 2.129612 MB/s

Copying 'SConscript' from USB drive to SD card
Copied 1211 bytes in 0.006663 seconds. Speed: 0.181750 MB/s

Copying 'sgl_dbl_click.png' from USB drive to SD card
Copied 11019 bytes in 0.008365 seconds. Speed: 1.317274 MB/s

Copying 'sgl_dbl_drag.png' from USB drive to SD card
Copied 25575 bytes in 0.010704 seconds. Speed: 2.389294 MB/s

All files in USB root directory have been copied to the SDCARD.
**** FINISHED ****
Example output (SDCARD to USB):
Code:
***** USB to SD or SD to USB multiple file copy example *****

This sketch will copy all files in the root directory of
a USB drive to SDCARD or from an SDCARD to USB drive.

There is define at the beginning of the sketch that can
you can change to determine the source and destination devices.
'#define USB_TO_SD 1'. The default is uncommented for USB to SDCARD.
Comment out this define to copy files from SDCARD to the USB drive

Press anykey to continue
Initializing USB MSC drive.
*** NOTE: If no USB drive is connected, sketch will hang here forever ***
Connect USB drive now if not connected and sketch will resume running...initialization done.

Initializing SD card...initialization done.


Copying 'MSCtesting.bas' from SD card to USB drive
Copied 534 bytes in 0.002624 seconds. Speed: 0.203506 MB/s

Copying '32MEGfile.dat' from SD card to USB drive
Copied 32768000 bytes in 2.760752 seconds. Speed: 11.869230 MB/s

Copying 'bench.dat' from SD card to USB drive
Copied 32768000 bytes in 2.765375 seconds. Speed: 11.849387 MB/s

Copying 'datalog.txt' from SD card to USB drive
Copied 380 bytes in 0.001752 seconds. Speed: 0.216895 MB/s

Copying 'copy.txt' from SD card to USB drive
Copied 32768000 bytes in 2.763748 seconds. Speed: 11.856363 MB/s

Copying 'test.txt' from SD card to USB drive
Copied 32768000 bytes in 2.758875 seconds. Speed: 11.877305 MB/s

Copying 'fail.jpg' from SD card to USB drive
Copied 45123 bytes in 0.005626 seconds. Speed: 8.020441 MB/s

Copying 'fontcnvt' from SD card to USB drive
Copied 16688 bytes in 0.003251 seconds. Speed: 5.133190 MB/s

Copying 'fontcnvt.c' from SD card to USB drive
Copied 955 bytes in 0.002624 seconds. Speed: 0.363948 MB/s

Copying 'sansurf.fnt' from SD card to USB drive
Copied 4096 bytes in 0.001248 seconds. Speed: 3.282051 MB/s

Copying 'sansurf.h' from SD card to USB drive
Copied 22050 bytes in 0.006877 seconds. Speed: 3.206340 MB/s

Copying 'SConscript' from SD card to USB drive
Copied 1211 bytes in 0.002627 seconds. Speed: 0.460982 MB/s

Copying 'sgl_dbl_click.png' from SD card to USB drive
Copied 11019 bytes in 0.003250 seconds. Speed: 3.390461 MB/s

Copying 'sgl_dbl_drag.png' from SD card to USB drive
Copied 25575 bytes in 0.004623 seconds. Speed: 5.532122 MB/s

All files in SDCARD root directory have been copied to the USB drive.
**** FINISHED ****

Hope it helps :unsure:

Edit: Fix incorrect SDCARD to USB drive output.
 
Last edited:
thank you wwatson.
i tested your Library and given code .it is working...thank you
but here two new things i never seen before
1st one ?
as your code Example in post #3 ( Usb files copying to Sd card ) yes ,, i placed 3 .wav files on usb drive . inserted usb drive into Teensy boards 's port
. After a Input from Serial monitor , I got Files copied to Sd Card. in your code i did'not understand , how serial input act in event???
is this function act as input??
C++:
void waitforInput()
{
  Serial.println("Press anykey to continue");
  while (Serial.read() == -1) ;
  while (Serial.read() != -1) ;
}
this is out of void loop() & void setup() . how it works??
if my sketch is like it
C++:
#include <Keypad.h>                               
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const uint8_t ROWS = 7;  // 7 rows
const uint8_t COLS = 4;  //4 columns       <<<< 1,2,3,7,8
char keys[ROWS][COLS] = {
    { 1, 2, 3, 4 },
    { 5, 6, 7, 8 },
    { 9, 10, 11, 12 },
    { 13, 14, 15, 16 },
    { 17, 18, 19, 20 },
    { 21, 22, 23, 24 },
    { 25, 26, 27, 28 }
};
uint8_t rowPins[ROWS] = { 33, 34, 35, 36, 37, 38, 39 }; 
uint8_t colPins[COLS] = { 40, 41, 14, 16 };         
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

#define SCREEN_WIDTH 128   
#define SCREEN_HEIGHT 32   
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C   
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
    Serial.begin(57600);
    kpd.setHoldTime(2000);
    if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
        Serial.println(F("SSD1306 allocation failed"));
        for (;;)
            ; 
    }
    display.display();
    delay(2000);
    display.clearDisplay();
    if (!(SD.begin(BUILTIN_SDCARD))) {
        while (1) {
            Serial.println("Unable to access the SD card");
            delay(500);
        }
    }
}

void loop() {
        if (kpd.getKeys()) {
        for (int i = 0; i < LIST_MAX; i++) 
        {    int mykey = (kpd.key[i].kchar);
                      if ((kpd.key[i].stateChanged)  && (mykey == 20))  //  -----------------------------------------Key Changed----------------
            {      switch (kpd.key[i].kstate) {
                    case PRESSED:
                    // Start  Copying  All files fom USB Drive To SD Card
                        break;
                    case RELEASED:
                    break;
                }
            }  //--------------------------------------------------------------------------------------------------
 }}} 

void SCN_TEXT() {
    display.clearDisplay();
    display.setTextSize(1);               
    display.setTextColor(SSD1306_WHITE);   
    display.setCursor(0, 0);
    display.print("ABCDE");
    display.display();
}
How to write (Input of Copying All files) in Pressed of mykey=20 ?????
2nd one ?? Report errors & event Monitoring in Serial Monitor change to Oled display
here is in code
C++:
 Serial.printf("\nCopying '%s' from USB drive to SD card\n",fname);
words ( \n , %s \n ) are new to me . i never seen before it . i have used text like ("Reading is : ") and variables,string, in bracts .
Can i write it for oled display like below
C++:
 Serial.printf("\nCopying '%s' from USB drive to SD card\n",fname);
into
C++:
   display.clearDisplay();
    display.setTextSize(1);               
    display.setTextColor(SSD1306_WHITE);   
    display.setCursor(0, 0);
    display.print("\nCopying '%s' from USB drive to SD card\n",fname);
    display.display();
printing next line will remove previous .. any idea???
As i took your example code in Post#3 and my example with Keypad& oled display in this post.
should i combine both sketch as below :
copy code before setup() from 1 >>> Paste in 2 before setup()
copy in setup() from 1 >>>Paste in 2 in setup()
copy in loop() from 1 >>> Paste in 2 in loop()
copy after loop() from 1 >>> Paste in 2 after loop
over all puzzle in mixing of code . ????
can i copy your entire code and paste into Tab2 of my Sketch ?? will it work ?? I never did it before
or any Other Trick ???
Thank you
 
@charnjit - A lot of questions :) I did not have a lot of the information about your setup. I see that you are using an Oled display and the driver for that type of display may not be setup to use "Serial.printf". Most of the code using "Serial.printf" can be done with "display.print" and "display.println". I have never used an Oled display and I am not familiar with with the drivers for them.

Unfortunately I will not have time to answer all of your questions right now, possibly tomorrow. You might want to get on the internet and search for information about "printf" and how it is used. Also use Arduinos reference guide to understand how "Serial.print", "Serial.prinln" and "Serial.read" are used with there arguments...
 
@charnjit - Ok, first question about "waitforInput()" answer I think is:
Code:
// Hangout here until a valid key is pressed then return.
void waitforInput()
{
  Serial.println("Press anykey to continue"); // Prompt user to press a key when ready to procced.
  while (Serial.read() == -1) ; // Wait for a charcter from the Serial  Monitor.
  while (Serial.read() != -1) ; // Wait for a valid character and exit if recieved.
}
Might no be exactly correct. See Arduino reference.

2nd question is about "Serial.printf()". I guess the easiest way to explain it is with an example of the same multi file copy sketch but changed to use "Serial.print", "Serial.println" and not use "Serial.printf". Here is the modified sketch:
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()
{
// Wait for Serial port to open (up to 5 milliseconds):
   while (!Serial && (millis() < 5000)) {
    ; // wait for serial port to connect.
  }

  Serial.print("***** USB to SD or SD to USB multiple file copy example *****\n\n");
//  Serial.print("%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");
  waitforInput();

  // 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);
      Serial.print("\nCopying ");
      Serial.print(fname);
      Serial.print(" from USB drive to SD card\n");
#else
//      Serial.printf("\nCopying '%s' from SD card to USB drive\n",fname);
      Serial.print("\nCopying ");
      Serial.print(fname);
      Serial.print(" from SD card to USB drive\n");
#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);
        Serial.print("An error occured while copying file ");
        Serial.print(fname);
        Serial.print(" to the SD drive!!\n");
      }
      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()
{
    // nothing happens after setup
}

// *********************************************************
// 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);
    Serial.print("Copied ");
    Serial.print(bytesRW);
    Serial.print(" bytes in ");
    Serial.print((1.0*finish)/1000000.0);
    Serial.print(" seconds. Speed: ");
    Serial.print(MegaBytes);
    Serial.print(" MB/s\n");
#endif

  }
  return 0; // 0 = success.
}

// Hangout here until a valid key is pressed then return.
void waitforInput()
{
  Serial.println("Press anykey to continue"); // Prompt user to press a key when ready to procced.
  while (Serial.read() == -1) ; // Wait for a charcter from the Serial  Monitor.
  while (Serial.read() != -1) ; // Wait for a valid character and exit if recieved.
}

If you look at this sketch starting at line 212 the single "serial.printf" is replaced by seven lines of "Serial.print". At my age it's a lot easier on the hands to type one line as apposed to typing 7 lines of code. But "Serial.printf" code consumes a lot more memory of code than "Serial.print" or "Serial.println" and on memory constrained MCU's like the Teensy1 and Teensy2 you could run out of memory very quickly using "Serial.printf". In fact, I'm not even sure if it was available back then.

Again I don't have an Oled display or a keypad like yours so I can't really do any testing, But I think using "display.print" and "display.println" should work the same as "Serial.print" and "Serial.println".

Good luck;)
 
Thank you sir,,
As we have a simple button state change example
C++:
int buttonPin = 5;
int buttonState = 0;
int lastButtonState = 0;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      Serial.println("Button Pressed");
        // Start copying All files from USB to SD Card
    } else {
      Serial.println("Button Released");
    }
  }
  lastButtonState = buttonState;
  delay(50);
}
In this example this is input part for button
C++:
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      Serial.println("Button Pressed");
// Start copying all files from USB to SD card
     }
  }
in your code at where We should set these lines???
You wrote copying functions in void setup() without using "if"condition .I dout , it should occur auto once, I wonder it is start on serial input. ???

After void loop() you mentioned "copying one file USB to SD" may I delete it, if I need to copying All file???

If already file exists on SD with same name, what will be???
I need here, remove older and paste new (overwrite)
I will try it mix with oled display as much my knowledge using urgent reports
Thank you,,
 
I must admit to not really understanding why you are doing this. Is it a one time operation, or will you need to do this regularly? Can you turn off the Teensy or must the Teensy be running?

To me if it is a one time task, the simplest approach would be just to turn off the Teensy, put the micro SD card into a micro SD card reader on your PC and also attach the USB disk, and just use your file explorer to copy the files. Obviously, if you wanted to learn how to access files on USB mounted drives, that is different. But if your goal is just to transfer some files, you don't need the infrastructure.

Now, it would be different if you were using a mounted flash file system using either the extra flash memory or a soldered flash memory chip since you can't remove those.

An alternative to having the Teensy reading a USB mounted drive and copying it to a micro SD card (or flash file system) is to use the MTP support. I don't recall whether MTP has made it to 1.60 beta #4 yet. Assuming it is not yet in, you would need to download and install the MTP_t4 library from:
Basically MTP allows the Teensy to connected to your computer as a series of removable disks. Once the MTP stuff is set up, you can copy files between your PC and the Teensy. You can delete, rename, etc. the files. The MTP library operates in the background, called from the main loop function.

I will attach an example that I modified to run on my Teensy:
 

Attachments

  • MtpPSram.ino
    11.6 KB · Views: 88
Last edited:
Thank you sir ,,,,,MichaelMeissner
I started to find "copying USB to SD card" only for transfer files to teeny built in SD card regularly.
Actually my teensy with audio board became a audio sampler project. I don't want remove SD card from board again and again. I like this option "use USB to SD card" as we discussed above.
can I not use & mix code"copying USB to SD card " with my "audio sampler project " code to use it regularly ??
Will it affect Audio sample play latency???
Will either code"copying USB to SD card " work ,or "audio sampler project"code???
If no, I will have to goto MTP .
Can I use & mix code "MTP" with my "Audio sampler project" code to use it regularly without affect latency ??
If both are for one time use , I have not use of it ....
Thank you,,
 
Thank you sir ,,,,,MichaelMeissner
I started to find "copying USB to SD card" only for transfer files to teeny built in SD card regularly.
Actually my teensy with audio board became a audio sampler project. I don't want remove SD card from board again and again. I like this option "use USB to SD card" as we discussed above.
can I not use & mix code"copying USB to SD card " with my "audio sampler project " code to use it regularly ??
Will it affect Audio sample play latency???
Will either code"copying USB to SD card " work ,or "audio sampler project"code???
If no, I will have to goto MTP .
Can I use & mix code "MTP" with my "Audio sampler project" code to use it regularly without affect latency ??
If both are for one time use , I have not use of it ....
Thank you,,
I don't know, you would have to test it out.

Off hand, I imagine that using MTP in the background could affect latency, but who knows. I imagine that when you are transferring files, you are not worried as much about latency, and it won't matter. If you aren't transferring files, it shouldn't affect the latency. The bit of code called from the 'loop' function will take a small amount of time to check to see if there is any USB traffic to act on.

In terms just copying files from the USB disk, you would have to integrate the code with your audio code. I suspect you would have to restructure the code so it doesn't in general just read/write the file and block and do nothing else. Unfortunately, the Arduino support is not really good at real multi-thread programming.
 
Thank you to give me option of file transfer "MTP" . before start this topic i never seen about MTP . yes i am interested in learning of MTP use. but at the spot by some limitation i can not use it , because of cable space in my project cabinet. i have made a narrow cabinet for teensy audio set before start this topic . you can see my cabinet:
IMG_20250519_203844.jpg
IMG_20250519_203817.jpg
I have to raised up teensy to program it for connecting data cable. And down after disconnect cable to fit upper cover.
after disconnect cable pic:
IMG_20250519_203653.jpg


& after fit cover

IMG_20250519_203523.jpg


recently i tried mix "Simple MSC example" of copying All file from usb to sd with "Simple Sd Audio play example". input for "copying" and "play .wav file" was by serial monitor .i used single .wav(500kb) file to be copied and play after copying process. it works .i got no problem. next i will try "Simple MSC Example " with my lengthy skecth . if i got any error or problem , i will report .let me test it . it will took some days . i will also try about use MTP. thank you for spot ....
 
Back
Top