Arduino mega stops looping after a while

Hello arduino community!

I have a problem with my arduino. I’ve recently gotten into programming and found it quite fun but i can figure this one out.

What i want to do is quite simple, i want to store my sensor data to a SD card which it does. The only problem is is that the arduino stops after a couple of loops and i cant figure out why.

To my arduino i have a robodyn moisture sensor, a AM2320 sensor and a TFT screen which i currently use as an SD card reader connected.

Here is my code:

#include <AM2320.h> 
#include <SD.h>
#include <SPI.h>
File myFile;
int pinCS = 53;

#define SensorPin A0 
float sensorValue = 0; 
AM2320 sensor; 


void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
sensor.begin();
Serial.print("Arduino is ready");
pinMode(pinCS, OUTPUT);

  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }

  
}

void loop() {
  
  // put your main code here, to run repeatedly:
if (sensor.measure()) {
  Serial.print("temperature:");
  Serial.println(sensor.getTemperature());
  Serial.print("humidity:");
  Serial.print(sensor.getHumidity());
  delay(1);
}
else delay(1000);;
 for (int i = 0; i <= 100; i++) 
 { 
   sensorValue = sensorValue + analogRead(SensorPin); 
   delay(1); 
 } 
 sensorValue = sensorValue/100.0; 
 Serial.print("Soil Moisture: ");
 Serial.println(sensorValue); 

  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {    
    myFile.print(float(sensor.getTemperature()));
    myFile.print(",");    
    myFile.println(float(sensor.getHumidity()));
    myFile.print(",");
    myFile.println(float(sensorValue));
    myFile.close(); 
  }
  // if the file didn't open, print an error:
  else {
    Serial.println("error opening test.txt");
  }
delay(3000);
}

I have a hunch that it is due to getting stuck on an if statement, but i dont know which one!

To find out which if-statement it is add serial-debug-output to the if.conditions and you will find it

best regards Stefan

haxorb:
I have a hunch that it is due to getting stuck on an if statement, but i dont know which one!

You only have two IF statements in loop(). In one of them you print stuff so it should be obvious if it works normally. Add a print statement into the other one and you will be able to see if it works normally.

If this was my project I would do this in two stages

myFile.print(float(sensor.getTemperature()));

First I would save the value to a variable as that would allow me to print it to check if it is getting the correct value and then, separately, I would save the variable values to the SD Card. That would ensure that the SD Card writing process is as simple as possible. Something like

float tempVal = sensor.getTemperature();
float humidVal = sensor.getHumidity();
// etc

myFile.print(tempVal);
myFile.print(',');
myFile.print(humdVal);
// etc

…R