Hardware Reference
In-Depth Information
return;
}
Serial.println("Card Ready");
Note that instead of just calling SD.begin(CS_pin) , it is executed within an
if statement. This tries to initialize the SD card and it returns a status. If it
returns true , the program moves on, and a success message is printed to the
serial terminal. If it returns false , a failure message is reported, and the return
command halts further execution of the program.
You use a similar approach when you are ready to write a new line of data to
a log file. If you want to write “hello” to a new line in the file, the code would
look like this:
File dataFile = SD.open("log.csv", FILE_WRITE);
if (dataFile)
{
dataFile.println("hello");
dataFile.close(); //Data isn't written until we close the connection!
}
else
{
Serial.println("Couldn't open log file");
}
This first line creates a new file (or opens the file if it exists) called log.csv
on the SD card. If the file is opened/created successfully, the dataFile variable
will be true , and the write process will be initiated. If it is false , an error is
reported to the serial monitor. Writing new lines to a file is easy: Just execute
dataFile.println() and pass what you want to write to a new line. You can
also use print() to prevent appending a newline character to the end. This is
sent to a buffer, and only actually added to the file once the close command is
called on the same File .
Now, you can bring all this knowledge together into a simple program that will
create a log.csv file on your SD card and write a comma-separated timestamp
and phrase every 5 seconds. On each line of the CSV file, you record the current
time from millis() and a simple phrase. This might not seem very useful, but
it is an important step to test before you start adding actual measurements in
the coming examples. The code should look something like Listing 13-1.
Listing 13-1: SD Card Write Test—write_to_sd.ino
//Write to SD card
#include <SD.h>
Search WWH ::




Custom Search