MySQL for the Internet of Things

(Steven Felgate) #1
ChapTEr 8 ■ DEmonsTraTion of high availabiliTy TEChniquEs

elapsedTime = 0;
#else
Wire.begin();
#endif
pinMode(13, OUTPUT); // turn on onboard LED (pin 13)
Serial.begin(115200);
// TODO: Add any database initialization code here
}


So, what is that callback for the slave? Here we simply receive a message from the master. The code to
do this is shown next and is pretty self-explanatory. Notice we read the characters from the master and print
them out to the serial monitor. We really don’t care what message the master sends, just so long as it sends
something. Notice too we set up the timer to start over whenever the master has sent a message.


void getHeartbeat(int chars) {
char ch;
while (Wire.available()) {
ch = Wire.read();
}
Serial.println("Master is ok.");
// Reset timer since master is Ok
startTime = millis();
elapsedTime = 0;
blink(); // visual feedback
}


On the master, we send the message with the following code. As you can see, we just write a simple,
short message. However, we cannot broadcast a message on the I2C bus; it must be directed to a specific
device. Here we use a simple variable, address, to set the address. Since the code is from the same file, we
ensure both master and slave are compiled with the same value.


void sendHeartbeat() {
Wire.beginTransmission(address);
Wire.write("hello!");
Wire.endTransmission();
blink(); // visual feedback
}


I should note at this point that we don’t want code specifically for the slave to be included with the
master (it will just waste precious memory), so you will see the conditional compilation block around the
slave-specific code.
So, how does the slave know the master is dead? We use the timeout code designated with the
elapsedTime, startTime, and maxTime variables. That is, we record the number of milliseconds from the
Arduino with millis()^10 each time through our loop so that if the time elapsed is more than the maximum
time set, we declare the master dead. In this case, we write the sketch (code) for the slave to execute the
same code the master does to read the sensor and save the data to the database.


(^10) A rudimentary albeit slightly inaccurate way to measure time without a real-time clock but good enough for use as a
rough timer.

Free download pdf