Problem with SD-Card Module

Hello everyone. I am currently working on a small Project with an Arduino Pro Mini 3.3V.

Right now i am trying to add an SD-Card Module to my already existing code, but for some reason the code wont run anymore now. It feels like a storage problem or something because when i remove all my Serial Outputs it starts working partially but the Arduino tells me that he cant find/open the file, which works with the example code from the Arduino IDE without any problems.

The Arduino IDE tells me that i am only using 64 and 57% of storage tho, so i dont know whats going on. Maybe i just made a mistake when implementing the example code for the SD-Card into my own Code.

I know that my code is nowhere near perfect but so far everything worked as intended.

Any help is appreciated. I know for sure that the SD-Card Module works and also my code. It only stops working if I add:

File Textdatei = SD.open("Messdaten.txt", FILE_WRITE);            // An dieser Stelle wird die Textdatei erstellt. Unsere Textdatei soll "test" heißen und im Format ".txt" (Text) erstellt werden.

    String ausgabe_sd = String(buff) + "," + String(Temperatur) + "," + String(Luftfeuchte) + "\n";

    if (Textdatei) {
      Textdatei.println(ausgabe_sd);
      Textdatei.close();
    } else {
      Serial.println("Konnte Messdaten.txt nicht öffnen/finden");
    }

I have included the needed librarys so thats not the problem.

Heres the code:

/*
  //---------------------------BMP180--------------------------
  #include <Wire.h>
  #include <Adafruit_BMP085.h>
  Adafruit_BMP085 bmp;
*/

//---------------------------DHT22---------------------------
#include <DHT.h>
#define DHTPIN 3
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

//--------------------------SD-Card--------------------------
#include <SPI.h>
#include <SD.h>

//---------------------------DS3231--------------------------
#include <ds3231.h>
#include <Wire.h>

#define BUFF_MAX 256

uint8_t sleep_period = 1;       // the sleep interval in minutes between 2 consecutive alarms

// how often to refresh the info on stdout (ms)
unsigned long prev = 1000, interval = 1000;

void set_next_alarm(void) {
  struct ts t;
  unsigned char wakeup_min;

  DS3231_get(&t);

  // calculate the minute when the next alarm will be triggered
  wakeup_min = (t.min / sleep_period + 1) * sleep_period;
  if (wakeup_min > 59) {
    wakeup_min -= 60;
  }

  // flags define what calendar component to be checked against the current time in order
  // to trigger the alarm
  // A2M2 (minutes) (0 to enable, 1 to disable)
  // A2M3 (hour)    (0 to enable, 1 to disable)
  // A2M4 (day)     (0 to enable, 1 to disable)
  // DY/DT          (dayofweek == 1/dayofmonth == 0)
  uint8_t flags[4] = { 0, 1, 1, 1 };

  // set Alarm2. only the minute is set since we ignore the hour and day component
  DS3231_set_a2(wakeup_min, 0, 0, flags);

  // activate Alarm2
  DS3231_set_creg(DS3231_CONTROL_INTCN | DS3231_CONTROL_A2IE);
}

//---------------------------Sleep---------------------------
#include <avr/sleep.h>
#include <avr/power.h>

int pin2 = 2;

void pin2Interrupt(void) {
  /* This will bring us back from sleep. */

  /* We detach the interrupt to stop it from
     continuously firing while the interrupt pin
     is low.
  */
  detachInterrupt(0);
}

void enterSleep(void) {
  /* Setup pin2 as an interrupt and attach handler. */
  attachInterrupt(0, pin2Interrupt, LOW);
  delay(100);

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();

  sleep_mode();

  /* The program will continue from here. */

  /* First thing to do is disable sleep. */
  sleep_disable();
}

//------------------------Variablen--------------------------
unsigned long previousMillis;
unsigned long currentMillis;
const long interval_2 = 2000;
float Temp_sum = 0;
float Luftfeuchte_sum = 0;
int x = 0;
int done = 0;
float Temperatur = 0;
float Luftfeuchte = 0;

//--------------------------Setup----------------------------
void setup() {
  Serial.begin(9600);
  while (!Serial);
  Wire.begin();
  /*
    //BMP180
    if (!bmp.begin()) {
    Serial.println("Sensor nicht gefunden!");
    while (1) {}
    } else if (bmp.begin()) {
    Serial.println("Sensor gefunden!");
    }*/

  /*
    Serial.println("           Starte Initialisierung");
    Serial.println("---------------------------------------------");
  */

  //DHT22
  dht.begin();

  /*
    //SD-Karte
    Serial.println("- Initialisiere SD-Karte");

    if (!SD.begin(5)) {                                                     // Wenn die SD-Karte nicht (!SD.begin) gefunden werden kann, ...
    Serial.println("  - SD-Karten Initialisierung fehlgeschlagen!");      // ... soll eine Fehlermeldung ausgegeben werden. ....
    return;
    } else {
    Serial.println("  - SD-Karten Initialisierung abgeschlossen");        // ... Ansonsten soll die Meldung "Initialisierung abgeschlossen." ausgegeben werden.
    }
  */

  //DS3231
  DS3231_init(DS3231_CONTROL_INTCN);
  DS3231_clear_a2f();
  set_next_alarm();

  //Sleep
  pinMode(pin2, INPUT);

  /*
    Serial.println("---------------------------------------------");
    Serial.println("      Initialisierung abgeschlossen");
    Serial.println("              Starte Programm");
    Serial.println("---------------------------------------------\n");
  */

  delay(2000);
}

//--------------------------Main-----------------------------
void loop() {

  /*
        Serial.print("Temperatur BMP180 = ");
        Serial.print(float(bmp.readTemperature()));
        Serial.println(" °C");

        float luftdruck = (bmp.readPressure() / 100) + 20;
        Serial.print("Luftdruck BMP180 = ");
        Serial.print(luftdruck);
        Serial.println(" hPa");
  */

  if (DS3231_triggered_a2()) {                                        //Wenn DS3231 (RTC) Alarm ausgelöst --> zurücksetzen
    set_next_alarm();
    DS3231_clear_a2f();
  }

  if (done != 1) {                                                    //Solange nicht Messung abgeschlossen
    if (x < 5) {                                                      //Schleife um 4 Messungen zu machen
      currentMillis = millis();
      if (currentMillis - previousMillis >= interval_2) {             //2 Sekunden Pause zwischen Messung wegen DHT22
        Temp_sum = Temp_sum + dht.readTemperature();
        Luftfeuchte_sum = Luftfeuchte_sum + dht.readHumidity();
        previousMillis = currentMillis;
        Serial.println("Test");
        x += 1;
      }
    }
    if (x == 4) {                                                     //Wenn 4 Messungen durchgeführt --> Temperatur und Luftfeuchte Ausgabewerte berechnen
      Temperatur = Temp_sum / 4;
      Luftfeuchte = round(Luftfeuchte_sum / 4);
      done = 1;
    }
  } else if (done == 1) {                                                                     //Wenn Messungen fertig

    /*
      String ausgabe_temp = "Temperatur DHT22: " + String(Temperatur) + "°C";
      Serial.println(ausgabe_temp);

      String ausgabe_luftfeuchte = "Luftfeuchtigkeit DHT22: " + String(Luftfeuchte) + "%\n";
      Serial.println(ausgabe_luftfeuchte);
    */

    char buff[BUFF_MAX];
    struct ts t;

    DS3231_get(&t);                                                                                               //Zeit messen
    snprintf(buff, BUFF_MAX, "%d.%02d.%02d %02d:%02d:%02d", t.year - 1900, t.mon, t.mday, t.hour, t.min, t.sec);  //Puffer mit Zeit beschreiben

    /*
      String ausgabe_sleep = "Going to sleep at: " + String(buff) + "\n";
      Serial.println(ausgabe_sleep);
    */

    File Textdatei = SD.open("Messdaten.txt", FILE_WRITE);            // An dieser Stelle wird die Textdatei erstellt. Unsere Textdatei soll "test" heißen und im Format ".txt" (Text) erstellt werden.

    String ausgabe_sd = String(buff) + "," + String(Temperatur) + "," + String(Luftfeuchte) + "\n";

    if (Textdatei) {
      Textdatei.println(ausgabe_sd);
      Textdatei.close();
    } else {
      Serial.println("Konnte Messdaten.txt nicht öffnen/finden");
    }

    x = 0;
    done = 0;
    Temp_sum = 0;
    Luftfeuchte_sum = 0;
    enterSleep();                                                                            //Arduino schlafen schicken (Stromsparen)
  }
}

Start with simple code and work your way up to more complex.

Read instructions at beginning of the forum would be a GOOD start.

Hi, sorry i had to edit my post since i messed up when uploading the code. Uploaded an older Version.

First of all thanks for your answer.

Simple code wont really help me here and also i understand what the code should do. I just cant figure out where my problem is. I have been troubleshooting for like 2 hours now. As said, when removing Serial Outputs the Code starts working again but then somehow the Arduino cant find the SD-Card Module.

Maybe its also a problem with some of the pins that i am using. For example that some functions wont work if one pin is used for something, like I2C or SPI. Hope that was somehow understandable, English is not my mother language.

If that helps here is also the wiring:

Wiring
DHT22:
Data – Pin 3
VCC – 3.3V
GND – GND
DS3231:
SDA – SDA
SCL – SCL
SQW - Pin 2
VCC – 3.3V
GND – GND
BMP180:
SDA – SDA
SCL – SCL
VCC – 3.3V
GND – GND
SD-Card Module:
CS – Pin 10
SCK – Pin 13
MOSI – Pin 11
MISO – Pin 12
3V3 – 3.3V
GND – GND

The BMP180 is currently not hooked up to the Arduino.

Better to show a circuit diagram (not fritzing....pencil paper is fine) and even a nice clear photo of your layout including power supplies.

Yes, it will. Make a minimum sketch (probably just the SD) that will either solve your problem or reproduce your problem. When you fix the minimum sketch, you move the changes to the full sketch. When you break the minimum sketch, you throw it away and try again. When you break the full sketch, you start from zero.

Substitute a simple Textdatei.println("test"); data for the String. Maybe the String size is the problem.

You might try changing the filename to 8.3 format.

Did you say that your SD module works with SD.h library examples, such as CardInfo and ReadWrite?

Could you post a photo of your SD module?

1 Like

Yes the SD module works with the example code of the SD.h library. I used that at first to get a look at how to use the SD Module and then I implemented the code from the example files into my code.

Here are some pictures of the module.


Hi, thanks for your answer. Yeah you are right, simple code is a good idea when troubleshooting and moving in steps with adding stuff to working code. However I already tried the SD.h examples and then i tried implementing it into my code.

I get the feeling that it is a problem with my power supply of the arduino right now.

I simplified the code, by removing the DS3231 RTC and also the Code for sending the Arduino to sleep. Also translated everything into english so you guys can read and understand everything.

When trying the code now, he outputs the temp and humidity like he should but then when he gets to the line of Opening and Writing onto the SD-Card something weird happens. He jumps back into the Setup routine so i guess the SD-Module draws too much current and forces the arduino to reboot/restart.

//---------------------------DHT22---------------------------
#include <DHT.h>
#define DHTPIN 3
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

//--------------------------SD-Card--------------------------
#include <SPI.h>
#include <SD.h>

//------------------------Variablen--------------------------
unsigned long previousMillis;
unsigned long currentMillis;
const long interval_2 = 2000;
float temp_sum = 0;
float humidity_sum = 0;
int i = 0;
int done = 0;
float temperature = 0;
float humidity = 0;

//--------------------------Setup----------------------------
void setup() {
  Serial.begin(9600);
  while (!Serial);

  Serial.println("        Starting Initialisation");
  Serial.println("---------------------------------------------");

  //DHT22
  dht.begin();

  //SD-Karte
  Serial.println("- Initialising SD-Card");

  if (!SD.begin(5)) {                                                     // If SD-Card not found (!SD.begin) ...
    Serial.println("  - SD-Card Initialisation failed!");      // ... print Warning ....
    return;
  } else {
    Serial.println("  - SD-Card Initialisation completed");        // ... else print "SD-Card Initialisation completed"
  }

  Serial.println("---------------------------------------------");
  Serial.println("        Initialisation completed");
  Serial.println("             Starting Program");
  Serial.println("---------------------------------------------\n");

  delay(2000);
}

//--------------------------Main-----------------------------
void loop() {

  if (done != 1) {                                                    //Stay here until measurement done
    if (i < 5) {                                                      //Loop to do 4 Measurements
      currentMillis = millis();
      if (currentMillis - previousMillis >= interval_2) {             //2 second pause cause of DHT22
        temp_sum = temp_sum + dht.readTemperature();
        humidity_sum = humidity_sum + dht.readHumidity();
        previousMillis = currentMillis;
        Serial.println("Measuring");
        i += 1;
      }
    }
    if (i == 4) {                                                     //If 4 Measurements complete --> Calculate Temperature and Humidity output value
      temperature = temp_sum / 4;
      humidity = round(humidity_sum / 4);
      done = 1;
    }
  } else if (done == 1) {                                                                     //If measurements and calculations complete go here

    String output_temp = "Temperature DHT22: " + String(temperature) + "°C";
    Serial.println(output_temp);

    String output_humidity = "Humidity DHT22: " + String(humidity) + "%\n";
    Serial.println(output_humidity);

    delay(100);

    File textdatei = SD.open("test.txt", FILE_WRITE);            // Create file with name "test" and Format ".txt"

    String output_sd = String(temperature) + "," + String(humidity) + "\n";

    if (textdatei) {
      textdatei.println(output_sd);
      textdatei.close();
    } else {
      Serial.println("Coudlnt open/find test.txt\n");
    }

    i = 0;
    done = 0;
    temp_sum = 0;
    humidity_sum = 0;
    
  }
}

Here is also a picture what the output looks like.

Here is a picture of the Wiring. I think the Problem is the DS3231 RTC-Module, cause if i unplug it and plug it back in suddenly the simplified program works. I am not sure if i even need the 2 pull up resistors on the I2C lane.

Here also a picture of the RTC-Module. I removed the Power LED and the Diode for charging the CR2032 battery.

That sounds like a power problem (brown-out condition). See if you can read the SD without the reset.

Have you tried the 5v pin (rather than the 3V3)?

Would you include a hand-drawn wiring diagram, too?

You shouldn’t need that type SD card module when using a 3.3V processor, the module is intended to translate the 3.3V logic of the SD card to 5V logic.

So i need a different module?

I can upload a wiring diagram later.

Could you explain further what you mean by " See if you can read the SD without the reset."?

IF writing SD data causes a reset, does reading SD data cause a reset?

The module should be fine for use with a 3.3V processor. It can be powered at its 5V pin, but that just gets regulated down to 3.3V, which is what the card needs. But you can also power it directly at the 3.3V pin. In either case, the SPI lines are all 3.3V, which is perfect for a 3.3V Pro Mini.

Well where is the 3.3V coming from to power the SD? Are you powering the Pro Mini from USB, and then depending on the Pro Mini's 3.3V regulator to power itself and the SD card? Is it powered the same way when you run the SD.h examples? Did you run the ReadWrite example? Erasing and writing takes more current than reading.

Could you temporarily power the module from a separate 5V supply and see if that makes any difference?

It seems that it's initializing the card ok, and only craps out after that. I do wonder about the use of the String functions. They are pretty notorious for causing crashes.

I don't know of anything involving the DS3231 what would cause this.

Thanks for your answer. The Arduino is currently powered via USB but will later be powered from a Li-Ion Battery and Solarpanel, however i am regulating the voltage down to 3.3V when using that. But for now just USB.

The SD Card is right now powered from the Arduino, i could however connect the 3.3V Line from the USB Programmer directly to the SD-Module, might really be that the Module draws too much power and thus causes a reset on the Arduino.

The SD.h examples worked somehow. Just tried it again and the ReadWrite Code works without problems. Same wiring, didnt change anything.

I will try without the String functions and powering the module from a seperate 5V module or directly from the 3.3V Programmer instead of the Arduinos Voltage Regulator.

I dont think powering the SD Card Module from an external 5V works. I just took an Arduino Uno and used its 5V Output. No idea if thats the right way to do it however. Doesnt work tho. Not even the ReadWrite. When i plug the 5V into the SD Module i get that Windows Device disconnected sound, however i can still upload to the Arduino.