I have been having lots of problems with my SD card attachment which is connected to a Teensy 4.0 along with a WIZ850IO.

I have followed all the guidelines regarding setup. I have also tried different SD cards. Using the SD library, the card would only be recognized about half the time.

After I gave up on the Teensy's SD library, I switched to the SDFat-Beta library. In this case, the card is recognized 100% of the time.

However, after writing a couple of relatively small files (20kb), the card stops writing and the filesystem is corrupted with very large files (1 MB).

Are there any guidelines to avoid this? I have spent hours trying to resolve this but no luck.

My setup code is below. Thanks in advance for any help.


Code:
#include <SPI.h>
#include "SdFat.h"
SdFat SD;

File myFile;
const int chipSelect = 4;   // Wiz820+SD board: pin 4

void setup()
{
  //------------------------------------------------------------
  //https://www.pjrc.com/store/wiz820_sd_adaptor.html#init
  //https://github.com/PaulStoffregen/Ethernet

  pinMode(9, OUTPUT);
  digitalWrite(9, LOW);    // begin reset the WIZ820io
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);  // de-select WIZ820io
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);   // de-select the SD Card
  digitalWrite(9, HIGH);   // end reset pulse

  //------------------------------------------------------------
  int SDFail = 0;
  if (!SD.begin(chipSelect))
  {
    if (SD.card()->errorCode())
    {
      Serial.println("   SD initialization failed!");
      SDFail = 1;
      //return;
    }
  }
  if (SDFail == 0)  Serial.println(">>>   SD SUCCESS.");
   //------------------------------------------------------------
   for (int i=0; i <= 4; i++){
      write2SD();
      delay(1000);
   } 
}

void write2SD()
{
  String tempStuff = String(truckID) + ".scn";
  myFile = SD.open(tempStuff.c_str(), FILE_WRITE);

  if (myFile)
  {
    myFile.print(triggerTime[1]);
    myFile.print("  ");
    myFile.println(triggerTime[0]);


    for (int SN = 0; SN < 3; SN++)           
    {
      for (int j = 1; j <= scan[SN] - 1; j++)
      {
        myFile.println("   ");
        tempStuff =  "Scan: " + String(j) ;
        myFile.println(tempStuff.c_str());
        for (int k = 0; k < 16; k++)
        {
          tempStuff =  String(k) + "," + String(BUFFER[SN][j][k][0]) + "," + String(BUFFER[SN][j][k][1]);
          myFile.println(tempStuff.c_str());
        }    
      }    
    }    

    myFile.close();
    Serial.println("SD File Closed");
  }
  else
  {
    Serial.println("ERROR: Cannot open SD File!");
  }
}