Home LearningBasics SD card example

SD card example

by shedboy71
[lebox id="1"]

In this example we connect an SD card to our Arduino, we will log analog readings to a file on the SD card.

SD card

SD card

Here is the layout

 

arduino and sdcard bb

arduino and sdcard bb

Code
[c]
#include <SD.h>

const int chipSelect = 4;

void setup()
{

Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
Serial.print(“Initializing SD card…”);
pinMode(10, OUTPUT);

//iniot SD card
if (!SD.begin(chipSelect))
{
Serial.println(“Card failed, or not present”);
return;
}
Serial.println(“card initialized.”);
}

void loop()
{

String dataString = “”;

// read three sensors and append to the string
for (int analogPin = 0; analogPin < 3; analogPin++)
{
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2)
{
dataString += “,”;
}
}

// open the file.
File dataFile = SD.open(“data.txt”, FILE_WRITE);

// if the file is available, write to it:
if (dataFile)
{
dataFile.println(dataString);
dataFile.close();
}
// if the file isn’t open
else
{
Serial.println(“error opening data.txt”);
}
}
[/c]

Links

sd card breakout at Amazon

sd card breakout on Amazon UK

Share
[lebox id="2"]

You may also like