Change original code to use SD Library instead of SdFat library?

I don't even know if this is possible but I am trying to change some code someone posted on a github to make an accelerometer (https://github.com/ammolytics/projects/tree/master/accelerometer). I can't seem to get the SdFat library to work with my board, but the SD library works just fine, I can read and write onto the card. I've never done any sort of coding before so I was wondering if someone could point me in the right direction as to how I would change this code to use the SD library instead of the SdFat library? Any help would be greatly appreciated.

I am using an Adafruit Feather M0 Bluefruit LE (nRF52832) with the Adalogger FeatherWing (RTC + SD).

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>
#include "RTClib.h"
#include "SdFat.h"


// Battery pin
#define VBATPIN A7

// I2C clock speed
#define I2C_SPEED 1000000
// Set range to 2G, 4G, 8G, 16G
#define ACCEL_RANGE LIS3DH_RANGE_8_G
// 5khz data rate
#define ACCEL_DATARATE LIS3DH_DATARATE_LOWPOWER_5KHZ
// Decimal precision for acceleration
#define ACCEL_PRECISION 3
// Separator character
#define SEP ","

// Enable debug logger.
// Note: Comment out before running in real-world.
#define DEBUG

#ifdef DEBUG
  #define DEBUG_PRINT(x)  Serial.print (x)
  #define DEBUG_PRINTLN(x)  Serial.println (x)
#else
  #define DEBUG_PRINT(x)
  #define DEBUG_PRINTLN(x)
#endif

RTC_PCF8523 rtc;

// change this to match your SD shield or module;
// Adafruit SD shields and modules: pin 10
const int chipSelect = 11;


// Filename format:  YYYYMMDDHHmm.csv
char filename[17];


unsigned long begin_us;
unsigned long begin_epoch;
unsigned long start_us;
unsigned long stop_us;
unsigned long counter = 0;


// software SPI
//Adafruit_LIS3DH lis = Adafruit_LIS3DH(LIS3DH_CS, LIS3DH_MOSI, LIS3DH_MISO, LIS3DH_CLK);
// hardware SPI
//Adafruit_LIS3DH lis = Adafruit_LIS3DH(LIS3DH_CS);
// I2C
Adafruit_LIS3DH lis = Adafruit_LIS3DH();

// set up variables using the SD utility library functions:
// File system object.
SdFat sd;
// Log file.
SdFile dataFile;


/**
 * Setup procedures.
 */
void setup() {
  #ifdef DEBUG
    Serial.begin(115200);
    while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
  #endif

  #ifdef DEBUG
    float measuredvbat = analogRead(VBATPIN);
    measuredvbat *= 2;    // we divided by 2, so multiply back
    measuredvbat *= 3.3;  // Multiply by 3.3V, our reference voltage
    measuredvbat /= 1024; // convert to voltage
    DEBUG_PRINT("VBat: " ); DEBUG_PRINTLN(measuredvbat);
  #endif

  /**
   * Initialize the Real Time Clock.
   */
  DEBUG_PRINTLN("Initializing RTC...");
  if (! rtc.begin()) {
    DEBUG_PRINTLN("Couldn't find RTC");
    while (1);
  }
  if (! rtc.initialized()) {
    DEBUG_PRINTLN("RTC is NOT running!");
  }
  DEBUG_PRINTLN("RTC initialized.");
  begin_us = micros();
  DateTime now = rtc.now();
  begin_epoch = now.unixtime();

  // Set filename based on timestamp.
  sprintf_P(filename, PSTR("%4d%02d%02d%02d%02d.csv"), now.year(), now.month(), now.day(), now.hour(), now.minute());
  DEBUG_PRINT("Filename: ");
  DEBUG_PRINTLN(filename);

  /**
   * Initialize the accelerometer.
   */
  DEBUG_PRINTLN("Initializing LIS3DH Sensor...");
  if (! lis.begin(LIS3DH_DEFAULT_ADDRESS)) {   // change this to 0x19 for alternative i2c address
    DEBUG_PRINTLN("Couldnt start");
    while (1);
  }
  // Set I2C high speedmode
  Wire.setClock(I2C_SPEED);
  lis.setRange(ACCEL_RANGE);
  lis.setDataRate(ACCEL_DATARATE);
  DEBUG_PRINTLN("LIS3DH initialized.");


  /**
   * Initialize the SD card and log file.
   */
  DEBUG_PRINTLN("Initializing SD card...");
  if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
    DEBUG_PRINTLN("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  DEBUG_PRINTLN("Card initialized.");

  if (! dataFile.open(filename, O_CREAT | O_APPEND | O_WRITE)) {
     DEBUG_PRINTLN("Could not open file...");
     while (1);
  }
  // Write header row to file.
  dataFile.println("timestamp (s), start (µs), accel x (G), accel y (G), accel z (G)");
  dataFile.sync();
  
  // Check to see if the file exists:
  if (! sd.exists(filename)) {
    DEBUG_PRINTLN("Log file doesn't exist.");
    while (1);
  }

  DEBUG_PRINTLN("Ready!");
  DEBUG_PRINTLN("timestamp (s), start (µs), delta (µs), accel x (G), accel y (G), accel z (G)");
}


/**
 * Main Loop
 */
void loop() {
  read_accel();
  log_timers();
  log_accel();
  counter++;

  if (counter >= 1000) {
    write_sd();
    counter = 0;
  }
}


/**
 * Read from the accelerometer sensor and measure how long the op takes.
 */
void read_accel() {
  start_us = micros();
  lis.read();
  stop_us = micros();
}


/**
 * Output the timing info.
 */
void log_timers() {
  DEBUG_PRINT(begin_epoch + ((stop_us - begin_us) / 1000000));
  DEBUG_PRINT(SEP);
  DEBUG_PRINT(stop_us);
  DEBUG_PRINT(SEP);
  // Include time delta in debug output.
  DEBUG_PRINT(stop_us - start_us);
  DEBUG_PRINT(SEP);

  // Write timestamp to file.
  // Roughly equivalent to calling rtc.now().unixtime(), without 1ms latency.
  dataFile.print(begin_epoch + ((stop_us - begin_us) / 1000000));
  dataFile.print(SEP);
  // Write timers to file.
  dataFile.print(stop_us);
  dataFile.print(SEP);
}


/**
 * Output the acceleration info.
 */
void log_accel() {
  #ifdef DEBUG
    Serial.print(lis.x_g, ACCEL_PRECISION);
    Serial.print(SEP);
    Serial.print(lis.y_g, ACCEL_PRECISION);
    Serial.print(SEP);
    Serial.print(lis.z_g, ACCEL_PRECISION);
    Serial.println();
  #endif
  // Write acceleration to file.
  dataFile.print(lis.x_g, ACCEL_PRECISION);
  dataFile.print(SEP);
  dataFile.print(lis.y_g, ACCEL_PRECISION);
  dataFile.print(SEP);
  dataFile.print(lis.z_g, ACCEL_PRECISION);
  // Write newline.
  dataFile.println();
}


/**
 * Flush buffer, actually write to disk.
 * This can take between 9 and 26 milliseconds. Or ~10ms with SDfat.
 */
void write_sd() {
  DEBUG_PRINTLN("Writing to SD card");
  unsigned long pre_write = micros();
  dataFile.sync();
  DEBUG_PRINT("Write ops took: ");
  DEBUG_PRINTLN(micros() - pre_write);
}

The Arduino SD library actually uses the SDFat library. There is no reason to change.

If you want to fix the posted code, post any error messages that you get, and explain what goes wrong. Also post a wiring diagram.

Hint: when using an unfamiliar library, always make sure that one or more of the examples included with the library run on your board, before doing anything else.

Interesting, I can get the example files from the SD library to work just fine, but I can't get anything to work on the SDFat library so I assumed my board didn't like the library. When I upload the script it doesn't recognize the SD card, in the serial monitor I get "Initializing SD card... Card failed, or not present."

Please do not modify the original post. Doing so makes it difficult or impossible for others to follow the thread.

Post the error messages in a new post, and explain what goes wrong.

I apologize I should have been more clear. I don't actually get any error codes, it just doesn't ever initialize the SD card. I will keep that in mind for future threads!

Explain how you know that it doesn't initialize the card.

I suggest to start over, and MAKE SURE that a library example runs on your setup, with the present SD card.

In the serial monitor it goes through the setup procedures. The RTC and the triple axis accelerometer both finish initializing but the SD fails. I do know that the card works because I can use the SD library examples to both read and write to the card.
Screenshot 2023-09-29 150424

Try a SDFat library example, and if it fails, check that the card is properly formatted.

Ok so I tried the ReadWrite example in the SdFat library and the initialization failed. the only thing I changed was the cs pin to pin 11 (I know it is this pin because it worked with the SD library ReadWrite example). Should I still reformat the card even though it just worked with the SD library example? I am using a 32gb card in the fat32 format. Also (I'm not sure if this would affect anything but I figured it was worth adding) the card is not empty. With the SD library it didn't recognize the card until I added a blank text document to the card, so that blank document is still there.

/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
//#include <SD.h>
#include "SdFat.h"
SdFat SD;

#define SD_CS_PIN 11
File myFile;

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


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

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

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}



Which you forgot to mention until now.

If you are using an AVR Arduino, that is the problem. Pin 10 (default CS) must be declared OUTPUT, or the SPI module won't work as expected.

You cannot arbitrarily change pins without consequences.

And what about THIS pin 11?

 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13

Please post an accurate and complete wiring diagram.

I apologize if I am reading this wrong, I am very new to this whole space and realize this is a massive undertaking for my non-existent skill level so I appreciate your help. I assume the AVR you mentioned is a board, which is not what I am using. I am using an adafruit Feather M0 which has the CS pin on pin 11. the sck mosi and miso pins are 24, 23, and 22 respectfully. I am not sure how to post a complete wiring diagram, but I could post a photo of my breadboard and wiring if that would help?

And they're also not telling you that this is the second topic they've opened on the same problem...

So the comments in the posted code are completely misleading.

I have not used the Adafruit Feather M0 with an SD card, so I can't advise. Adafruit generally has excellent getting started guides and that is your best source of information, along with the Adafruit user forum.

Ok I appreciate all your help anyways!! I will see what I can do from here.

Please do not cross post. It wastes everyone's times and is against forum rules.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.