Home ArduinoArduino Code Arduino SD card example

Arduino SD card example

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

Here is the layout

 

arduino and sdcard

arduino and sdcard

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

You may also like

1 comment

AirSense, a DIY, cheap, air quality sensor | Bocho's Blog August 8, 2017 - 8:16 pm

[…] SD card reader wasn’t Grove-compatible either, but it’s to find an example of how to connect […]

Comments are closed.