In this example we will add a DS18B20 temperature sensor and an SD card. We will then log the results of the sensor to a file on the SD Card called temp.txt.
Layout
Code
You need to download 2 libraries and copy them into your Arduino libraries folder.
“DallasTemperature” Library
“1-Wire” Library
[c]
#include <SD.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define DS18B20 7
const int chipSelect = 4;
OneWire ourWire(DS18B20);
DallasTemperature sensors(&ourWire);
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
Serial.print(“Initializing SD card…”);
pinMode(10, OUTPUT);
//init SD card
if (!SD.begin(chipSelect))
{
Serial.println(“Card failed, or not present”);
return;
}
Serial.println(“card initialized.”);
sensors.begin();
}
void loop()
{
sensors.requestTemperatures();
// open the file.
File dataFile = SD.open(“temp.txt”, FILE_WRITE);
// if the file is available, write to it:
if (dataFile)
{
dataFile.println(sensors.getTempCByIndex(0));
dataFile.close();
}
// if the file isn’t open
else
{
Serial.println(“error opening temp.txt”);
}
}
[/c]
Results
Run the example, then remove the SD Card from your SD Card breakout, connect it to your PC and open the temp.txt and look at the contents
Here is some of the entries in my file
28.19
28.44
28.44
28.69
28.69
28.69
28.87
28.87
29.12
29.12
29.25
Links