MySQL for the Internet of Things

(Steven Felgate) #1

// Setup the network connection
Ethernet.begin(mac_addr);


delay(1000);
// Test the connection
Serial.println("Testing connection...");
if (conn.connect(server_addr, 3306, user, password)) {
delay(1000);
Serial.println("Success!");
conn.close();
} else {
Serial.println("ERROR: Connection failed.");
}
}


void loop() {
int value;


// Read the sensor
value = analogRead(sensorPin);


// Attempt to connect to the database server
if (!conn.connected()) {
if (conn.connect(server_addr, 3306, user, password)) {
delay(1000);
dump_cache(); // read any rows stored in the cache file
}
}
// Save the data to the database if connected
if (conn.connected()) {
Serial.println("Writing data");
write_data(value, "NULL");
} else {
// Database unreachable, save data to the cache file
cache_data(value);
}
conn.close();
delay(2000); // wait for it...
}


I want to call your attention to two things in this code. First, notice the last delay() method. Use this
method to set the amount of time you want the sketch to wait to take samples. Since we are just testing the
sketch, you can keep this short (2 seconds), but you may want that much longer should you implement this
code or a derivative for your own data collectors. Second, notice I have added many informational messages.
Some would suggest I’ve added too many, and indeed if you took them out, it would save some space, but
I put them there so that I could see how the sketch was running (more precisely, when the data is cached,
read from cache, and written to the database). Let’s see that it action.


ChapTEr 8 ■ DEmonsTraTion of high availabiliTy TEChniquEs

Free download pdf