Problems with creating audio file inside folder in SD Card

Hi Everyone,
I am new to programming and Arduino. Working on a school project right now, so have been trying things out one step at a time.
The interaction of the project is:

  1. scan an NFC tag
  2. touch a touchpad on MPR121 capacitive sensor (doesn't matter which touchpad it is. There are 12 in total)
  3. When I touch one pad for the first time, it starts recording
  4. When it is the second time, touch on the same pad, stop recording
  5. When the third time, start playing the recording.

So for each recording, I want the name of the file to be "NFC tag UID + number of the pad", i.e. 4D2e5C7h1, 4D2e5C7h6, 4D2e5C7h3, 4D2e5C7h12 and so forth. (the order of the touchpad doesn't matter.)

I have been struggling to get this right. I used the Serial.println to debug. The name is reflected correctly but it is not recording.
So here is my code: (The codes here are just to test the name + recording. I haven't integrated with the capacitive sensor part yet. )

#include <SPI.h>        // RC522 Module uses SPI protocol
#include <MFRC522.h>  // Library for Mifare RC522 Devices
#include <SD.h>    
#include <TMRpcm.h>

#define RST_PIN   9     // Configurable, see typical pin layout above
#define SS_PIN    8    // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

MFRC522::MIFARE_Key key;

#define sdPin 10      // Set SD Pin
TMRpcm audio;   

byte readCard[4];   // Stores scanned ID read from RFID Module
int pad[]={1,2,3,4,5,6,7,8,9,10,11,12};
char filename[] = "XXXXXXXXXX.wav";  // 4 bytes from UID + touchpad number
char extension[] = "wav";  

void setup() {
  Serial.begin(9600);  // Initialize serial communications with the PC
  while (!Serial) {
    delay(10);
  }
  
  SD.begin(sdPin);
  if (!SD.begin(sdPin)) {                       // Initialize SD Hardware
    Serial.println(F("SD initialization failed!"));
    return;// Could not initialize                                  // Do not go further
  }else{
  Serial.println(F("SD initialization done.")); }
  audio.CSPin = sdPin;
  
  SPI.begin();         // Init SPI bus
  mfrc522.PCD_Init();  // Init MFRC522 card
  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  Serial.println("Ready to read a card");
}

void loop() {
    if ( mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
    // Now a card is selected. The UID and SAK is in mfrc522.uid.
 
    Serial.print(F("Card UID:"));
    for (byte i = 0; i < 4; i++) {
      readCard[i] = mfrc522.uid.uidByte[i];
      Serial.print(readCard[i], HEX);
    }
      Serial.println("");
      mfrc522.PICC_HaltA();// Stop reading

    if(Serial.available()>0){                       
      switch(Serial.read()){
        case 'r': 
        sprintf(filename, "%02x%02x%02x%02x%u.%s", readCard[0], readCard[1], readCard[2], readCard[3], pad[0], extension);
        Serial.println(filename);//debug
        audio.startRecording(filename, 16000, A0); break;   
        case 's': 
        Serial.println("r done");//debug
        audio.stopRecording(filename); break;  
        case 'a': 
        sprintf(filename, "%02x%02x%02x%02x%u.%s", readCard[0], readCard[1], readCard[2], readCard[3], pad[1], extension);
        Serial.println(filename);//debug
        audio.startRecording(filename, 16000, A0); break;   
        case 'b':
        Serial.println("a done"); //debug
        audio.stopRecording(filename); break;            
      }
    }
  }
}

When I just try: case 'r': audio.startRecording("test.wav", 16000, A0); break; , the testing file is recorded.

(So eventually, I would want to scan the NFC tag, search if it exists in the SD card. If it is, then no matter which touchpad is touched, it starts to play the recording associated with that "nfc tag + touchpad".
If it is new, then it starts to record. But this would be for the future. Just want to let you know this is the whole interaction I am trying to build here. )

Could you help to let me know what went wrong and how to fix it? Thank you very much!

Just want to update you on what I have tried so far. Any thoughts would be helpful! Thank you very much!

  1. I am using MPR121 to trigger recording now instead of switch statement and am able to create the name of the audio file based on the touchpad. The recordings are fine.
  2. I am able to create the folder inside SD card based on the scanned NFC tag UID.

The problem now is once I combined the two together, the recording stopped working. So my goal is to scan a nfc tag, check if that folder name exists or not. If it doesn't exist, it goes into recording mode.
Then all the recording will write inside that folder. I have read many posts online about how to read and write to SD card, but I can't figure out how to add the audio file inside a created folder.

Here is my code now:

#include <Wire.h>
#include "Adafruit_MPR121.h"
#ifndef _BV
#define _BV(bit) (1 << (bit)) 
#endif
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <MFRC522.h> 

#define SD_ChipSelectPin 10 
TMRpcm audio;  

#define RST_PIN   9     // Configurable, see typical pin layout above
#define SS_PIN    8    // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

MFRC522::MIFARE_Key key;

uint16_t lasttouched = 0;
uint16_t currtouched = 0;
Adafruit_MPR121 cap = Adafruit_MPR121();
uint8_t touchThreshold = 40;
uint8_t releaseThreshold = 20;

unsigned long lastDebounceTime = 0; 
unsigned long debounceDelay = 50;   
int TouchCounter[12]; //12 can be changed to the corresponding members in the arrary 

uint8_t successRead;
byte readCard[4]; 
int pad[] ={1,2,3,4,5,6,7,8,9,10,11,12};

char foldername[8]; //NFC Tag UID 
char audioname[] = "XX.wav";  // touchpad number
char extension[] = "wav";  

File myrecording;

void setup() {
  Serial.begin(115200);

  while (!Serial) { // needed to keep leonardo/micro from starting too fast!
    delay(10);
  }

  Serial.println("Adafruit MPR121 Capacitive Touch sensor test"); 
  
  // Default address is 0x5A, if tied to 3.3V its 0x5B
  // If tied to SDA its 0x5C and if SCL then 0x5D
  if (!cap.begin(0x5A)) {
    Serial.println("MPR121 not found, check wiring?");
    while (1);
  }
  Serial.println("MPR121 found!");

 
  if (!SD.begin(SD_ChipSelectPin)) { 
    return;
  }else{
    Serial.println("SD OK");
  }
  audio.CSPin = SD_ChipSelectPin;

  SPI.begin();         // Init SPI bus
  mfrc522.PCD_Init();  // Init MFRC522 card
  for (byte a = 0; a < 6; a++) {
    key.keyByte[a] = 0xFF;
  }
  Serial.println("Ready to read a card");
  
//assign 0 as default value for each Touchcounter 
  for (uint8_t i=0; i<12; i++){
  TouchCounter[i]=0;
  }

}

void loop() {
  // start button
  do{
    successRead=getUID();
  }
  while (!successRead);
  
  sprintf(foldername, "%02x%02x%02x%02x", readCard[0], readCard[1], readCard[2], readCard[3]);
  if (SD.exists(foldername)) {
    Serial.println("exists.");
    playmode();
  }
  else {
    Serial.println("doesn't exist.");
    Serial.println("Creating new folder");
    Serial.println(foldername);
    SD.mkdir(foldername);
    delay (100);
   }
   recording(); //not working
}   
   
uint8_t getUID() {
    if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
    return 0;}
    if ( ! mfrc522.PICC_ReadCardSerial()) {   //Since a PICC placed get Serial and continue
    return 0;}
    // Now a card is selected. The UID and SAK is in mfrc522.uid.
 
    Serial.print(F("Card UID:"));
    for (byte j = 0; j < 3; j++) {
      readCard[j] = mfrc522.uid.uidByte[j];
      Serial.print(readCard[j], HEX);
    }
      Serial.println("");
      mfrc522.PICC_HaltA();// Stop reading
      return 1;
}

void recording() {
  currtouched = cap.touched();
  for (uint8_t i=0; i<12; i++) {
   
     if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    if ((currtouched & _BV(i)) && !(lasttouched & _BV(i))) {
      lastDebounceTime = millis();
    }
   
    if (!(currtouched & _BV(i)) && (lasttouched & _BV(i))) {
      TouchCounter[i]++;
      sprintf(audioname, "%u.%s", pad[i], extension);
      
      if (TouchCounter[i] == 1) {
        Serial.print(i); Serial.println(" Touched Once");
        myrecording = SD.open("foldername/audioname", FILE_WRITE); //waiting for test
        audio.startRecording(audioname, 16000, A0);
        }
      if (TouchCounter[i] ==2) {
        Serial.print(i); Serial.println(" Touched Twice");
        audio.stopRecording(audioname);
        }
       if ((TouchCounter[i] >2) && (TouchCounter[i]%2==1)) {
        Serial.print(i); Serial.println(" Playing"); 
        //audio.play(audioname);
        }
        if ((TouchCounter[i] >2) && (TouchCounter[i]%2==0)) {
        Serial.print(i); Serial.println(" Pause Playing"); 
        //audio.stopPlayback(audioname);
        }
       }
       delay(50);
      }
    }
   // reset our state
   //sortArray(audioname, 12); 
   lasttouched = currtouched;
   return;
  
  // debugging info, what
  Serial.print("\t\t\t\t\t\t\t\t\t\t\t\t\t 0x"); Serial.println(cap.touched(), HEX);
  Serial.print("Filt: ");
  for (uint8_t i=0; i<12; i++) {
    Serial.print(cap.filteredData(i)); Serial.print("\t");
  }
  Serial.println();
  Serial.print("Base: ");
  for (uint8_t i=0; i<12; i++) {
    Serial.print(cap.baselineData(i)); Serial.print("\t");
  }
  Serial.println();
  
  // put a delay so it isn't overwhelming
  delay(100);
}

The code now can create a folder and check if it exists or not. But when I touched the touchpad, it did not print out "Touched Once" and there is nothing recorded.

I am also writing the playmode. If the folder exists, it goes to the play recording mode. Given there are 12 recordings in one folder and the name is 1.wav, 2.wav, 3.wav and so forth. I don't know how to match the touchpad number 'i' to the recording name. I can write the code for 12 times but there must be an easier way.
Here is what I have for this part assuming my recordings are created successfully:

void playmode() { //can't test
  // open wave file from sdcard
  for (uint8_t i=0; i<12; i++) {
    if ((cap.touched() & (1 << 0)) ){
      //How to match i to the audioname? 
      
      ////below hasn't modified
       myrecording = SD.open("foldername/1.wav");
        if (!myrecording) {
        // if the file didn't open, print an error and stop
        Serial.println("error opening recording");
        while (true);}

       Serial.print("Playing");

       // until the file is not finished  
       //audio.play(myfile);
       while (true) ; }
       }
    }
 }