GIGA R1 USB crashes upon opening file to write

Hey folks, I'm using the usb a port on my GIGA R1 to log some data. Initially during the first 10 mins there is no issue in writing the data to the usb then all of a sudden it abruptly crashes indicated by red light of doom. The crash occurs right when the code is at FILE = fopen("...").

#include <Wire.h>
#include <WiFi.h>
#include <math.h>
#include <Arduino_USBHostMbed5.h>
#include <DigitalOut.h>
#include "Variables.h"
#include "PinAssign.h"
#include "MyConstants.h"
#include "thingProperties.h"
#include "VRTC.h"

USBHostMSD msd;
mbed::FATFileSystem usb("usb");

int transfercounter = 0;
bool transferinterval = true;

void setup() {
  Serial.begin(9600);
  Wire.begin(); //SDA,SCl serial buses   (All other I2C components) 
  Wire1.begin();//SDA1,SCl1 serial buses (EEPROM) 
  delay(1000);

  //Establish WiFi connection
    WIFIConnectionHandler();
    ArduinoCLoudConnection();
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

  //GPIO pins for sensors
    // Float pins
    pinMode(top1, INPUT_PULLUP);
    pinMode(bottom1, INPUT_PULLUP);
    pinMode(top2, INPUT_PULLUP);
    pinMode(bottom2, INPUT_PULLUP);
    pinMode(dtop, INPUT_PULLUP);
    pinMode(dbot, INPUT_PULLUP);
    Serial.println("Float pins initiated");

    // Flow Sensor pins
    pinMode(FLOW_SENSOR_1, INPUT_PULLUP);
    pinMode(FLOW_SENSOR_2, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(FLOW_SENSOR_1), flow1ISR, RISING);
    Serial.println("Flow sensor pin 5 initialized");
    attachInterrupt(digitalPinToInterrupt(FLOW_SENSOR_2), flow2ISR, RISING);
    Serial.println("Flow sensor pin 14 initialized");

  //GPIO pins for relays
    // Valve relays
    pinMode(t1d, OUTPUT);
    digitalWrite(t1d, LOW);
    pinMode(t2d, OUTPUT);
    digitalWrite(t2d, LOW);
    pinMode(dt1, OUTPUT);
    digitalWrite(dt1, LOW);
    pinMode(dt2, OUTPUT);
    digitalWrite(dt2, LOW);
    Serial.println("Valve relays defined");

    // Pump Relays
    pinMode(dsp, OUTPUT);
    digitalWrite(dsp, LOW);
    pinMode(drp, OUTPUT);
    digitalWrite(drp, LOW);
    pinMode(dpc1, OUTPUT);
    digitalWrite(dpc1, LOW);
    pinMode(dpc2, OUTPUT);
    digitalWrite(dpc2, LOW);
    Serial.println("Pump relays defined");
  
    // Fan Relays
    pinMode(df, OUTPUT);
    pinMode(fcu, OUTPUT);
    Serial.println("Fan relays defined");
    digitalWrite(df, LOW);
    digitalWrite(fcu, LOW);

    delay(2000);

  // Read previous state from EEPROM
    lowTrig1 = readTriggerState(0);
    lowTrig2 = readTriggerState(1);
    overflow = readTriggerState(2);
    Serial.println("LowTrig1 from EEPROM: " + String(lowTrig1) + "\nLowTrig2 from EEPROM: " + String(lowTrig2) + "\nOverflow from EEPROM: " + String(overflow));

  //Sensors/Modules setup
    // SHT connection
    Precision = PRECISION_HIGH;
    Heater = NO_HEATER;

    // Initialize first sensor
    select_channel(SENSOR1_CHANNEL);
    Serial.println("Initializing first ES13511 sensor");
    ES135xx_probe();

    // Initialize second sensor
    select_channel(SENSOR2_CHANNEL);
    Serial.println("Initializing second ES13511 sensor");
    ES135xx_probe();

    // Temp sensor
    sensors.begin();

    //Begin RTC
    setNtpTime();

    //USB 
    USBconnection();
}

void loop(){
  currentTime = millis();

 // Check if connected to WiFi
  if(WiFi.status() != WL_CONNECTED){
    Serial.println("\nOffline loop");
    Serial.print("System Clock: ");
    Serial.println(getLocaltime());
    //offline loop
    loop2();
    if (currentTime - currentMillis >= 120000 ) {
      digitalWrite(PA_15, LOW);
      delay(1000);
      Serial.println("Attempting reconnection...");
      WIFIConnectionHandler();
      ArduinoCLoudConnection();
      USBconnection();
      delay(1000);
    }
  }
   else {
    //online loop
    loop1();
  }
 }

Loop 2 :

//OFFLINE Loop
void loop2(){

//Reset control variables 
  fanswitch           = false;
  SaltTransfer2_1     = false;
  SaltTransfer1_2     = false;
  T1Def               = false;
  T2Def               = false;
  testswitch          = false;
  reset               = false;
  FanisON             = true;
  dehumidifier_status = true;
  dehumidifier_Status = false;
  dPC_Status          = false;
  printonce           = false;
  power               = false;
  previousTime        = currentTime;

  USBstorage();
  FloatSensorReading();
  SensorReadings();
  Dehumidification();
  Cooling();
  onResetChange();

  delay(100);
}

Functions:

    void USBconnection(){
      pinMode(PA_15, OUTPUT); //enable the USB-A port
      digitalWrite(PA_15, HIGH);
      while (!msd.connect()) {
        Serial.println("Connecting to USB device...");
        delay(1000);
      }
      Serial.println("USB device connected.");

      if (usb.mount(&msd) == 0) {
        Serial.println("USB drive mounted.");
      } else {
        Serial.println("Failed to mount USB drive.");
      }  
    } 

void USBstorage(){ 
  String timestamp = getLocaltime();
 // Create a file on the USB drive
  FILE *file = fopen("/usb/Sensor_Data.txt", "a"); // Append mode
  if (file) {
    if(USBon){
      fprintf(file, "                   | Storage RH%% | Storage T°C | Utility RH%% | Utility T°C | Tank1 T°C | Tank2 T°C | Float status 1 | Float status 2 | Float status overflow |\n");
      USBon = false;
    }
    fprintf(file, "%s| ", timestamp.c_str());
    fprintf(file, "    %.2f    |", storage_hum);
    fprintf(file, "    %.2f     |", storage_temp);
    fprintf(file, "    %.2f     |", utility_hum);
    fprintf(file, "    %.2f     |", utility_temp);
    fprintf(file, "   %.2f    |", Temp_tank1);
    fprintf(file, "   %.2f    |", Temp_tank2);
    fprintf(file, "     %d      |", lowTrig1);
    fprintf(file, "     %d      |", lowTrig2);
    fprintf(file, "        %d          |\n", overflow);
    Serial.println("Data written to USB drive.");
    fclose(file);
  } else {
    Serial.println("Error opening file.");
  }

}

i have also noticed that if the loop takes considerable time between cycles then the board crashes immediately in the second cycle just after uploading the sketch. i tried to dismount it before i try to connect to the wifi network and reconnect it back after the wifi connection block to mitigate this issue but the issue persists.

// Check if connected to WiFi
  if(WiFi.status() != WL_CONNECTED){
    Serial.println("\nOffline loop");
    Serial.print("System Clock: ");
    Serial.println(getLocaltime());
    //offline loop
    loop2();
    if (currentTime - currentMillis >= 120000 ) {
      digitalWrite(PA_15, LOW);
      delay(1000);
      Serial.println("Attempting reconnection...");
      WIFIConnectionHandler();
      ArduinoCLoudConnection();
      USBconnection();
      delay(1000);
    }
  }

Output for the above block:

03:36.046 -> Offline loop
12:03:36.046 -> System Clock: 2024-06-28 12:04:42
12:03:36.046 -> Data written to USB drive.
12:03:36.090 -> Reading from EEPROM---->  Float status 1: 1, Float status 2: 1, Float status 3:1
12:03:36.090 -> Tank 1: ACTIVE | Tank 2: ACTIVE | Supply pump: INACTIVE
12:03:36.090 -> Check wiring
12:03:36.090 -> Storage Temp = 0.00 C  Storage RH = 0.00% | Check wiring
12:03:36.090 -> Utility Temp = 0.00 C  Utility RH = 0.00%
12:03:36.808 -> Temperature 1: -127.00 C | Temperature 2: -127.00 C
12:03:36.808 -> Flow Rate supply: 0.00 L/min | Flow Rate return: 0.00 L/min
12:03:36.808 -> 
12:03:37.810 -> Check wiring
12:03:37.810 -> Dew point cooler OFF
12:03:38.911 -> Attempting reconnection...
12:03:38.911 -> Attempting to connect to primary WiFi network...
12:03:39.607 -> ...........
12:03:40.604 -> Failed to connect to the primary network. Trying the first alternative network...
12:04:16.468 -> ..........
12:04:17.335 -> Failed to connect to the first alternative network. Trying the second one...
12:04:18.039 -> ...........
12:04:19.057 -> Failed to connect to both alternative networks.
12:04:19.057 -> Connecting to USB device...
12:04:20.033 -> Connecting to USB device...
12:04:21.147 -> USB device connected.
12:04:21.147 -> Failed to mount USB drive.
12:04:22.150 -> 
12:04:22.150 -> Offline loop
12:04:22.150 -> System Clock: 2024-06-28 12:05:28

the board crashed here. Dont know why it fails to mount usb. The board crashes at the same place even if i remove the wifi checking block just that it runs for a few mins then crashes. Any help would be appreciated

Hi @temperate. My advice is to create a demonstration program that contains only the absolute minimum of code required to produce the fault. Doing this will make the situation easier to understand by removing all irrelevant complexity from the system.

I find that often by the time I have completed this work the cause of the fault has become clear to me. Even if it doesn't, you can then share this minimal, reproducible, verifiable example (MCVE) here on the forum. It will be of value to the helpers here.

Thank you for your insight. I have tried this minimal code

#include <Arduino.h>
#include <Arduino_USBHostMbed5.h>
#include <DigitalOut.h>

USBHostMSD msd;
mbed::FATFileSystem usb("usb");

void setup() {
  Serial.begin(9600);
  while (!msd.connect()) {
    Serial.println("Connecting to USB device...");
    delay(1000);
  }
  Serial.println("USB device connected.");

  if (usb.mount(&msd) == 0) {
    Serial.println("USB drive mounted.");
  } else {
    Serial.println("Failed to mount USB drive.");
  }
}

void loop() {
  // Simulated temperature readings (replace with actual sensor data)
  float tempSensor1 = 25.5;
  float tempSensor2 = 26.0;
  float tempSensor3 = 24.8;
  float tempSensor4 = 25.2;

  // Create a file on the USB drive
  FILE *file = fopen("/usb/temperature_data.txt", "a"); // Append mode
  if (file) {
    fprintf(file, "Sensor 1: %.2f°C\n", tempSensor1);
    fprintf(file, "Sensor 2: %.2f°C\n", tempSensor2);
    fprintf(file, "Sensor 3: %.2f°C\n", tempSensor3);
    fprintf(file, "Sensor 4: %.2f°C\n", tempSensor4);
    fclose(file);
    Serial.println("Data written to USB drive.");
  } else {
    Serial.println("Error opening file.");
  }

  delay(5000); // Adjust the delay as needed
}

The issue persists. However, it's taking relatively longer time than before for the crash. I don't think the external usb fileread/write is made to be called repeatedly which probably explains why Arduino doesn't mention this method for datalogging in their built in examples. There is one mentioned using micro SD though. planning to try it out.

Hi,

I have the same problem of the red light of doom when writing to the USB file. What ended up resolving it?

Cheers
Stu

Unfortunately, i couldn't find a solution. however, I switched to using microSD instead of the usb and it works well.

Hi!
How did that work with an Arduino Giga R1 with just a USB-A port? Did you use an adaptor: USB-A to MicroSD? Which model of adaptor did you get?
Or did you literally get a MicroSD connector to the Arduino board?!
Thanks!
Stu

i used a MicroSd module. here's a link to it on amazon Robodo MO20 Micro SD Card Module Reader Slot Socket Shield Arduino Arm MCU Read and Write SPI : Amazon.in: Industrial & Scientific