Home > other >  Arduino: Read from SD card to char array, then save to SD card
Arduino: Read from SD card to char array, then save to SD card

Time:11-06

I am working with Arduino and Lora. Arduino A has a camera, Lora radio and SD card. Arduino B has the same setup minus the camera. Plan is to take a picture on Arduino A and save it to the SD card, then read and via Lora send to Arduino B which will save the information on its own SD card.

My current milestone is to read a test text file in the SD card and save it as a copy on the same card, all within Arduino A.

This worked reading and writing byte by byte using the standard SD library, however it's too slow.

I want to read 100 bytes (eventually 512) and save it to a buffer (char array), write those 100 bytes to the SD card in one write instruction, and repeat until the file is completly written.

I am not succeding in spliting the text into blocks, especially when there are less than 100 bytes in the file. Beguiner at C. Code follows. Thank you!

oFile = SD.open("message.txt", FILE_READ); // Original file
cFile = SD.open("message2.txt", FILE_WRITE); // Copy
int cIndex = 0;
char cArray[101]; // Buffer for the blocks of data
int cByteTotal = oFile.available(); // Get total bytes from file in SD card.

for(int i=0; i < cByteTotal ; i  ){ // Looping
   cArray[cIndex] = (char)myFile.read(); //Cast byte as char and save to char array
      if (cIndex == 100 ){ // Save 100 bytes in buffer
         cArray[cIndex   1] = '\0'; // Terminate the array?
         Serial.println(String(cArray)); // Print to console
         cFile.write(cArray); // Save 100 bytes to SD card.
         memset(cArray, 0, sizeof(cArray)); // Clear the array so that its ready for next block
         cIndex = -1; // Reset cIndex for next loop
      }
      if (cByteAvailable <= 99){ // When cByteTotal is less than 100...
         Serial.print("Last block");
      }
    cIndex  ;
}
oFile.close();
cFile.close();

CodePudding user response:

From the SD.read() documentation I would suggest using the read(buf, len) format to read a maximum of 100 bytes per go. And similarly for SD.write() . Something like this should go faster:

int cByteTotal = oFile.available();
while (cByteTotal > 0) {
    int length = cByteTotal < 100 ? cByteTotal : 100;
    if (length < 100) {
        Serial.print("Last block");
    }
    oFile.read(cArray, length);
    cFile.write(cArray, length);
    cByteTotal -= length;
}
oFile.close();
cFile.close(); 
  • Related