Logging altitude from GPS to microSD card

Hi,
I’m trying to log altitude from GPS NEO-6M GYNEO6MV2 to microSD card.
Problem isn’t reading altitude from GPS or writing data to microSD card. Both of it works, but only separated.
When I try to write altitude to micoSD card my GPS start to gives me an invalid altitude(1000000000.00).
After I remove code which writes data to card or remove card from SD module, GPS works fine.

Here is my code:

#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <SD.h>

#define TX 19
#define RX 18

TinyGPS gps;
File altitudeFile;
SoftwareSerial gpsSerial(RX, TX);

void setup() {
  Serial.begin(115200);
  gpsSerial.begin(9600);
  SD.begin(4);
}

void loop()
{
  while (gpsSerial.available())
  {
    int data = gpsSerial.read();
    if (gps.encode(data))
    {
      altitudeFile = SD.open("alt.txt", FILE_WRITE);
      float alt = gps.altitude();

      Serial.println(alt);
      
      altitudeFile.println(alt);
      altitudeFile.close();
      
    }
  }
}

Really don’t know what I’m doing wrong. :confused:
Thanks a lot for any help.

It is a bad idea to open and close the file every time you write to it.

Open the file once in setup(), and close it when you are done logging.

If you forget to close the file, you will lose only the last couple of measurements.

Like jremington said, open the file once in setup. To reduce the chance of lost data, flush the file periodically:

#include <NeoSWSerial.h>
#include <NMEAGPS.h>
#include <SD.h>

#define TX 19
#define RX 18

NMEAGPS gps;
File altitudeFile;
NeoSWSerial gpsSerial(RX, TX);

void setup() {
  Serial.begin(115200);
  gpsSerial.begin(9600);
  SD.begin(4);

  altitudeFile = SD.open("alt.txt", FILE_WRITE);
}

void loop()
{
  if (gps.available( gpsSerial ))
  {
    gps_fix fix = gps.read();

    if (fix.valid.altitude)
    {
      Serial      .println( fix.altitude() );
      altitudeFile.println( fix.altitude() );
      altitudeFile.flush();
    }
  }
}

You should consider using NeoSWSerial instead of SoftwareSerial. SoftwareSerial is very inefficient, because it disables interrupts for long periods of time. This can intefere with other parts of your sketch or with other libraries. There are several alternatives described here.

If you want to try that version of your sketch, NeoGPS and NeoSWSerial are available from the Arduino Library Manager, under the menu Sketch-> Include Library-> Manage Libraries. NeoGPS is smaller, faster, more reliable and more accurate than all other libraries. I think it’s easier to read the sketch, too.

Cheers,
/dev