Home LearningBasics SD card example

SD card example

by shedboy71

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

#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”);
}
}

Links

sd card breakout at Amazon

sd card breakout on Amazon UK

Share

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More