Not enough memory

Hello,
I have been programming my Arduino Micro but I am running out of program storage space as well as dynamic memory. I am pretty new to programming so I don’t know how to fix this. Can anyone help me understand how to fix this?

Thanks in advance for your help!

Sketch uses 27928 bytes (97%) of program storage space. Maximum is 28672 bytes.
Global variables use 2068 bytes (80%) of dynamic memory, leaving 492 bytes for local variables. Maximum is 2560 bytes.
Low memory available, stability problems may occur.

Test.ino (14.1 KB)

You have to factor this code. You're already using the F() macro for text so no wiggle room there. Here we have 2 nearly identical code blocks, you can make this into one function and pass the data that differs as parameters:

  //writing xa data to SD card
  if (SDCard == 1 ) {
    xaSD = SD.open("xa.txt", FILE_WRITE);
    if (xaSD) {  
      xaSD.print(timeAfterStart);
      xaSD.print(F(","));    
      xaSD.println(X_out);
      xaSD.close(); // close the file    
    }
  // if the file didn't open, print an error:
  else {
    Serial.println(F("error opening xa.txt"));
  }
  }

  //writing ya data to SD card
  if (SDCard == 1 ) {
    yaSD = SD.open("ya.txt", FILE_WRITE);
    if (yaSD) {  
      yaSD.print(timeAfterStart);
      yaSD.print(F(","));    
      yaSD.println(Y_out);
      yaSD.close(); // close the file    
    }
  // if the file didn't open, print an error:
  else {
    Serial.println(F("error opening ya.txt"));
  }
  }

Just an example, you will have to vet the entire sketch for opportunities like this. I'm sure there are more.

You have an entire list of File variables, but you can only open 1 file at a time. That is wasteful. Have one File variable and re-use it. Something like this will get you 94% program space and 53% dynamic memory
Attached due to length

Test.ino (8.86 KB)