Duplicating Information in SDCARD

2

Hello

I'm studying the use of SDCARD in Arduino and I need to write the values of the sensors into a .TXT file, but it gets duplicate information in the .TXT file as it goes through the FOR loop, why? I'm cracking my ass all night, but I'm not finding the error, it may be a silly thing, but I'm not locating. What is wrong?

You're recording like this:

Um
Dois
Um
Dois

My code:

 #include <SdFat.h>

 SdFat sdCard;
 SdFile meuArquivo;

 const int chipSelect = 4;

 void setup()
 {
 // nada a ser feito no setup
 Serial.begin(9600);

 // Inicializa o modulo SD
 if(!sdCard.begin(chipSelect,SPI_HALF_SPEED))sdCard.initErrorHalt();
 // Abre o arquivo TESTANDO.TXT
 if (!meuArquivo.open("testando.txt", O_RDWR | O_CREAT | O_AT_END))
 {
   sdCard.errorHalt("Erro na abertura do arquivo testando.txt!");
 } 

}

void loop()
{
   gravar();
 }

 void gravar()
 {
  for (int i=0; i <= 20; i++){

  Serial.println(i);
  delay(10);

  if(i == 1)
  {
    Serial.println("Um");
    meuArquivo.println("Um");
  }
  else if(i == 2)
  {
    Serial.println("dois");
    meuArquivo.println("Dois");
    meuArquivo.close();
    while(1){};
  }
   else
  {

  }
   delay(100);
 } 
}

Thank you

    
asked by anonymous 29.04.2016 / 19:11

1 answer

1

The loop() function is executed infinitely and in the gravar() function you create a i variable and assign a 0 value every time the gravar() function is called (infinitely). Try this:

#include <SdFat.h>

 SdFat sdCard;
 SdFile meuArquivo;

 const int chipSelect = 4;
 int executaUmaVez = 0;
 void setup()
 {
 // nada a ser feito no setup
 Serial.begin(9600);

 // Inicializa o modulo SD
 if(!sdCard.begin(chipSelect,SPI_HALF_SPEED))sdCard.initErrorHalt();
 // Abre o arquivo TESTANDO.TXT
 if (!meuArquivo.open("testando.txt", O_RDWR | O_CREAT | O_AT_END))
 {
   sdCard.errorHalt("Erro na abertura do arquivo testando.txt!");
 } 

}

void loop()
{
    if(executaUmaVez ==0){
       gravar();
       executaUmaVez=1;
    }
 }

 void gravar()
 {
  for (int i=0; i <= 20; i++){

  Serial.println(i);
  delay(10);

  if(i == 1)
  {
    Serial.println("Um");
        meuArquivo.println("Um");
  }
  if(i == 2)
  {
    Serial.println("dois");
    meuArquivo.println("Dois");
    meuArquivo.close();
   }
   delay(100);

 } 
}
    
29.04.2016 / 22:14