Search code examples
arduinotext-filessd-cardarduino-yun

How can I create a text file on an SD card mounted on an Arduino Yun?


Like the title says, I am trying to create a text file from my Arduino sketch. My Arduino is connected to my computer via an Ethernet cable but the SD card is mounted on the Arduino, so I am assuming the connection to the computer (USB or Ethernet) does not matter. What I've found on the official Arduino documentation seems pretty straightforward, but yet I can't get to create the file.

Here is my code:

#include <Bridge.h>
#include <Console.h>
#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Start using the Bridge.
  Bridge.begin();
  // To output on the Serial Monitor
  Console.begin();
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  if (!SD.begin(4)) {
    Console.println("initialization failed!");
    //return;
  }
  Console.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    Console.print("Writing to test.txt...\n");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Console.print("done.\n");
  } else {
    // if the file didn't open, print an error:
    Console.print("error opening test.txt\n");
  }
  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Console.print("test.txt: ");
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Console.print(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Console.print("error opening test.txt\n");
  }
}

void loop() {
  Console.print("Loop\n");
  delay(1000);
}

And this is the output:

initialization failed!
initialization done.
error opening test.txterror opening test.txt
Loop
[...]
Loop

As opposed to the link I provided above, I am using Console instead of Serial for the print statements. The rest is the same. And I obviously have an SD card mounted.

Any idea anyone?


Solution

  • As suggested by gre_gor in the comments I followed this tutorial specifically for the Arduino Yun: https://www.arduino.cc/en/Tutorial/YunDatalogger. I had to change the path to the file on the SD card (mine was '/mnt/sda1/myFile.txt') and I had to delete these two lines in the setup function:

    // Delete these two lines:
    while (!SerialUSB); // wait for Serial port to connect.
    SerialUSB.println("Filesystem datalogger\n");
    

    And it worked.