Record Data on a SD Card

Overview:

One of the most important things in engineering (really in life) is data logging and the ability to go back and look at whats going on. Typically you would need the Arduino connected to the computer so that you can record, copy, and then paste the code into excel.  As a result, you typically can’t go very far from your computer. So is there another way to record data but not be confined to a computer? The answer is yes, and it’s pretty easy to do also.  All you need is an SD card and a method for the SD card and the Arduino to communicate (SD card Module).

There are libraries that easily handle the reading and writing to an SD card.  For this tutorial, we are only going to be looking at writing to the SD card.

I’m going to show you how to wire the SD card module along with a DHT11 temperature and barometric pressure sensor.  You will then record data from the DHT11 onto the Arduino SD card module

 

Components:

1X Arduino Compatible Board

1X Male – Male jumper cables

1X DHT11 module

1XSD card Module

dht11 and SD

Code:

 

#include <DHT.h>
#include <SPI.h>
#include <SD.h>


int DHTPIN = 2;
const int chipSelect = 4;
unsigned long Secs=0;
#define DHTTYPE DHT11   // DHT 11

DHT dht(DHTPIN, DHTTYPE);


void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  dht.begin();

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  // make a string for assembling the data to log:
  String dataString = "";
  int h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature(true); //true : fahrenheit   false:celsius
  unsigned long Secs=millis();

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("temp.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(String(Secs)+","+String(h)+","+String(t));
    dataFile.close();
    // print to the serial port too:
    Serial.println(String(Secs)+","+String(h)+","+String(t));
    delay(6000);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}










corra02

Leave a Reply

Your email address will not be published.