SD card creating file but not writing on it

I have a SD card working with a LoRa device and a LCD, and the sd card generates a file but it cannot open it to write in it. Here goes the code:

#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <LoRa.h>
#include <SD.h>

File myFile;

//#include <SdFat.h>
//
//SdFat sd;
//SD myFile;


// LCD
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 16 column and 2 rows

// LoRa
#define txPower 20
#define spreadingFactor 11
#define signalBandwidth 500E3
#define codingRateDenominator 4
#define preambleLength 6



const byte longitud = 15;     //nombre de bytes que llegeix Node

char data[10][longitud];
bool flag_comm_Serial = false, flag_comm_LoRa = false;
int send_tries = 5;  //intents d'enviament missatge activacio flash
uint32_t t0 = 0;
uint16_t print_period = 900;



void setup()
{
//pinMode(4, OUTPUT);
//pinMode(4, OUTPUT);

  
  //spiSelect(10);
  lcd.init(); // initialize the lcd
  lcd.backlight();

  Serial.begin(9600);
  while (!Serial);
  Serial.println("LoRa Receiver");
  LoRa.setPins(10, 9); //Pins Ares placa  //nss,nreset
  
  lcd.print("LoRa Receiverr");
//  delay(2000);
  lcd.clear();
  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    lcd.print("LoRa Failed");
  //  delay(2000);
    lcd.clear();
    while (1);
  }
   LoRa.setTxPower(txPower);
  LoRa.setSpreadingFactor(spreadingFactor);
  LoRa.setSignalBandwidth(signalBandwidth);
  LoRa.setCodingRate4(codingRateDenominator);
  LoRa.setPreambleLength(preambleLength);
  LoRa.enableCrc();



  // SD
pinMode(4, OUTPUT);
//spiSelect(4);

  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

    if(!SD.exists("test.txt"))
  {
      myFile = SD.open("test.txt", FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");
        myFile.close();
      } else {

        Serial.println("Error creando el archivo datalog.csv");
      }
  }
 

  
}

void loop()
{
  char a;
  byte c;
  //delay(2000);
  //lcd.print("Inside Loop");
  //Serial.print("Inside Loop");

  //delay(2000);
  //lcd.clear();

// try to parse packet
    //spiSelect(10);
    int packetSize = LoRa.parsePacket();
  
    if (packetSize) {
        //delay(2000);
        //lcd.print("Dintre Parse");
        //delay(2000);
        //lcd.clear();
      // received a paket
  
      Serial.print("Received packet '");
  
      // read packet
        while (LoRa.available()) {
        for(byte i = 0; i < 10; i++){
          a = LoRa.read(); 
          c = 0;
          while (a != ',' and c < longitud - 2){
              data[i][c] = a;
              a = LoRa.read();     
              c++;   
          }
          data[i][c] = ' ';
          c++;
          while(c < longitud){
            data[i][c] = '\0';
            c++;
          }
        }
      }
      lcd.clear(); // clear display
      lcd.setCursor(0, 0);   
      lcd.print(data[0]); // stage
      Serial.println(data[0]);
      lcd.setCursor(0, 1);        
      lcd.print(data[1]); // altitude
      Serial.println(data[1]);
      lcd.setCursor(0, 2);        
      lcd.print(data[1]); // altitude
      Serial.println(data[1]);
      lcd.setCursor(0, 3);        
      lcd.print(data[1]); // altitude
      Serial.println(data[1]);
  
      //SD
  
      //spiSelect(4);
          myFile = SD.open("test.txt", FILE_WRITE); // open the file for reading
        if (myFile) { 
          Serial.print("Escribiendo SD: ");
          int a = int(data[0]);
          int b  = int(data[1]);
          int c = int(data[1])+1;
          myFile.print("Tiempo(ms)=");
          myFile.print(millis());
          myFile.print(", sensor1=");
          myFile.print(a);
          myFile.print(", sensor2=");
          myFile.print(b);
          myFile.print(", sensor3=");
          myFile.println(c);
          
          myFile.close(); //cerramos el archivo
          
          Serial.print("Tiempo(ms)=");
          Serial.print(millis());
          Serial.print(", sensor1=");
          Serial.print(a);
          Serial.print(", sensor2=");
          Serial.print(b);
          Serial.print(", sensor3=");
          Serial.println(c);       
          
       
    } else {
      Serial.println("Error al abrir el archivo");
    }
    
  //   spiSelect(10);
  
  delay(900);
  lcd.clear();
 // delay(2000);
      
  
  }

  //digitalWrite(4,HIGH);
  //spiSelect(4); 
  // delay(2000);
}
void spiSelect(int CS) 
  {
    digitalWrite(10,HIGH);
    digitalWrite(4,HIGH);

    digitalWrite(CS,LOW);  
  }

If I try the following code for the sd alone it works:

type or paste code#include <SD.h>

File myFile;
void setup()
{
  Serial.begin(9600);
  Serial.print("Iniciando SD ...");
  if (!SD.begin(4)) {
    Serial.println("No se pudo inicializar");
    return;
  }
  Serial.println("inicializacion exitosa");
  
  if(!SD.exists("datalog.csv"))
  {
      myFile = SD.open("datalog.csv", FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");
        myFile.close();
      } else {

        Serial.println("Error creando el archivo datalog.csv");
      }
  }
  
}

void loop()
{
  myFile = SD.open("datalog.csv", FILE_WRITE);//abrimos  el archivo
  
  if (myFile) { 
        Serial.print("Escribiendo SD: ");
        int sensor1 = analogRead(0);
        int sensor2 = analogRead(1);
        int sensor3 = analogRead(2);
        myFile.print(millis());
        myFile.print(",");
        myFile.print(sensor1);
        myFile.print(",");
        myFile.print(sensor2);
        myFile.print(",");
        myFile.println(sensor3);
        
        myFile.close(); //cerramos el archivo
        
        Serial.print("Tiempo(ms)=");
        Serial.print(millis());
        Serial.print(",sensor1=");
        Serial.print(sensor1);
        Serial.print(",sensor2=");
        Serial.print(sensor2);
        Serial.print(",sensor3=");
        Serial.println(sensor3);       
                    
  
  } else {
    // if the file didn't open, print an error:
    Serial.println("Error al abrir el archivo");
  }
  delay(100);
}here

And this is my error:
image
However, the file is created but remains empty

image

One issue that I see in your code is that you are trying to use pin 4 for both the CS pin of your LoRa module and the CS pin of your SD card. This might be causing conflicts and preventing the SD card from functioning properly.

I would recommend trying to use a different pin for one of the CS pins and see if that helps to resolve the issue. Additionally, you might want to try printing out any error messages that you are getting to the serial monitor to help diagnose the problem.

I'm not sure, but maybe this will help!

SD card has no reset line. After you download, the CPU is reset but NOT the SD card. Cycle power to reset both and see if problem clears.
Also, SD cards take a LOT of current (over 100mA) so power issues can appear if running from battery.
Final notes: 32gb is max card size, and all filenames must be DOS 8.3 format names.

Hello, thanks for the answer! Could you specify where am I using pin 4 for the LoRa? I cannot see it, so maybe I have it wrong!

Hi, thanks for the answer! I don't know how to reset the SD card, could you provide a small example? As for the battery and filename format, thanks for the advice, I will absolutely take this into account.

The only way to reset the SD card reader is to turn it off and back on again. If you turn the whole project off and on again, it should come up clean.

Doing this I get the same problem but no other file is generated. Any other idea?

I solved it. It was an issue of memory, I had over 80% of the dynamic memory in use. I solved it by introducing the following F() to all Serial.prints

Serial.println(F("Test done. Results:"));

According to: https://support.arduino.cc/hc/en-us/articles/360013825179-Reduce-the-size-and-memory-usage-of-your-sketch
Thank you all for the help.
Here goes the final code:

#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <LoRa.h>
#include <SD.h>

File myFile;

//#include <SdFat.h>
//
//SdFat sd;
//SD myFile;


// LCD
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 16 column and 2 rows

// LoRa
#define txPower 20
#define spreadingFactor 11
#define signalBandwidth 500E3
#define codingRateDenominator 4
#define preambleLength 6



const byte longitud = 15;     //nombre de bytes que llegeix Node

char data[10][longitud];
bool flag_comm_Serial = false, flag_comm_LoRa = false;
int send_tries = 5;  //intents d'enviament missatge activacio flash
uint32_t t0 = 0;
uint16_t print_period = 900;



void setup()
{
//pinMode(4, OUTPUT);
//pinMode(4, OUTPUT);

  
  //spiSelect(10);
  lcd.init(); // initialize the lcd
  lcd.backlight();

  Serial.begin(9600);
  while (!Serial);
  Serial.println("LoRa Receiver");
  LoRa.setPins(10, 9); //Pins Ares placa  //nss,nreset
  
  lcd.print("LoRa Receiverr");
//  delay(2000);
  lcd.clear();
  if (!LoRa.begin(433E6)) {
    Serial.println(F("Starting LoRa failed!"));
    lcd.print("LoRa Failed");
  //  delay(2000);
    lcd.clear();
    while (1);
  }
   LoRa.setTxPower(txPower);
  LoRa.setSpreadingFactor(spreadingFactor);
  LoRa.setSignalBandwidth(signalBandwidth);
  LoRa.setCodingRate4(codingRateDenominator);
  LoRa.setPreambleLength(preambleLength);
  LoRa.enableCrc();



  // SD
pinMode(4, OUTPUT);
//spiSelect(4);

  Serial.println(F("Initializing SD card..."));
  if (!SD.begin(4)) {
    Serial.println(F("initialization failed!"));
    while (1);
  }
  Serial.println(F("initialization done."));

    if(!SD.exists("test.txt"))
  {
      myFile = SD.open("test.txt", FILE_WRITE);
      if (myFile) {
        Serial.println(F("Archivo nuevo, Escribiendo encabezado(fila 1)"));
        myFile.println(F("Tiempo(ms),Sensor1,Sensor2,Sensor3"));
        myFile.close();
      } else {

        Serial.println(F("Error creando el archivo test.txt"));
      }
  }
  else
  {
    Serial.println(F("Ya existe test.txt"));
    Serial.println(F("Archivo nuevo, Escribiendo encabezado(fila 1)"));
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");
        myFile.close();
  }
 

  
}

void loop()
{
  char a;
  byte c;
  //delay(2000);
  //lcd.print("Inside Loop");
  //Serial.print("Inside Loop");

  //delay(2000);
  //lcd.clear();

// try to parse packet
    //spiSelect(10);
    int packetSize = LoRa.parsePacket();
  
    if (packetSize) {
        //delay(2000);
        //lcd.print("Dintre Parse");
        //delay(2000);
        //lcd.clear();
      // received a paket
  
      Serial.print(F("Received packet '"));
  
      // read packet
        while (LoRa.available()) {
        for(byte i = 0; i < 10; i++){
          a = LoRa.read(); 
          c = 0;
          while (a != ',' and c < longitud - 2){
              data[i][c] = a;
              a = LoRa.read();     
              c++;   
          }
          data[i][c] = ' ';
          c++;
          while(c < longitud){
            data[i][c] = '\0';
            c++;
          }
        }
      }
      lcd.clear(); // clear display
      lcd.setCursor(0, 0);   
      lcd.print(data[0]); // stage
      Serial.println(data[0]);
      lcd.setCursor(0, 1);        
      lcd.print(data[1]); // altitude
      Serial.println(data[1]);
      lcd.setCursor(0, 2);        
      lcd.print(data[2]); // altitude
      Serial.println(data[2]);
      lcd.setCursor(0, 3);        
      lcd.print(data[3]); // altitude
      Serial.println(data[3]);
  
      //SD
  
      //spiSelect(4);
          myFile = SD.open("test.txt", FILE_WRITE); // open the file for reading
        if (myFile) { 
          Serial.print("Escribiendo SD: ");
          int a = int(data[0]);
          int b  = int(data[1]);
          int c = int(data[1])+1;
          myFile.print("Tiempo(ms)=");
          myFile.print(millis());
          myFile.print(", sensor1=");
          myFile.print(data[0]);
          myFile.print(", sensor2=");
          myFile.print(data[1]);
          myFile.print(", sensor3=");
          myFile.println(data[2]);
          myFile.print(", sensor4=");
          myFile.println(data[3]);
          
          myFile.close(); //cerramos el archivo
          
          Serial.print(F("Tiempo(ms)="));
          Serial.print(millis());
          Serial.print(F(", sensor1="));
          Serial.print(data[0]);
          Serial.print(F(", sensor2="));
          Serial.print(data[1]);
          Serial.print(F(", sensor3="));
          Serial.println(data[2]);    
          Serial.print(F(", sensor4="));
          Serial.println(data[3]);   
          
       
    } else {
      Serial.println(F("Error al abrir el archivo"));
    }
    
  //   spiSelect(10);
  
  delay(900);
  lcd.clear();
 // delay(2000);
      
  
  }

  //digitalWrite(4,HIGH);
  //spiSelect(4); 
  // delay(2000);
}
void spiSelect(int CS) 
  {
    digitalWrite(10,HIGH);
    digitalWrite(4,HIGH);

    digitalWrite(CS,LOW);  
  }

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