Record file not uploading to firebase esp32

I have tried Below 2 codes which record audio and save it as .raw file. and upload it to firebase.

but in this both 2 code, after recording completed, it show nothing in serial monitor. whether it uploading to firebase or not. i have tried so many times to modify these 2 codes and try. but none of methods are working.

1 code is using SPIFFS. 2nd code is using LittleFS. I want to use one of this code for my project. but none of it correctly uploading recorded file to firebase.

can someone help me to fix this.

gps and mic code which use SPIFFS

#include <driver/i2s.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <WiFiClientSecure.h>
#include <LittleFS.h>  // Include LittleFS instead of SPIFFS
#include <Preferences.h>  // Include Preferences library
#include <Arduino.h>
#include <TinyGPS++.h>

// Firebase configuration
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// I2S configuration for recording
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32
#define I2S_PORT I2S_NUM_0
#define I2S_SAMPLE_RATE (16000)
#define I2S_SAMPLE_BITS (16)
#define I2S_READ_LEN (16 * 1024)
#define RECORD_TIME (20)  // Seconds
#define I2S_CHANNEL_NUM (1)
#define FLASH_RECORD_SIZE (I2S_CHANNEL_NUM * I2S_SAMPLE_RATE * I2S_SAMPLE_BITS / 8 * RECORD_TIME)


// Wi-Fi and Firebase configurations
#define WIFI_SSID "{redacted}"
#define WIFI_PASSWORD "{redacted}"
#define API_KEY "{redacted}"
#define USER_EMAIL "{redacted}"
#define USER_PASSWORD "{redacted}"
#define STORAGE_BUCKET_ID "{redacted}"
#define DATABASE_URL "{redacted}"

// Define the push button pin
#define BUTTON_PIN 23

File file;
char filename[50];  // To store dynamically generated filename

// Create object for HardwareSerial and GPS
HardwareSerial GPS_Serial(2); // (Rx, Tx)
TinyGPSPlus gps;

// Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

Preferences preferences;  // Create Preferences object

// File counter
int fileCounter;  // Declare fileCounter
// Task flags
bool recordingComplete = false;
bool taskCompleted = false;

unsigned long sendDataPrevMillis = 0;
bool signupOK = false;
int buttonState = 0;

// Function prototypes
void LittleFSInit();
void i2sInit();
void i2s_adc(void* arg);
void uploadToFirebase();
bool fileExists(const char* path);
void generateNewFileName();
void clearLittleFS();

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

  GPS_Serial.begin(9600, SERIAL_8N1, 16, 17);  // Use pins 16 and 17 for RX and TX
  // Set up the push button pin
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  preferences.begin("counter", false);  // Open preferences with the namespace "counter" 
  // Retrieve the counter from preferences (default to 1 if not set)
  fileCounter = preferences.getInt("fileCounter", 1);
  Serial.printf("Starting with fileCounter: %d\n", fileCounter);

  // Initialize Wi-Fi connection
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.println("Connecting to Wi-Fi...");
  }
  Serial.println("Connected to Wi-Fi!");

  // Initialize LittleFS
  LittleFSInit();

  // Initialize Firebase
  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;

  // Sign up for Firebase
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("Firebase signup successful");
    signupOK = true;
  } else {
    Serial.printf("Firebase signup failed: %s\n", config.signer.signupError.message.c_str());
  }

  // Token status callback function
  config.token_status_callback = tokenStatusCallback;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  smartDelay(1000);  // Handle GPS communication

  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) {
    sendDataPrevMillis = millis();

    if (gps.location.isValid()) {
      double latitude = gps.location.lat();
      double longitude = gps.location.lng();
      double altitude = gps.altitude.meters();

      // Send latitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/latitude", latitude)) {
        
      } else {
        Serial.println("Failed to update latitude.");
        Serial.println(fbdo.errorReason());
      }

      // Send longitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/longitude", longitude)) {
        
      } else {
        Serial.println("Failed to update longitude.");
        Serial.println(fbdo.errorReason());
      }

      // Send altitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/altitude", altitude)) {
        
      } else {
        Serial.println("Failed to update altitude.");
        Serial.println(fbdo.errorReason());
      }
    } else {
      Serial.println("Invalid GPS data");
    }
  }

  // Handle push button state and update Firebase
  if (Firebase.ready() && signupOK) {
    buttonState = digitalRead(BUTTON_PIN);

    if (buttonState == LOW) {  // Button pressed
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 1)) {
        Serial.println("Button pressed! Alert sent to Firebase.");
        // Initialize I2S and start recording task
        i2sInit();
        xTaskCreate(i2s_adc, "i2s_adc", 1024 * 4, NULL, 1, NULL);
        if (Firebase.ready() && recordingComplete && !taskCompleted) {
          taskCompleted = true;

          if (fileExists(filename)) {
            uploadToFirebase();
          } else {
            Serial.println("File not found, cannot upload.");
          }
        }
      } else {
        Serial.println("Failed to write to Firebase");
        Serial.println(fbdo.errorReason());
      }
    } else {  // Button not pressed
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 0)) {
        // Serial.println("No alert. Button not pressed.");
      } else {
        Serial.println("Failed to write to Firebase");
        Serial.println(fbdo.errorReason());
      }
    }

    // Small delay to avoid flooding Firebase
    delay(500);
  }
}

static void smartDelay(unsigned long ms) {
  unsigned long start = millis();
  do {
    while (GPS_Serial.available()) {
      gps.encode(GPS_Serial.read());
    }
  } while (millis() - start < ms);
}

void LittleFSInit() {
  if (!LittleFS.begin()) {  // Initialize LittleFS
    Serial.println("LittleFS initialization failed!");
    while (1) yield();
  }

  // Generate a new filename for the current recording
  generateNewFileName();

  file = LittleFS.open(filename, FILE_WRITE);
  if (!file) {
    Serial.println("File creation failed!");
    while (1) yield();
  }
  Serial.println("LittleFS initialized and file opened.");
}

void generateNewFileName() {
  int fileNumber = 1;

  // Check if the counter file exists in LittleFS
  if (LittleFS.exists("/fileCounter.txt")) {
    File counterFile = LittleFS.open("/fileCounter.txt", FILE_READ);
    fileNumber = counterFile.parseInt();
    counterFile.close();
  }

  // Create a new filename using the file number
  sprintf(filename, "/guardianRecord%d.raw", fileNumber);

  // Increment and save the new file number back to LittleFS
  File counterFile = LittleFS.open("/fileCounter.txt", FILE_WRITE);
  counterFile.printf("%d", fileNumber + 1);
  counterFile.close();

  Serial.printf("New file name generated: %s\n", filename);
}

void i2sInit() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = I2S_SAMPLE_RATE,
    .bits_per_sample = i2s_bits_per_sample_t(I2S_SAMPLE_BITS),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = 0,
    .dma_buf_count = 16,
    .dma_buf_len = 1024,
    .use_apll = 1
  };
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);

  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };
  i2s_set_pin(I2S_PORT, &pin_config);
}

void i2s_adc(void* arg) {
  int i2s_read_len = I2S_READ_LEN;
  int flash_wr_size = 0;
  size_t bytes_read;
  char* i2s_read_buff = (char*)calloc(i2s_read_len, sizeof(char));

  while (flash_wr_size < FLASH_RECORD_SIZE) {
    i2s_read(I2S_PORT, (void*)i2s_read_buff, i2s_read_len, &bytes_read, portMAX_DELAY);
    file.write((const unsigned char*)i2s_read_buff, bytes_read);
    flash_wr_size += bytes_read;
    Serial.printf("Recording %d%%\n", flash_wr_size * 100 / FLASH_RECORD_SIZE);
  }
  file.close();
  free(i2s_read_buff);

  Serial.println("Recording complete");
  recordingComplete = true;

  i2s_driver_uninstall(I2S_PORT);
  vTaskDelete(NULL);
}

void uploadToFirebase() {
  String uploadPath = "/audio/guardianRecord" + String(fileCounter) + ".raw";
  Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, filename, mem_storage_type_flash, uploadPath.c_str(), "audio/raw");

  if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) {
    Serial.println("Upload successful!");

 // Increment file counter and save to preferences
    fileCounter++;
    preferences.putInt("fileCounter", fileCounter);

    // Clear LittleFS after successful upload
    clearLittleFS();
  } else {
    Serial.printf("Failed to upload file, reason: %s\n", fbdo.errorReason().c_str());
  }
}

bool fileExists(const char* path) {
  return LittleFS.exists(path);
}

void clearLittleFS() {
  LittleFS.remove(filename);
  Serial.println("LittleFS cleared.");
}

gps and mic code which use LittleFS

#include <driver/i2s.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <WiFiClientSecure.h>
#include <LittleFS.h>  // Include LittleFS instead of SPIFFS
#include <Preferences.h>  // Include Preferences library
#include <Arduino.h>
#include <TinyGPS++.h>

// Firebase configuration
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// I2S configuration for recording
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32
#define I2S_PORT I2S_NUM_0
#define I2S_SAMPLE_RATE (16000)
#define I2S_SAMPLE_BITS (16)
#define I2S_READ_LEN (16 * 1024)
#define RECORD_TIME (20)  // Seconds
#define I2S_CHANNEL_NUM (1)
#define FLASH_RECORD_SIZE (I2S_CHANNEL_NUM * I2S_SAMPLE_RATE * I2S_SAMPLE_BITS / 8 * RECORD_TIME)


// Wi-Fi and Firebase configurations
#define WIFI_SSID "{redacted}"
#define WIFI_PASSWORD "{redacted}"
#define API_KEY "{redacted}"
#define USER_EMAIL "{redacted}"
#define USER_PASSWORD "{redacted}"
#define STORAGE_BUCKET_ID "{redacted}"
#define DATABASE_URL "{redacted}"

// Define the push button pin
#define BUTTON_PIN 23

File file;
char filename[50];  // To store dynamically generated filename

// Create object for HardwareSerial and GPS
HardwareSerial GPS_Serial(2); // (Rx, Tx)
TinyGPSPlus gps;

// Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

Preferences preferences;  // Create Preferences object

// File counter
int fileCounter;  // Declare fileCounter
// Task flags
bool recordingComplete = false;
bool taskCompleted = false;

unsigned long sendDataPrevMillis = 0;
bool signupOK = false;
int buttonState = 0;

// Function prototypes
void LittleFSInit();
void i2sInit();
void i2s_adc(void* arg);
void uploadToFirebase();
bool fileExists(const char* path);
void generateNewFileName();
void clearLittleFS();

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

  GPS_Serial.begin(9600, SERIAL_8N1, 16, 17);  // Use pins 16 and 17 for RX and TX
  // Set up the push button pin
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  preferences.begin("counter", false);  // Open preferences with the namespace "counter" 
  // Retrieve the counter from preferences (default to 1 if not set)
  fileCounter = preferences.getInt("fileCounter", 1);
  Serial.printf("Starting with fileCounter: %d\n", fileCounter);

  // Initialize Wi-Fi connection
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.println("Connecting to Wi-Fi...");
  }
  Serial.println("Connected to Wi-Fi!");

  // Initialize LittleFS
  LittleFSInit();

  // Initialize Firebase
  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;

  // Sign up for Firebase
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("Firebase signup successful");
    signupOK = true;
  } else {
    Serial.printf("Firebase signup failed: %s\n", config.signer.signupError.message.c_str());
  }

  // Token status callback function
  config.token_status_callback = tokenStatusCallback;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  smartDelay(1000);  // Handle GPS communication

  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) {
    sendDataPrevMillis = millis();

    if (gps.location.isValid()) {
      double latitude = gps.location.lat();
      double longitude = gps.location.lng();
      double altitude = gps.altitude.meters();

      // Send latitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/latitude", latitude)) {
        Serial.println("Latitude updated successfully.");
      } else {
        Serial.println("Failed to update latitude.");
        Serial.println(fbdo.errorReason());
      }

      // Send longitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/longitude", longitude)) {
        Serial.println("Longitude updated successfully.");
      } else {
        Serial.println("Failed to update longitude.");
        Serial.println(fbdo.errorReason());
      }

      // Send altitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/altitude", altitude)) {
        Serial.println("Altitude updated successfully.");
      } else {
        Serial.println("Failed to update altitude.");
        Serial.println(fbdo.errorReason());
      }
    } else {
      Serial.println("Invalid GPS data");
    }
  }

  // Handle push button state and update Firebase
  if (Firebase.ready() && signupOK) {
    buttonState = digitalRead(BUTTON_PIN);

    if (buttonState == LOW) {  // Button pressed
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 1)) {
        Serial.println("Button pressed! Alert sent to Firebase.");
        // Initialize I2S and start recording task
        i2sInit();
        xTaskCreate(i2s_adc, "i2s_adc", 1024 * 4, NULL, 1, NULL);
        if (Firebase.ready() && recordingComplete && !taskCompleted) {
          taskCompleted = true;

          if (fileExists(filename)) {
            uploadToFirebase();
          } else {
            Serial.println("File not found, cannot upload.");
          }
        }
      } else {
        Serial.println("Failed to write to Firebase");
        Serial.println(fbdo.errorReason());
      }
    } else {  // Button not pressed
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 0)) {
        // Serial.println("No alert. Button not pressed.");
      } else {
        Serial.println("Failed to write to Firebase");
        Serial.println(fbdo.errorReason());
      }
    }

    // Small delay to avoid flooding Firebase
    delay(500);
  }
}

static void smartDelay(unsigned long ms) {
  unsigned long start = millis();
  do {
    while (GPS_Serial.available()) {
      gps.encode(GPS_Serial.read());
    }
  } while (millis() - start < ms);
}

void LittleFSInit() {
  if (!LittleFS.begin()) {  // Try to initialize LittleFS
    Serial.println("LittleFS initialization failed, formatting...");

    if (LittleFS.format()) {  // Try to format if initialization fails
      Serial.println("LittleFS formatted successfully.");
      
      if (LittleFS.begin()) {  // Re-attempt to mount after formatting
        Serial.println("LittleFS mounted successfully after formatting.");
      } else {
        Serial.println("LittleFS failed to mount even after formatting!");
        while (1) yield();  // Halt execution if LittleFS can't be mounted
      }
    } else {
      Serial.println("LittleFS formatting failed!");
      while (1) yield();  // Halt execution if formatting fails
    }
  } else {
    Serial.println("LittleFS mounted successfully.");
  }

  // Generate a new filename for the current recording
  generateNewFileName();

  file = LittleFS.open(filename, FILE_WRITE);
  if (!file) {
    Serial.println("File creation failed!");
    while (1) yield();  // Halt execution if the file can't be created
  }
  Serial.println("LittleFS initialized and file opened.");
}


void generateNewFileName() {
  int fileNumber = 1;

  // Check if the counter file exists in LittleFS
  if (LittleFS.exists("/fileCounter.txt")) {
    File counterFile = LittleFS.open("/fileCounter.txt", FILE_READ);
    fileNumber = counterFile.parseInt();
    counterFile.close();
  }

  // Create a new filename using the file number
  sprintf(filename, "/guardianRecord%d.raw", fileNumber);

  // Increment and save the new file number back to LittleFS
  File counterFile = LittleFS.open("/fileCounter.txt", FILE_WRITE);
  counterFile.printf("%d", fileNumber + 1);
  counterFile.close();

  Serial.printf("New file name generated: %s\n", filename);
}

void i2sInit() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = I2S_SAMPLE_RATE,
    .bits_per_sample = i2s_bits_per_sample_t(I2S_SAMPLE_BITS),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = 0,
    .dma_buf_count = 16,
    .dma_buf_len = 1024,
    .use_apll = 1
  };
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);

  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };
  i2s_set_pin(I2S_PORT, &pin_config);
}

void i2s_adc(void* arg) {
  int i2s_read_len = I2S_READ_LEN;
  int flash_wr_size = 0;
  size_t bytes_read;
  char* i2s_read_buff = (char*)calloc(i2s_read_len, sizeof(char));

  while (flash_wr_size < FLASH_RECORD_SIZE) {
    i2s_read(I2S_PORT, (void*)i2s_read_buff, i2s_read_len, &bytes_read, portMAX_DELAY);
    file.write((const unsigned char*)i2s_read_buff, bytes_read);
    flash_wr_size += bytes_read;
    Serial.printf("Recording %d%%\n", flash_wr_size * 100 / FLASH_RECORD_SIZE);
  }
  file.close();
  free(i2s_read_buff);

  Serial.println("Recording complete");
  recordingComplete = true;

  i2s_driver_uninstall(I2S_PORT);
  vTaskDelete(NULL);
}

void uploadToFirebase() {
  String uploadPath = "/audio/guardianRecord" + String(fileCounter) + ".raw";
  Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, filename, mem_storage_type_flash, uploadPath.c_str(), "audio/raw");

  if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) {
    Serial.println("Upload successful!");

// Increment file counter and save to preferences
    fileCounter++;
    preferences.putInt("fileCounter", fileCounter);

    // Clear LittleFS after successful upload
    clearLittleFS();
  } else {
    Serial.printf("Failed to upload file, reason: %s\n", fbdo.errorReason().c_str());
  }
}

bool fileExists(const char* path) {
  return LittleFS.exists(path);
}

void clearLittleFS() {
  LittleFS.remove(filename);
  Serial.println("LittleFS cleared.");
}

Please do not post passwords, API keys, IDs, email addresses or any other sensitive data. I suggest you review the post above to ensure everything sensitive has been scrubbed.

Bear in mind that the search engine spiders are extremely efficient. There is a high probability that the sensitive data you posted is available through a search.

1 Like

I forgot to remove those lines from my code. Thank you....

Although the focus has changed from spiffs v. littlefs to Firebase, your previous thread has some useful information so I post the link here: LittleFS mount failed Error - #32 by chamika2003

Your error message:

From here, you seem to have a basic problem posting anything to firebase. That was a simple float.

I think the best approach is to write a much simpler program which simply attempts to post a basic data set to Firebase, completely separate from your main code and focus on solving the problems with that. I don't know Firebase at all but I could imagine that, if you are using a free service, there could be restrictions on how much and how often you can send data.
There are a number of Firebase tutorials and there may be ways of getting better error messages from it.

No. it successfully updating Realtime database with GPS location. only issue is after auio recording success, it not upload anything.

#include <driver/i2s.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <WiFiClientSecure.h>
#include <LittleFS.h>
#include <Preferences.h>
#include <Arduino.h>
#include <TinyGPS++.h>

// Firebase configuration
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// I2S configuration for recording
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32
#define I2S_PORT I2S_NUM_0
#define I2S_SAMPLE_RATE (16000)
#define I2S_SAMPLE_BITS (16)
#define I2S_READ_LEN (4 * 1024)  // Reduced buffer size for stability
#define RECORD_TIME (10)         // Seconds
#define I2S_CHANNEL_NUM (1)
#define FLASH_RECORD_SIZE (I2S_CHANNEL_NUM * I2S_SAMPLE_RATE * I2S_SAMPLE_BITS / 8 * RECORD_TIME)

// Wi-Fi and Firebase configurations
#define WIFI_SSID "Chamika"
#define WIFI_PASSWORD "24682468"
#define API_KEY "AIzaSyAIQv6xLIrPtM9X2B6K6uoFJuP7JP8NhuU"
#define USER_EMAIL "guardianalert4u@gmail.com"
#define USER_PASSWORD "GUARDIANalert2024"
#define STORAGE_BUCKET_ID "guardianalert-ddde5.appspot.com"
#define DATABASE_URL "guardianalert-ddde5-default-rtdb.firebaseio.com"

// Define the push button pin
#define BUTTON_PIN 23

File file;
char filename[50];  // To store dynamically generated filename

// Create object for HardwareSerial and GPS
HardwareSerial GPS_Serial(2);
TinyGPSPlus gps;

// Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

Preferences preferences;  // Create Preferences object

// File counter
int fileCounter;
bool recordingComplete = false;
bool taskCompleted = false;
bool recordingInProgress = false;
unsigned long sendDataPrevMillis = 0;
bool signedInOK = false;
int buttonState = 0;

// Function prototypes
void LittleFSInit();
void i2sInit();
void i2s_adc(void* arg);
void uploadToFirebase();
bool fileExists(const char* path);
void generateNewFileName();
void clearLittleFS();

void setup() {
  Serial.begin(115200);
  Serial.printf("Available space: %u bytes\n", LittleFS.totalBytes() - LittleFS.usedBytes());

  GPS_Serial.begin(9600, SERIAL_8N1, 16, 17);  // Use pins 16 and 17 for RX and TX
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  preferences.begin("counter", false);  // Open preferences with the namespace "counter"
  fileCounter = preferences.getInt("fileCounter", 1);
  Serial.printf("Starting with fileCounter: %d\n", fileCounter);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.println("Connecting to Wi-Fi...");
  }
  Serial.println("Connected to Wi-Fi!");

  LittleFSInit();

  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;
  
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("Firebase signup successful");
    signupOK = true;
  } else {
    Serial.printf("Firebase signup failed: %s\n", config.signer.signupError.message.c_str());
  }

  config.token_status_callback = tokenStatusCallback;
  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  if (!recordingInProgress) {
    smartDelay(1000);

    if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) {
      sendDataPrevMillis = millis();

      if (gps.location.isValid()) {
        double latitude = gps.location.lat();
        double longitude = gps.location.lng();
        double altitude = gps.altitude.meters();

        Firebase.RTDB.setFloat(&fbdo, "/gps/latitude", latitude);
        Firebase.RTDB.setFloat(&fbdo, "/gps/longitude", longitude);
        Firebase.RTDB.setFloat(&fbdo, "/gps/altitude", altitude);
      } else {
        Serial.println("Invalid GPS data");
      }
    }
  }

  if (Firebase.ready() && signupOK) {
    buttonState = digitalRead(BUTTON_PIN);

    if (buttonState == LOW) {
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 1)) {
        Serial.println("Button pressed! Alert sent to Firebase.");
        recordingInProgress = true;

        i2sInit();
        xTaskCreate(i2s_adc, "i2s_adc", 1024 * 4, NULL, 1, NULL);
      }
    } else {
      Firebase.RTDB.setInt(&fbdo, "/alertStatus", 0);
    }

    delay(500);
  }
}

static void smartDelay(unsigned long ms) {
  unsigned long start = millis();
  do {
    while (GPS_Serial.available()) {
      gps.encode(GPS_Serial.read());
    }
  } while (millis() - start < ms);
}

void LittleFSInit() {
  if (!LittleFS.begin()) {
    Serial.println("LittleFS initialization failed, formatting...");
    if (LittleFS.format() && LittleFS.begin()) {
      Serial.println("LittleFS formatted and mounted successfully.");
    } else {
      Serial.println("LittleFS failed to format or mount.");
      while (1) yield();
    }
  } else {
    Serial.println("LittleFS mounted successfully.");
  }

  generateNewFileName();
}

void generateNewFileName() {
  int fileNumber = 1;

  if (LittleFS.exists("/fileCounter.txt")) {
    File counterFile = LittleFS.open("/fileCounter.txt", FILE_READ);
    fileNumber = counterFile.parseInt();
    counterFile.close();
  }

  sprintf(filename, "/guardianRecord%d.raw", fileNumber);

  File counterFile = LittleFS.open("/fileCounter.txt", FILE_WRITE);
  counterFile.printf("%d", fileNumber + 1);
  counterFile.close();

  Serial.printf("New file name generated: %s\n", filename);
}

void i2sInit() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = I2S_SAMPLE_RATE,
    .bits_per_sample = i2s_bits_per_sample_t(I2S_SAMPLE_BITS),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = 0,
    .dma_buf_count = 16,
    .dma_buf_len = 1024,
    .use_apll = 1
  };
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);

  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };
  i2s_set_pin(I2S_PORT, &pin_config);
}

void i2s_adc(void* arg) {
  int i2s_read_len = I2S_READ_LEN;
  int flash_wr_size = 0;
  size_t bytes_read;

  char* i2s_read_buff = (char*)malloc(i2s_read_len);
  if (!i2s_read_buff) {
    Serial.println("Memory allocation failed!");
    vTaskDelete(NULL);
  }

  // Open the file for writing
  file = LittleFS.open(filename, FILE_WRITE);
  if (!file) {
    Serial.println("Failed to open file for writing!");
    free(i2s_read_buff);
    vTaskDelete(NULL);
  }

  Serial.println(" *** Recording Start *** ");
  while (flash_wr_size < FLASH_RECORD_SIZE) {
    i2s_read(I2S_PORT, (void*)i2s_read_buff, i2s_read_len, &bytes_read, portMAX_DELAY);
    if (bytes_read > 0) {
      file.write((const uint8_t*)i2s_read_buff, bytes_read);
      flash_wr_size += bytes_read;
      Serial.printf("Sound recording %u%%\n", flash_wr_size * 100 / FLASH_RECORD_SIZE);
      Serial.printf("Free Heap: %u bytes\n", ESP.getFreeHeap());

      // Flush data to ensure it's written to LittleFS
      file.flush();
    }

    // Yield periodically to avoid watchdog reset
    vTaskDelay(1);
  }

  // Final flush and close file
  file.flush();
  file.close();
  free(i2s_read_buff);

  if (LittleFS.exists(filename)) {
    File savedFile = LittleFS.open(filename, FILE_READ);
    if (savedFile) {
      Serial.printf("Recording complete. File saved: %s, Size: %u bytes\n", filename, savedFile.size());
      savedFile.close();
    } else {
      Serial.println("Recording complete but failed to open the saved file!");
    }
  } else {
    Serial.println("Recording complete but file not found!");
  }

  Serial.println("Recording complete");
  recordingComplete = true;

  // After recording, upload to Firebase
  uploadToFirebase();

  // Resume GPS updates after upload
  recordingInProgress = false;

  i2s_driver_uninstall(I2S_PORT);
  vTaskDelete(NULL);
}

void uploadToFirebase() {

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wi-Fi not connected, attempting to reconnect...");
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(300);
      Serial.print(".");
    }
    Serial.println("Reconnected to Wi-Fi.");
  }

  if (!Firebase.ready()) {
    Serial.println("Firebase is not ready, reinitializing...");
    Firebase.begin(&config, &auth);
    Firebase.reconnectWiFi(true);
  }

  // Ensure we don't remount LittleFS here; it's already mounted in setup()
  String uploadPath = "/audio/guardianRecord" + String(fileCounter) + ".raw";


  if (LittleFS.exists(filename)) {
    Serial.printf("Uploading file: %s to Firebase path: %s\n", filename, uploadPath.c_str());
    Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, filename, mem_storage_type_flash, uploadPath.c_str(), "audio/raw");

    if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) {
      Serial.println("Upload successful!");
      fileCounter++;
      preferences.putInt("fileCounter", fileCounter);
      clearLittleFS();
    } else {
      Serial.printf("Failed to upload file, reason: %s\n", fbdo.errorReason().c_str());
    }
  } else {
    Serial.println("File does not exist for upload.");
  }
}

void clearLittleFS() {
  LittleFS.remove(filename);
}

this is the code Im checking. still i couldnt find the error. can you please help me to find out the error if u have time. whether i correctly save record file, i pause gps updating when recording start untill it successfully upload raw file to firebase. then it again start updating gps to firebase.

can i get your email to contact you. i have used one code for only check mic recording and uploading. it successfully recording the audio and uploading to fiebase. when i add tht code to my gps code only this error coming. if you can help me to merge these 2 codes, Im happy !!!

I'll certainly attempt to help but openly in this forum so maybe others also possibly benefit.
Post the output which the code generated which failed to send the audio file to firebase.
Post also the stripped down but working code which generated an audio file and successfully sent it to Firebase.

Again Im facing issue which take more time to complie. since 4 hours im trying to modify code and check. but it still like stuck in middle of compiling. when i run small code file like formatLittlefs and all, it uploading within a minute. but this full code still not compiled.

so i cannot share the serial monitor errors which show after recording complete. i have old serial monitor output. but yesterday night i modified code and i dont know which code is related to that serial monitor out put.

so can i share my seperate gps code and INMp441 mic codes which correctly working. can you help me to merge it.

working GPS ONLY code

this one successfully upload gps to firebase realtime database.

i added button pressed code to this bcz, when the button is presed, firebase alertStatus change 0 to 1. then alert i showing in my android app which created for this project.

#include <Arduino.h>
#include <TinyGPS++.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "****"
#define WIFI_PASSWORD "****"

// Define the push button pin
#define BUTTON_PIN 23
// Insert Firebase project API Key
#define API_KEY "******"

// Insert RTDB URL
#define DATABASE_URL "******"

// Create object for HardwareSerial and GPS
HardwareSerial GPS_Serial(2); // (Rx, Tx)
TinyGPSPlus gps;

// Firebase Data object
FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;
bool signupOK = false;
int buttonState = 0;

void setup() {
  Serial.begin(115200);
  GPS_Serial.begin(9600, SERIAL_8N1, 16, 17);  // Use pins 16 and 17 for RX and TX

  // Set up the push button pin
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  // Initialize WiFi
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  // Firebase configuration
  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;

  // Sign up for Firebase
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("Firebase signup successful");
    signupOK = true;
  } else {
    Serial.printf("Firebase signup failed: %s\n", config.signer.signupError.message.c_str());
  }

  // Token status callback function
  config.token_status_callback = tokenStatusCallback;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  smartDelay(1000); // Handle GPS communication

  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) {
    sendDataPrevMillis = millis();

    if (gps.location.isValid()) {
      double latitude = gps.location.lat();
      double longitude = gps.location.lng();
      double altitude = gps.altitude.meters();

      // Send latitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/latitude", latitude)) {
        Serial.println("Latitude updated successfully.");
      } else {
        Serial.println("Failed to update latitude.");
        Serial.println(fbdo.errorReason());
      }

      // Send longitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/longitude", longitude)) {
        Serial.println("Longitude updated successfully.");
      } else {
        Serial.println("Failed to update longitude.");
        Serial.println(fbdo.errorReason());
      }

      // Send altitude to Firebase
      if (Firebase.RTDB.setFloat(&fbdo, "/gps/altitude", altitude)) {
        Serial.println("Altitude updated successfully.");
      } else {
        Serial.println("Failed to update altitude.");
        Serial.println(fbdo.errorReason());
      }
    } else {
      Serial.println("Invalid GPS data");
    }
  }

  // Handle push button state and update Firebase
  if (Firebase.ready() && signupOK) {
    buttonState = digitalRead(BUTTON_PIN);

    if (buttonState == LOW) { // Button pressed
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 1)) {
        Serial.println("Button pressed! Alert sent to Firebase.");
      } else {
        Serial.println("Failed to write to Firebase");
        Serial.println(fbdo.errorReason());
      }
    } else { // Button not pressed
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 0)) {
        // Serial.println("No alert. Button not pressed.");
      } else {
        Serial.println("Failed to write to Firebase");
        Serial.println(fbdo.errorReason());
      }
    }

    // Small delay to avoid flooding Firebase
    delay(500);
  }

}

static void smartDelay(unsigned long ms) {
  unsigned long start = millis();
  do {
    while (GPS_Serial.available()) {
      gps.encode(GPS_Serial.read());
    }
  } while (millis() - start < ms);
}

WORKING INMP MIC RECORDING AND UPLOADING

this code is correctly recording and uploading raw files to firebase.

i want to add this code inside button pressed code. when button pressed, recording should start and upload to firebase storage.

#include <driver/i2s.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <WiFiClientSecure.h>
#include <LittleFS.h>  // Include LittleFS instead of SPIFFS
#include <Preferences.h>  // Include Preferences library
// Firebase configuration
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// I2S configuration for recording
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32
#define I2S_PORT I2S_NUM_0
#define I2S_SAMPLE_RATE (16000)
#define I2S_SAMPLE_BITS (16)
#define I2S_READ_LEN (16 * 1024)
#define RECORD_TIME (20)  // Seconds
#define I2S_CHANNEL_NUM (1)
#define FLASH_RECORD_SIZE (I2S_CHANNEL_NUM * I2S_SAMPLE_RATE * I2S_SAMPLE_BITS / 8 * RECORD_TIME)

File file;
char filename[50];  // To store dynamically generated filename

// Wi-Fi and Firebase configurations
#define WIFI_SSID "Chamika"
#define WIFI_PASSWORD "24682468"
#define API_KEY "*****"
#define USER_EMAIL "*****"
#define USER_PASSWORD "*******"
#define STORAGE_BUCKET_ID "*****"

// Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

Preferences preferences;  // Create Preferences object

// File counter
int fileCounter;  // Declare fileCounter
// Task flags
bool recordingComplete = false;
bool taskCompleted = false;

// Function prototypes
void LittleFSInit();
void i2sInit();
void i2s_adc(void* arg);
void uploadToFirebase();
bool fileExists(const char* path);
void generateNewFileName();
void clearLittleFS();

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

  preferences.begin("counter", false);  // Open preferences with the namespace "counter" 
  // Retrieve the counter from preferences (default to 1 if not set)
  fileCounter = preferences.getInt("fileCounter", 1);
  Serial.printf("Starting with fileCounter: %d\n", fileCounter);
  
  // Initialize Wi-Fi connection
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.println("Connecting to Wi-Fi...");
  }
  Serial.println("Connected to Wi-Fi!");

  // Initialize LittleFS
  LittleFSInit();

  // Initialize Firebase
  config.api_key = API_KEY;
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);

  if (!Firebase.ready()) {
    Serial.println("Firebase initialization failed.");
    return;
  }

  // Initialize I2S and start recording task
  i2sInit();
  xTaskCreate(i2s_adc, "i2s_adc", 1024 * 4, NULL, 1, NULL);
}

void loop() {
  // Ensure Firebase is ready and task is not completed
  if (Firebase.ready() && recordingComplete && !taskCompleted) {
    taskCompleted = true;

    if (fileExists(filename)) {
      uploadToFirebase();
    } else {
      Serial.println("File not found, cannot upload.");
    }
  }
}

void LittleFSInit() {
  if (!LittleFS.begin()) {  // Initialize LittleFS
    Serial.println("LittleFS initialization failed!");
    while (1) yield();
  }

  // Generate a new filename for the current recording
  generateNewFileName();

  file = LittleFS.open(filename, FILE_WRITE);
  if (!file) {
    Serial.println("File creation failed!");
    while (1) yield();
  }
  Serial.println("LittleFS initialized and file opened.");
}

void generateNewFileName() {
  int fileNumber = 1;

  // Check if the counter file exists in LittleFS
  if (LittleFS.exists("/fileCounter.txt")) {
    File counterFile = LittleFS.open("/fileCounter.txt", FILE_READ);
    fileNumber = counterFile.parseInt();
    counterFile.close();
  }

  // Create a new filename using the file number
  sprintf(filename, "/guardianRecord%d.raw", fileNumber);

  // Increment and save the new file number back to LittleFS
  File counterFile = LittleFS.open("/fileCounter.txt", FILE_WRITE);
  counterFile.printf("%d", fileNumber + 1);
  counterFile.close();

  Serial.printf("New file name generated: %s\n", filename);
}

void i2sInit() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = I2S_SAMPLE_RATE,
    .bits_per_sample = i2s_bits_per_sample_t(I2S_SAMPLE_BITS),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = 0,
    .dma_buf_count = 16,
    .dma_buf_len = 1024,
    .use_apll = 1
  };
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);

  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };
  i2s_set_pin(I2S_PORT, &pin_config);
}

void i2s_adc(void* arg) {
  int i2s_read_len = I2S_READ_LEN;
  int flash_wr_size = 0;
  size_t bytes_read;

  char* i2s_read_buff = (char*)malloc(i2s_read_len);
  if (!i2s_read_buff) {
    Serial.println("Memory allocation failed!");
    vTaskDelete(NULL);
  }

  Serial.println(" *** Recording Start *** ");
  while (flash_wr_size < FLASH_RECORD_SIZE) {
    i2s_read(I2S_PORT, (void*)i2s_read_buff, i2s_read_len, &bytes_read, portMAX_DELAY);
    if (bytes_read > 0) {
      file.write((const uint8_t*)i2s_read_buff, bytes_read);
      flash_wr_size += bytes_read;
      Serial.printf("Sound recording %u%%\n", flash_wr_size * 100 / FLASH_RECORD_SIZE);
      Serial.printf("Free Heap: %u bytes\n", ESP.getFreeHeap());
    }

    // Yield periodically to avoid watchdog reset
    vTaskDelay(1);
  }

  file.close();
  free(i2s_read_buff);

  if (LittleFS.exists(filename)) {
    Serial.printf("Recording complete. File saved: %s, Size: %u bytes\n", filename, LittleFS.open(filename).size());
  } else {
    Serial.println("Recording complete but file not found!");
  }

  Serial.println(" *** Recording End *** ");
  recordingComplete = true;  // Mark recording as complete
  vTaskDelete(NULL);
}

void uploadToFirebase() {
  String uploadPath = "/audio/guardianRecord" + String(fileCounter) + ".raw";
  Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, filename, mem_storage_type_flash, uploadPath.c_str(), "audio/raw");

  if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) {
    Serial.println("Upload successful!");

 // Increment file counter and save to preferences
    fileCounter++;
    preferences.putInt("fileCounter", fileCounter);

    // Clear LittleFS after successful upload
    clearLittleFS();
  } else {
    Serial.printf("Failed to upload file, reason: %s\n", fbdo.errorReason().c_str());
  }
}

void clearLittleFS() {
  Serial.println("Formatting LittleFS to free space...");
  LittleFS.format();
  Serial.println("LittleFS formatted.");
}

bool fileExists(const char* path) {
  File file = LittleFS.open(path);
  bool exists = file && file.size() > 100;
  file.close();
  return exists;
}

You have a number of problems then. A first compilation can take a number of minutes but subsequent compilations should not take so long. If it is 4 hours, there is definitely something wrong. The first thing I would try is rolling back the ESP32 Arduino core to version 3.0.4. Automatically clearing the Flash memory (setting in tools menu) before an upload causes a delay but that could be quite short.
You are still leaving credentials in your code.

Anyway, I am trying to get an overview of what you are doing.
You appear to be continually, while the ESP32 is powered up, recording audio files and sending these to Firebase together with a set of GPS coordinates. You have also a push button which registers an alert in Firebase. Is that correct? What is the role of the Android in this ?
How I see it at the moment is that by far the most complex activity is the recording of the audio files and their despatch to Firebase. Getting GPS coordinates and a button press is relatively simple. So I would be thinking of adding the GPS/button press functionality to the working Audio code.

1 Like

sorry.. i totaly forgot to remove that.

i think due my antivirus, it took long time. i alway forget to off the antivirus.

and my project is this.

this device send live location to our android app.

and when user press the button if he face some trouble(women/childern), it send the alert to our android app, then it start recording 20 sec audio from mic and send it to our app.

gps is continously updating location to firebase. its working fine.

when the utton is pressed, i want to implement mic recording and uploading process.
(since this is just prototype, we use 20 sec audio crecording and we dont use sd card to keep audio.)

I tried this code. now it show recorded file size also. that mean file is created in little fs. but it show error when uploading to filebase.

Sound recording 99%
Free Heap: 182604 bytes
Sound recording 101%
Free Heap: 187224 bytes
Recording complete. File saved: /guardianRecord2.raw, Size: 323584 bytes
Recording complete
File size to upload: 323584 bytes
Uploading file: /guardianRecord2.raw to Firebase path: /audio/guardianRecord1.raw
Failed to upload file, HTTP code: -1000
Error reason: 

here the code i used

#include <driver/i2s.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <WiFiClientSecure.h>
#include <LittleFS.h>
#include <Preferences.h>
#include <Arduino.h>
#include <TinyGPS++.h>

// Firebase configuration
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// I2S configuration for recording
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32
#define I2S_PORT I2S_NUM_0
#define I2S_SAMPLE_RATE (16000)
#define I2S_SAMPLE_BITS (16)
#define I2S_READ_LEN (4 * 1024)  // Reduced buffer size for stability
#define RECORD_TIME (10)         // Seconds
#define I2S_CHANNEL_NUM (1)
#define FLASH_RECORD_SIZE (I2S_CHANNEL_NUM * I2S_SAMPLE_RATE * I2S_SAMPLE_BITS / 8 * RECORD_TIME)

// Wi-Fi and Firebase configurations
#define WIFI_SSID "Chamika"
#define WIFI_PASSWORD "24682468"
#define API_KEY "******"
#define USER_EMAIL "*******"
#define USER_PASSWORD "******"
#define STORAGE_BUCKET_ID "****"
#define DATABASE_URL "********"

// Define the push button pin
#define BUTTON_PIN 23

File file;
char filename[50];  // To store dynamically generated filename

// Create object for HardwareSerial and GPS
HardwareSerial GPS_Serial(2);
TinyGPSPlus gps;

// Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

Preferences preferences;  // Create Preferences object

// File counter
int fileCounter;
bool recordingComplete = false;
bool taskCompleted = false;
bool recordingInProgress = false;
unsigned long sendDataPrevMillis = 0;
bool signupOK = false;
int buttonState = 0;

// Function prototypes
void LittleFSInit();
void i2sInit();
void i2s_adc(void* arg);
void uploadToFirebase();
bool fileExists(const char* path);
void generateNewFileName();
void clearLittleFS();

void setup() {
  Serial.begin(115200);
  Serial.printf("Available space: %u bytes\n", LittleFS.totalBytes() - LittleFS.usedBytes());

  GPS_Serial.begin(9600, SERIAL_8N1, 16, 17);  // Use pins 16 and 17 for RX and TX
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  preferences.begin("counter", false);  // Open preferences with the namespace "counter"
  fileCounter = preferences.getInt("fileCounter", 1);
  Serial.printf("Starting with fileCounter: %d\n", fileCounter);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.println("Connecting to Wi-Fi...");
  }
  Serial.println("Connected to Wi-Fi!");

  LittleFSInit();

  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;
  
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("Firebase signup successful");
    signupOK = true;
  } else {
    Serial.printf("Firebase signup failed: %s\n", config.signer.signupError.message.c_str());
  }

  config.token_status_callback = tokenStatusCallback;
  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  if (!recordingInProgress) {
    smartDelay(1000);

    if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) {
      sendDataPrevMillis = millis();

      if (gps.location.isValid()) {
        double latitude = gps.location.lat();
        double longitude = gps.location.lng();
        double altitude = gps.altitude.meters();

        Firebase.RTDB.setFloat(&fbdo, "/gps/latitude", latitude);
        Firebase.RTDB.setFloat(&fbdo, "/gps/longitude", longitude);
        Firebase.RTDB.setFloat(&fbdo, "/gps/altitude", altitude);
      } else {
        Serial.println("Invalid GPS data");
      }
    }
  }

  if (Firebase.ready() && signupOK) {
    buttonState = digitalRead(BUTTON_PIN);

    if (buttonState == LOW) {
      if (Firebase.RTDB.setInt(&fbdo, "/alertStatus", 1)) {
        Serial.println("Button pressed! Alert sent to Firebase.");
        recordingInProgress = true;

        i2sInit();
        xTaskCreate(i2s_adc, "i2s_adc", 1024 * 4, NULL, 1, NULL);
      }
    } else {
      Firebase.RTDB.setInt(&fbdo, "/alertStatus", 0);
    }

    delay(500);
  }
}

static void smartDelay(unsigned long ms) {
  unsigned long start = millis();
  do {
    while (GPS_Serial.available()) {
      gps.encode(GPS_Serial.read());
    }
  } while (millis() - start < ms);
}

void LittleFSInit() {
  if (!LittleFS.begin()) {
    Serial.println("LittleFS initialization failed, formatting...");
    if (LittleFS.format() && LittleFS.begin()) {
      Serial.println("LittleFS formatted and mounted successfully.");
    } else {
      Serial.println("LittleFS failed to format or mount.");
      while (1) yield();
    }
  } else {
    Serial.println("LittleFS mounted successfully.");
  }

  generateNewFileName();
}

void generateNewFileName() {
  int fileNumber = 1;

  if (LittleFS.exists("/fileCounter.txt")) {
    File counterFile = LittleFS.open("/fileCounter.txt", FILE_READ);
    fileNumber = counterFile.parseInt();
    counterFile.close();
  }

  sprintf(filename, "/guardianRecord%d.raw", fileNumber);

  File counterFile = LittleFS.open("/fileCounter.txt", FILE_WRITE);
  counterFile.printf("%d", fileNumber + 1);
  counterFile.close();

  Serial.printf("New file name generated: %s\n", filename);
}

void i2sInit() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = I2S_SAMPLE_RATE,
    .bits_per_sample = i2s_bits_per_sample_t(I2S_SAMPLE_BITS),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = 0,
    .dma_buf_count = 16,
    .dma_buf_len = 1024,
    .use_apll = 1
  };
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);

  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };
  i2s_set_pin(I2S_PORT, &pin_config);
}

void i2s_adc(void* arg) {
  int i2s_read_len = I2S_READ_LEN;
  int flash_wr_size = 0;
  size_t bytes_read;

  char* i2s_read_buff = (char*)malloc(i2s_read_len);
  if (!i2s_read_buff) {
    Serial.println("Memory allocation failed!");
    vTaskDelete(NULL);
  }

  // Open the file for writing
  file = LittleFS.open(filename, FILE_WRITE);
  if (!file) {
    Serial.println("Failed to open file for writing!");
    free(i2s_read_buff);
    vTaskDelete(NULL);
  }

  Serial.println(" *** Recording Start *** ");
  while (flash_wr_size < FLASH_RECORD_SIZE) {
    i2s_read(I2S_PORT, (void*)i2s_read_buff, i2s_read_len, &bytes_read, portMAX_DELAY);
    if (bytes_read > 0) {
      file.write((const uint8_t*)i2s_read_buff, bytes_read);
      flash_wr_size += bytes_read;
      Serial.printf("Sound recording %u%%\n", flash_wr_size * 100 / FLASH_RECORD_SIZE);
      Serial.printf("Free Heap: %u bytes\n", ESP.getFreeHeap());

      // Flush data to ensure it's written to LittleFS
      file.flush();
    }

    // Yield periodically to avoid watchdog reset
    vTaskDelay(1);
  }

  // Final flush and close file
  file.flush();
  file.close();
  free(i2s_read_buff);

  if (LittleFS.exists(filename)) {
    File savedFile = LittleFS.open(filename, FILE_READ);
    if (savedFile) {
      Serial.printf("Recording complete. File saved: %s, Size: %u bytes\n", filename, savedFile.size());
      savedFile.close();
    } else {
      Serial.println("Recording complete but failed to open the saved file!");
    }
  } else {
    Serial.println("Recording complete but file not found!");
  }

  Serial.println("Recording complete");
  recordingComplete = true;

  // After recording, upload to Firebase
  uploadToFirebase();

  // Resume GPS updates after upload
  recordingInProgress = false;

  i2s_driver_uninstall(I2S_PORT);
  vTaskDelete(NULL);
}

void uploadToFirebase() {
  // Ensure LittleFS is mounted and file exists
  if (!LittleFS.exists(filename)) {
    Serial.println("File does not exist, cannot upload.");
    return;
  }

  // Debug info for file size
  File tempFile = LittleFS.open(filename, FILE_READ);
  if (tempFile) {
    Serial.printf("File size to upload: %u bytes\n", tempFile.size());
    tempFile.close();
  } else {
    Serial.println("Failed to open the file before upload.");
    return;
  }

  // Specify the upload path
  String uploadPath = "/audio/guardianRecord" + String(fileCounter) + ".raw";
  Serial.printf("Uploading file: %s to Firebase path: %s\n", filename, uploadPath.c_str());

  // Attempt the upload
  if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, filename, mem_storage_type_flash, uploadPath.c_str(), "audio/raw")) {
    Serial.println("Upload successful!");
    fileCounter++;
    preferences.putInt("fileCounter", fileCounter);
    clearLittleFS();
  } else {
    // Print more detailed error information
    Serial.printf("Failed to upload file, HTTP code: %d\n", fbdo.httpCode());
    Serial.printf("Error reason: %s\n", fbdo.errorReason().c_str());
  }
}


void clearLittleFS() {
  LittleFS.remove(filename);
}

The code looks quite similar to that in post #9 under the title "WORKING INMP MIC RECORDING AND UPLOADING" which you said was working. What is the major difference ?

above code #12 post i include gps location update also. i cant understand what is the issue it alway show that failed to upload

Strange. If it were a problem with stack space for the task i2s_adc or generally a storage problem, then you would have got a runtime stack trace.

But there is clearly a conflict somewhere.

All I can suggest is that you try to localise the error by commenting out the Firebase commands here to see if this newly added code is the source of the problem.

 if (!recordingInProgress) {
    smartDelay(1000);

    if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) {
      sendDataPrevMillis = millis();

      if (gps.location.isValid()) {
        double latitude = gps.location.lat();
        double longitude = gps.location.lng();
        double altitude = gps.altitude.meters();

        Firebase.RTDB.setFloat(&fbdo, "/gps/latitude", latitude);
        Firebase.RTDB.setFloat(&fbdo, "/gps/longitude", longitude);
        Firebase.RTDB.setFloat(&fbdo, "/gps/altitude", altitude);
      } else {
        Serial.println("Invalid GPS data");
      }
    }
  }

no . before add that code also issue was same. still I tried to fix but same. Im using 2mb app/ 2mb spiffs. so there is no any error my spiffs is not enough.

how i can fix this issue. it show HTTP 1000 error. in google also there is no any information about this error.

there is no connection issue also. bcz gps is continously updating location to firebase.

and when ever i press button it start new recording. but result is same. if there is no enough memory, it should show right. instead of this http 1000 error.

next week i have exhibition. what i can do for this..

please help me.

You need to simplify your code than slowly add new code. You need to post in code tags the entire verbose error log. Constantly changing the code you show us does not help.
Start over with your intended sketch (post it), explain what it should do, what it actually does, and also post the error log in code tags.
You said you could not find any info re HTTP 1000 error. I found lot's of information, here is the top reason

I got the error. are there any way to modify my full code to use new library. bcz i spent full week with this old library.

You must not use that old library, it will be nothing but trouble. KISS, and divide and conquer.

Of course there is, shouldn't be much different.