SD card works with Example, Cant find my mistake in code!

As described in the title my project uses multiple devices. Mainly a DS3231 RTC, MPU 6050, A couple of level shifters to shift the logic level from my 3.3v Seeeduino Xiao.
A I2C .96inch OLED. Last but not least the SD card module with built in level shifter.

Yes I know SD cards run better natively at 3.3v however due to the fact all my other devices are 5V id like to keep it this way. I have however tested removing and bypassing the 3.3V regulator on a spare sd module I had, feeding it 3.3v directly. It does work with example sketch but not with my code.

I am aware that the string class is incredibly inefficient use of sram, However I am still new to this and haven't had the time to look into it yet. I do not believe this is my problem as the code never manages to open the file. It will initialize the card no problem, but when it comes to writing it doesn't work.

Outside of my main sketch the sd card works on its own, I figure im getting some interference between a couple of the libraries however im unable to work out which library is causing me the
issues.

My code is sloppy please be kind however, constructive criticism and pointers are well appreciated. I've been at this for two days now ready to start banging my head against a wall so any help is more than appreciated.

<--------- Working example sketch

<--------- Writing to card, Datalogger example.

My code

#include "SSD1306Ascii.h"
#include "SSD1306AsciiWire.h"
#include <Arduino.h>
#include <TinyMPU6050.h>
#include <RTCZero.h>
#include <Wire.h>
#include <FastLED.h>
#include <SPI.h>
#include <SD.h>


MPU6050 mpu (Wire);
RTCZero rtc;

// 0X3C+SA0 - 0x3C or 0x3D
#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiWire oled;

/*
  //Change these values to set the current initial time
  const byte seconds = 0;
  const byte minutes = 47;
  const byte hours = 15;

  //Change these values to set the current initial date
  const byte day = 14;
  const byte month = 11;
  const byte year = 21;

*/
const int chipSelect = 6;
const int MasterPwrRelay = 8;
const int PwrSw = 7;
const int SelectorSw = 0;



// Define proper RST_PIN if required.;
#define RST_PIN -1
#define DATA_PIN_STRIP1   3
#define DATA_PIN_STRIP2   6
#define DATA_PIN_STRIP3   7
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
const int NUM_LEDS1 = 110;
const int NUM_LEDS2  =  40;
const int NUM_LEDS3  =  10;


const int BRIGHTNESS = 255;
const int FRAMES_PER_SECOND = 120;

CRGB leds1[NUM_LEDS1]; // Setting up 3 seperate lightning zones.
CRGB leds2[NUM_LEDS2];
CRGB leds3[NUM_LEDS3];
bool SelectorSwStatus = 0;
bool lastswitchstatus = 0;

void setup() {

  // Communication Initilization...
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Wire.begin();
  Wire.setClock(400000L);
  rtc.begin(); // initialize RTC

#if RST_PIN >= 0
  oled.begin(&Adafruit128x32, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x32, I2C_ADDRESS);
#endif // RST_PIN >= 0

  oled.setFont(Adafruit5x7);


  oled.clear();
  // first row
  oled.set2X();
  oled.println(F("Comm Setup"));
  oled.println(F("This may take"));
  oled.print(F("a moment"));

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


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

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println(F("Card failed, or not present"));
    // don't do anything more:
    while (1);
  }
  Serial.println(F("card initialized."));



  //Setting the controllers pin modes...
  pinMode(SelectorSw, INPUT_PULLUP);       // sets the digtial pin as input

  //MPU 6050 Initialisation and calibration Sequence.

  // Initialization
  mpu.Initialize();

  // Calibration
  Serial.println("=====================================");
  Serial.println(F("Starting calibration..."));
  oled.clear();
  oled.set2X();
  oled.println(F("Gyro Cali... "));
  oled.set1X();
  oled.println(F("This may take"));
  oled.print(F("a moment"));

  mpu.Calibrate();
  Serial.println(F("Calibration complete!"));

  oled.clear();
  oled.set2X();
  oled.println(F("Gyro Cali..."));
  oled.set2X();
  oled.println(F("Successful"));


  delay(5000);
  oled.clear();
  // tell FastLED about the LED strip configurations & Set the strip brightness.
  FastLED.addLeds<LED_TYPE, DATA_PIN_STRIP1, COLOR_ORDER>(leds1, NUM_LEDS1).setCorrection(TypicalLEDStrip);
  FastLED.addLeds<LED_TYPE, DATA_PIN_STRIP2, COLOR_ORDER>(leds2, NUM_LEDS2).setCorrection(TypicalLEDStrip);
  FastLED.addLeds<LED_TYPE, DATA_PIN_STRIP3, COLOR_ORDER>(leds3, NUM_LEDS3).setCorrection(TypicalLEDStrip);
  FastLED.setBrightness(BRIGHTNESS);


  if (SelectorSwStatus = 0) {
    lastswitchstatus = 0;
  }
  else {
    lastswitchstatus = 1;
  }
}


// List of patterns to cycle through.  Each is defined as a separate function below.
typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm,};

int gCurrentPatternNumber = 0; // Index number of which pattern is current
int gHue = 0; // rotating "base color" used by many of the patterns

const char* myStrings[] = {"Rainbow", "RainbowWithGlitter", "Confetti", "Sinelon", "juggle", "bpm"};

void loop() {

  String dataString = "";

  mpu.Execute();
  String TIMEString = String(rtc.getHours()) + ":" + String(rtc.getMinutes()) + ":" + String(rtc.getSeconds());
  dataString = String(TIMEString) + "," + String(mpu.GetAccX(), 3) + "," + String(mpu.GetAccY(), 3) + "," + String(mpu.GetAccZ(), 3) + "," + String(mpu.GetGyroX(), 3) + "," + String(mpu.GetGyroY(), 3) + "," + String(mpu.GetGyroZ(), 3) + "," + String(mpu.GetAngX(), 3) + "," + String(mpu.GetAngY(), 3) + "," + String(mpu.GetAngZ(), 3) ; //


  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  delay(250);
  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    // print to the serial port too:
    Serial.println(dataString);
    dataFile.close();
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println(F("error opening datalog.csv"));
  }

  SelectorSwStatus = digitalRead (SelectorSw);

  // Call the current pattern function once, updating the 'leds' array
  gPatterns[gCurrentPatternNumber]();

  int i  = 0;
  while (i == 0) {

    oled.set2X();
    oled.println(myStrings[gCurrentPatternNumber]);
    i++;
  }


  // send the 'leds' array out to the actual LED strip
  FastLED.show();
  // insert a delay to keep the framerate modest
  FastLED.delay(1000 / FRAMES_PER_SECOND);

  // do some periodic updates
  EVERY_N_MILLISECONDS( 20 ) {
    gHue++;  // slowly cycle the "base color" through the rainbow
  }

  if (SelectorSwStatus != lastswitchstatus) {
    Serial.println(F("Next Pattern Request"));
    nextPattern();
    delay(250);

    oled.clear();
    oled.set2X();
    oled.println(myStrings[gCurrentPatternNumber]);
    if (SelectorSwStatus == 1) {
      lastswitchstatus = 1;
    }

    else {
      lastswitchstatus = 0;

    }
  }


}




#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))



void nextPattern()
{
  // add one to the current pattern number, and wrap around at the end
  gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
  Serial.println(F("Next Pattern"));
}

void rainbow()
{

  // FastLED's built-in rainbow generator
  fill_rainbow( leds1, NUM_LEDS1, gHue, 7);
  // FastLED's built-in rainbow generator
  fill_rainbow( leds2, NUM_LEDS2, gHue, 7);
  // FastLED's built-in rainbow generator
  fill_rainbow( leds3, NUM_LEDS3, gHue, 7);


}

void rainbowWithGlitter()
{
  // built-in FastLED rainbow, plus some random sparkly glitter
  rainbow();
  addGlitter(80);



}

void addGlitter( fract8 chanceOfGlitter)
{
  if ( random8() < chanceOfGlitter) {
    leds1[ random16(NUM_LEDS1) ] += CRGB::White;
  }

  if ( random8() < chanceOfGlitter) {
    leds2[ random16(NUM_LEDS2) ] += CRGB::White;
  }

  if ( random8() < chanceOfGlitter) {
    leds3[ random16(NUM_LEDS3) ] += CRGB::White;
  }


}


void confetti()
{
  // random colored speckles that blink in and fade smoothly
  fadeToBlackBy( leds1, NUM_LEDS1, 10);
  int pos1 = random16(NUM_LEDS1);
  leds1[pos1] += CHSV( gHue + random8(64), 200, 255);


  // random colored speckles that blink in and fade smoothly
  fadeToBlackBy( leds2, NUM_LEDS2, 10);
  int pos2 = random16(NUM_LEDS2);
  leds2[pos2] += CHSV( gHue + random8(64), 200, 255);


  // random colored speckles that blink in and fade smoothly
  fadeToBlackBy( leds3, NUM_LEDS3, 10);
  int pos3 = random16(NUM_LEDS3);
  leds3[pos3] += CHSV( gHue + random8(64), 200, 255);


}

void sinelon()
{
  // a colored dot sweeping back and forth, with fading trails
  fadeToBlackBy( leds1, NUM_LEDS1, 20);
  int pos1 = beatsin16( 13, 0, NUM_LEDS1 - 1 );
  leds1[pos1] += CHSV( gHue, 255, 192);

  // a colored dot sweeping back and forth, with fading trails
  fadeToBlackBy( leds2, NUM_LEDS2, 20);
  int pos2 = beatsin16( 13, 0, NUM_LEDS2 - 1 );
  leds2[pos2] += CHSV( gHue, 255, 192);

  // a colored dot sweeping back and forth, with fading trails
  fadeToBlackBy( leds3, NUM_LEDS3, 20);
  int pos3 = beatsin16( 13, 0, NUM_LEDS3 - 1 );
  leds3[pos3] += CHSV( gHue, 255, 192);

}

void bpm()
{
  // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
  uint8_t BeatsPerMinute1 = 62;
  CRGBPalette16 palette1 = PartyColors_p;
  uint8_t beat1 = beatsin8( BeatsPerMinute1, 64, 255);
  for ( int i = 0; i < NUM_LEDS1; i++) { //9948
    leds1[i] = ColorFromPalette(palette1, gHue + (i * 2), beat1 - gHue + (i * 10));
  }
  // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
  uint8_t BeatsPerMinute2 = 62;
  CRGBPalette16 palette2 = PartyColors_p;
  uint8_t beat2 = beatsin8( BeatsPerMinute2, 64, 255);
  for ( int i = 0; i < NUM_LEDS2; i++) { //9948
    leds2[i] = ColorFromPalette(palette2, gHue + (i * 2), beat2 - gHue + (i * 10));
  }
  // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
  uint8_t BeatsPerMinute3 = 62;
  CRGBPalette16 palette3 = PartyColors_p;
  uint8_t beat3 = beatsin8( BeatsPerMinute3, 64, 255);
  for ( int i = 0; i < NUM_LEDS3; i++) { //9948
    leds3[i] = ColorFromPalette(palette3, gHue + (i * 2), beat3 - gHue + (i * 10));
  }



}

void juggle() {
  // eight colored dots, weaving in and out of sync with each other
  fadeToBlackBy(leds1, NUM_LEDS1, 20);
  byte dothue1 = 0;
  for ( int i = 0; i < 8; i++) {
    leds1[beatsin16( i + 7, 0, NUM_LEDS1 - 1 )] |= CHSV(dothue1, 200, 255);
    dothue1 += 32;
  }

  // eight colored dots, weaving in and out of sync with each other
  fadeToBlackBy(leds2, NUM_LEDS2, 20);
  byte dothue2 = 0;
  for ( int i = 0; i < 8; i++) {
    leds2[beatsin16( i + 7, 0, NUM_LEDS2 - 1 )] |= CHSV(dothue2, 200, 255);
    dothue2 += 32;
  }

  // eight colored dots, weaving in and out of sync with each other
  fadeToBlackBy(leds3, NUM_LEDS3, 20);
  byte dothue3 = 0;
  for ( int i = 0; i < 8; i++) {
    leds3[beatsin16( i + 7, 0, NUM_LEDS3 - 1 )] |= CHSV(dothue3, 200, 255);
    dothue3 += 32;
  }

}

What I have tried...... Rewired it like a dozen times, however the example sketches work so I doubt this is the issue. I have searched far and wide across the web for someone else experiencing the same issue. Have yet to find something similar.
The most frustrating part is if I open the file in setup it works. Trying to open in loop fails every time. Could this be a SPI speed problem?? I apologize as I do not have an great wiring diagram as it is still a prototype on a breadboard.

I will also include the serial monitor below and compiler information, maybe some of you pros might spot something I do not see. Thanks

Cory

Just as I finished typing this post and wanting to prove it does not work it started working again. Intermittent af. So confused, anyone have any clarity or ideas to provide Thanks..

The chip select pin for the SD card is pin 6. The data pin for your second set of LEDs is pin 6. It can't be both.

1 Like

omg..... facepalm... 2 days looking at this hahah
Thanks you so much!!!