MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 4 ■ Data transformation


void setup() {
Serial.begin(115200);
while (!Serial);
Serial.print("Initializing SD card...");
if (!SD.begin(SD_PIN)) {
Serial.println("ERROR!");
return;
}
Serial.println("ready.");


if (SD.remove("data_log.txt")) {
Serial.println("file removed");
}


// initiate random seed
randomSeed(analogRead(0));
}


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);
log_file.println(strData);
Serial.print("Data written: ");
Serial.println(strData);
log_file.close();
Serial.println("Log file closed.");
} else {
Serial.println("ERROR: Cannot open file for reading.");
}
}


In this example, I use the String class to concatenate the strings with the sensor readings. While there
are other methods, this one seems clearer to demonstrate the annotation. Notice I place a comma in the
string before the second sensor. This comma can be used to help parse the data should you need to do so in
the future. For example, you can split the data on the comma and then locate the data values at the end of
the string after the colon. Here is a sample of the output or in this case an excerpt from the log file:


Temperature sensor: 90.82, Barometric sensor: 15.00
Temperature sensor: 91.43, Barometric sensor: 15.09
Temperature sensor: 91.13, Barometric sensor: 15.23

Free download pdf