Real Time Clock
AIM
I fixed one of the limits of my datalogger: the Arduino doesn't know what time it is. I just bought this DS1307 RTC (Real Time Clock) for a dollar, to add the function of time to my recordings. The DS1307 has an integrated I2C interface which makes it easy to communicate date and time using strings. It also has its own library to control the clock with easy commands. In this experiment I just added the clock function to my datalogger experiment, so I can see date and time for each data record.
SKETCH
This code is a copy of the datalogger project, plus the commands of the RTC. For the RTC I'm referring to the book "exploring arduino" from Jeremy Blum. I found it very useful and I recommend you to buy it. It covers basic to advanced topics, including practical projects, and it explains about electronics and useful components, not only Arduino. You can download the RTClib.h library here. Note that it's in a folder named "RTClib-master", which can't be read by the Arduino IDE. You have to rename it without "-" symbol.
As you can see, in the setup loop the code says "if the clock is not running write date and time from computer". Then the clock starts running. In the loop we extract the data we want from the string (year, month, day, hour, minute, seconds) and we set the format of date and time. These strings are then added to the string recorded to the SD card in the file "datalogger.log", separated by a tab ("\t").
#include <DHT11.h>
#include <SD.h>
#include <Wire.h> //For RTC
#include "RTClib.h" //For RTC
int pin=3;
DHT11 dht11(pin);
RTC_DS1307 RTC;
String year, month, day, hour, minute, second, time, date;
const int chipSelect = 10;
void setup()
{
pinMode(10, OUTPUT);
if (!SD.begin(chipSelect)) {
return;
}
Wire.begin();
RTC.begin();
if (! RTC.isrunning())
{
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}
void loop()
{
DateTime datetime = RTC.now();
year = String(datetime.year(), DEC);
month = String(datetime.month(), DEC);
day = String(datetime.day(), DEC);
hour = String(datetime.hour(), DEC);
minute = String(datetime.minute(), DEC);
second = String(datetime.second(), DEC);
date = year + "/" + month + "/" + day;
time = hour + ":" + minute + ":" + second;
int err;
float temp, humi;
if((err=dht11.read(humi, temp))==0)
{
int t,h;
t = (int) temp;
h = (int) humi;
String dataString = "";
dataString += date;
dataString += "\t";
dataString += time;
dataString += "\t";
dataString += "temperature:";
dataString += String(t);
dataString += "\t";
dataString += "humidity:";
dataString += String(h);
dataString += "\t";
dataString += "light:";
dataString += String(analogRead(0));
File dataFile = SD.open("datalog.log", FILE_WRITE);
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
}
}
delay(3000);
}
No comments:
Post a Comment