File name gets written but contains no data.

I’m cross-posting this from Programming Questions part of the forum as I did not get an answer there. Here’s hoping this part of the forum is the correct one.

Hello all,

Having made a GPS datalogger that works, I now set myself on the trail of making an new filename after each button press.

Normally, when the logger is switched on, it logs the data once a certain set of GPS parameters is met and after 10 lines, it will halt logging and blink a LED to indicate to the user it’s logged 10 lines and that the operator needs to push a button in order for the logger to start logging again.

Currently, this works without issues. Every time the button is pressed, inside loop a run once IF loop is run and the headers of each log is written to the same file (GPSDATA.CSV). After each button press, it appends to this same file.

What I want is that with each button press, a new file, incremented, is made on the SDcard, the headers written and then the rest of the code is executed, writing 10 lines and closing the file.

Before setup, I added the following declaration: char filename[13];

I’ve added this to the loop:

// create a new file
      char filename[] = "GPSLOG00.CSV";
      for (uint8_t i = 0; i < 100; i++) {
          filename[6] = i/10 + '0';
          filename[7] = i%10 + '0';

The files do get written, but they don’t possess any data other than the headers. It’ll quickly go up to 100 files but data isn’t logged although the green LED blinks.

Should I put the file-name generating into its own function? Or am I missing something with (global) variables not getting changed?

Here’s my code:

#include <SPI.h>//include library code to communicate with SPI devices
#include <SD.h>//include library code for SD card
#include <NMEAGPS.h> //the GPS library
#include <GPSport.h> //The used port configuration set for NMEAGPS

//**********************************************************************
NMEAGPS     gps;
const int chipSelect = 10; //SDcard is set to pin 10.
// Check configuration
#ifndef GPS_FIX_HDOP
#error You must uncomment GPS_FIX_HDOP in GPSfix_cfg.h!
#endif
//**********************************************************************
//Button configuration

const int buttonPin = 2;     // the number of the pushbutton pin

//LED configuration
const int blueled = 6;
const int redled = 7;
const int greenled = 5;
int ledState = LOW;
//int redState = LOW;
//int greenState = LOW;

unsigned long previousMillis = 0;  //stores the last time the LED was updated
const long interval = 200; //Interval at which to blink LED
int buttonState = 0; 
int counter = 0;
boolean printheaders = false; //needed for a one time run in loop
char filename[13];
void setup()
{
  pinMode(buttonPin, INPUT); //The button is used to start another logging cycle
  pinMode(blueled, OUTPUT); //Blue part of the RGB Led
  pinMode(redled, OUTPUT); //Red part of the RGB Led
  pinMode(greenled, OUTPUT); //Green part of the RGB Led
  digitalWrite(greenled, HIGH); //As I'm currently using common Anode RGB Led, this is set to High. When using common Cathode, use LOW instead.
  digitalWrite(redled, HIGH); //As I'm currently using common Anode RGB Led, this is set to High. When using common Cathode, use LOW instead.
  digitalWrite(blueled, HIGH); //As I'm currently using common Anode RGB Led, this is set to High. When using common Cathode, use LOW instead.
  DEBUG_PORT.begin(9600);
  gpsPort.begin(9600);
  Serial.print("Initializing SD card...");//setup for the SD card
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present!");
    digitalWrite(blueled, LOW);
    digitalWrite(redled, LOW);
    delay(5000);
    return;
  }
  Serial.println("Card initialized.");
  Serial.println("File opened. Start logging GPS data to SD card:");
  
  //DEBUG_PORT.println
  //(
  //  F( "Sats HDOP Latitude  Longitude  Date       Time    Speed  Heading  \n"
  //     "          (deg)     (deg)                                         \n" )
  //);

  //repeat( '-', 133 );
 
}
void loop()
{
        digitalWrite(blueled, HIGH);
    
      if ((counter == 0) && (printheaders == false))  { //making sure this runs only once
      printheaders = true;
      
      // create a new file
      char filename[] = "GPSLOG00.CSV";
      for (uint8_t i = 0; i < 100; i++) {
          filename[6] = i/10 + '0';
          filename[7] = i%10 + '0';
      
  
            if (! SD.exists(filename)) {
            File dataFile = SD.open(filename, FILE_WRITE);
                if (dataFile) {     // if the file is available, write to it:
                dataFile.println("Date, Time , Lat , Long , Sats , HDOP , Heading, Speed");//prints the headers for our data
                              }
            dataFile.close();//file closed  
            break;
                }
            }
      }
    if (gps.available( gpsPort ) && (counter <= 9)) {
    gps_fix fix = gps.read();
                                   
    if (fix.valid.hdop && (fix.hdop < 2000)){  
        bool  validDT         = fix.valid.date & fix.valid.time;
                
    /*            print(             fix.satellites       , fix.valid.satellites, 3             );
                print(             fix.hdop / 1000.0      , fix.valid.hdop      , 6, 2          );
                print(             fix.latitude ()      , fix.valid.location  , 10, 6         );
                print(             fix.longitude()      , fix.valid.location  , 11, 6         );
                DEBUG_PORT.println(); */
    
                   
    File dataFile = SD.open(filename, FILE_WRITE);
    Serial.println(filename);
    digitalWrite(redled, HIGH);
    digitalWrite(greenled, LOW); //data is being written to the card
    if (dataFile) {     // if the file is available, write to it:
      
        
      if (fix.dateTime.date < 10)
        dataFile.print( '0' );
      dataFile.print(fix.dateTime.date);
      dataFile.print( '/' );
      if (fix.dateTime.month < 10)
        dataFile.print( '0' );
      dataFile.print(fix.dateTime.month);
      dataFile.print( '/' );
      dataFile.print(fix.dateTime.year);
      dataFile.print(',');

      if (fix.dateTime.hours < 10)
        dataFile.print( '0' );
      dataFile.print(fix.dateTime.hours);
      dataFile.print( ':' );
      if (fix.dateTime.minutes < 10)
        dataFile.print( '0' );
      dataFile.print(fix.dateTime.minutes);
      dataFile.print( ':' );
      if (fix.dateTime.seconds < 10)
        dataFile.print( '0' );
      dataFile.print(fix.dateTime.seconds);
      dataFile.print(',');
      dataFile.print(fix.latitude (), 10);
      dataFile.print(",");
      dataFile.print(fix.longitude(), 11);
      dataFile.print(",");
      dataFile.print(fix.satellites, 3);
      dataFile.print(",");
      dataFile.print(fix.hdop / 1000.0, 6);
      dataFile.print(",");
      dataFile.print(fix.heading (), 7);
      dataFile.print(",");
      dataFile.print(fix.speed_kph(), 7);
      dataFile.print("\n");
      dataFile.close();
    //Serial.println(counter, DEC);
    counter++;
    }
   }
   else {
      noFix();
    }
    }
    else {
  digitalWrite(greenled, HIGH);    //Lines written, no more write actions.
  if (counter >= 10){ //once 10 lines are written, called poslog, positive log to stop writing lines and wait for operator input
    poslog();
  }
    }
}  


void noFix() //blink the red LED to show there is no fix
{
  unsigned long currentMillis = millis();
  //digitalWrite(greenled, HIGH);
    if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == HIGH) {
      ledState = LOW;
    } else {
      ledState = HIGH;
    }
  }
    // set the LED with the ledState of the variable:
    digitalWrite(redled, ledState);
}

void poslog()
  {
   unsigned long currentMillis = millis();
   digitalWrite(blueled, HIGH);
        while (digitalRead(buttonPin) == LOW) { //Wait for the operator to press butan
          counter = 0;
          printheaders = false;
          break;
        }
        if (currentMillis - previousMillis >= interval) { //else, just blink the led
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == HIGH) {
        ledState = LOW;
    } 
    else {
      ledState = HIGH;
    }
  }
    // set the LED with the ledState of the variable:
    digitalWrite(blueled, ledState);
    }

You have declared a global filename variable that never gets set to anything. You also have a local variable in loop with the same name which takes care of creating the files.

However, you're using the blank global version to try and open a file to write data.

Thank you for pointing out the issues with the variables.

If I understand correctly (probably not haha), I’m declaring an array just before Setup, here:

char filename[13];

My intention is to create a global variable (?)/ array that must be filled.

The filling takes place here:

char filename[] = "GPSLOG00.CSV";

My thought is that this creates this filename and the code below amend the filename to include a number that gets incremented depending on what’s on the SDcard already.

So far, this works, I see 99 files getting created on the SDcard.

So the error in my ways must be here:

File dataFile = SD.open(filename, FILE_WRITE);

Apparently, I’m not opening the file created but rather write to a non-existent file named “”, is that correct?
How would I point to the correct variable filename?

Cut (not copy) this out:

    char filename[] = "GPSLOG00.CSV";

and use it to replace this:

char filename[13];

Then I expect you'll be able to write data to a file called GPSLOG99.CSV.

OK, I'll try later tonight and will let you know. Thank you.

wildbill:
Cut (not copy) this out:

    char filename[] = "GPSLOG00.CSV";

and use it to replace this:

char filename[13];

Then I expect you'll be able to write data to a file called GPSLOG99.CSV.

This was indeed the case. It now makes a new filename and logs to that filename.

Thank you, I bow to your wisdom and will study the answer.