MySQL for the Internet of Things

(Steven Felgate) #1
Chapter 4 ■ Data transformation

Listing 4-4. Date and Time Annotation (Arduino)


String get_datetime() {
DateTime now = rtc.now();
String dateStr = String(now.day());
dateStr += "/";
dateStr += now.month();
dateStr += "/";
dateStr += now.year();
dateStr += " ";
dateStr += String(now.hour());
dateStr += ":";
dateStr += String(now.minute());
dateStr += ":";
dateStr += String(now.second());
return dateStr;
}


void loop() {
delay(2000);
log_file = SD.open("data_log.txt", FILE_WRITE);
if (log_file) {
Serial.println("Log file open.");
strData = String("Temperature sensor: ");
strData += read_sensor(1);
strData += " ";
delay(1000);
strData += ", Barometric sensor: ";
strData += read_sensor(2);
strData += " ";
strData += get_datetime();
log_file.println(strData);
Serial.print("Data written: ");
Serial.println(strData);
log_file.close();
Serial.println("Log file closed.");
delay(2000);
} else {
Serial.println("ERROR: Cannot open file for reading.");
}
}


As you can see, the code is nearly the same as the previous example. The only difference is the addition
of the method named get_datetime() to get and format the date and time returning a string, which we then
append to the row being written to the file. Sample rows from this code are shown here:


Temperature sensor: 92.33, Barometric sensor: 15.23 Datetime: 11/07/2015 22:36:32
Temperature sensor: 90.72, Barometric sensor: 15.32 Datetime: 11/07/2015 22:36:48
Temperature sensor: 94.38, Barometric sensor: 15.13 Datetime: 11/07/2015 22:36:50
Temperature sensor: 96.74, Barometric sensor: 14.95 Datetime: 11/07/2015 22:36:50

Free download pdf