Duplicating an image on sd card

Hi,

I am rather new to sd cards and files in general.

I am trying to duplicate an image on the sd but for some reason I am only getting half the bytes in the 2nd file.

I am writing the new file in chunks of 100 bytes because it is faster. byte by byte for 44kb file takes about 10min whereas in 100 byte chunks it is a few seconds.

Can someone please figure out what I am doing wrong?

Thanks in advance :slight_smile:

DuplicateFile.ino (1.42 KB)

Just post the code, so we can all read it.

#include <SPI.h>
#include <SD.h>
#define arraySize 100
char inData[arraySize];

File myFile;
File myFile2;
int index = 0;
int counter = 0;


void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(19200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("SUNP0004.jpg");
  myFile2 = SD.open("test.jpg", FILE_WRITE);
  Serial.println("Created test.jpg");
  if (myFile) {
    Serial.println("test.txt:");
    Serial.println(myFile.available());
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      if (myFile2) {
        char inChar;

        while (myFile.available() > 0 && index < arraySize - 1)
        {
          inChar = myFile.read();

          inData[index] = inChar;
          index++;
          if (index == arraySize - 1)
          {
            myFile2.print(inData);
            Serial.println(counter);
            counter++;
            index =0;
          }
      }  
    }
  }
  }
  else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
      // close the file:
      myFile2.close();
      myFile.close();
      Serial.println("done. jpg test");
}

void loop()
{
}

ErrorNaik:
I am writing the new file in chunks of 100 bytes because it is faster. byte by byte for 44kb file takes about 10min whereas in 100 byte chunks it is a few seconds.

Can someone please figure out what I am doing wrong?

When initializing the SD library and when the ChipSelect/SlaveSelect of the SD card is different from the hardware ChipSelect pin of the SPI interface, you would have to set the hardware ChipSelect to OUTPUT first:

pinMode(SS, OUTPUT);
if (!SD.begin(4)) {

BTW: Your programming logic is only buffering the writes, but you do the reads single byte for single byte for single byte for single byte. That's not really fast.

For fastest copying it would be much faster if you

  • read a chunk of bytes
  • write a chunk of bytes
    You can use the same buffer for both.