Categories
TUTORIALS

Writing and Reading Data to an SD Card

Occasionally, it is necessary to store and recall more data than can fit on a standard Arduino board. With the addition of an SD data logger shield, we can store more data, but still access when needed. In this tutorial, you will sense light intensity through a photo sensor and store the readings every second on an SD card. You will also average the last 5 reading on the SD card and print this average to the serial port. This can be easily adapted to other sensor applications or averaging over a longer window.

Parts List
Schematic

 

Circuit and Board Setup

If your data logger shield did not come with header pins attached, then the first thing you will need to do is solder on those header pins. Once connected, carefully stack the data logger shield on your Arduino Uno (or other R3 compatible board). Wire the circuit according to the schematic, with a pull-up resistor between the 5V pin and the sensor pin (pin 0) and the photo-resistor between the sensor pin and ground.

Code

When working with files on an SD card, it can be challenging to name files and not overwrite previously recorded data.  The code snippet below will create a new file each time Arduino restarts and advance the number at the end of the name by 1.

 

Once the file is named, there are three parts involved in writing to an SD file. Opening the file, writing to the file, and closing the file. In the following snippet, we open the SDfile, write two values separated by a tab character, and close the file.

 

We can also access  data and work with information written to the SD card. In this last snippet, we read the last 5 values from the SD card and calculate their average.

 

The complete code for this sketch is included below. The frequency of sensor readings can be manipulated by changing the value in the delay() function. You can also change the number of values used in calculating the average by changing the for loop to include more past values.

One reply on “Writing and Reading Data to an SD Card”

Thanks for your interesting post on writing/reading to/from SD.

Would appreciate any suggestions you can give for the following project: I use Arduino to read an analog sensor, display the values on TFT and store them as txt file on SD. I would like to play back the txt file from SD and display it on the TFT–in other words to redisplay the initial recording. My attempts so far have failed. I haven’t found any projects that purport to accomplish this goal although it sounds as if it should be simple and something that many people might like to do.

Leave a Reply

Your email address will not be published. Required fields are marked *