MySQL for the Internet of Things

(Steven Felgate) #1

ChapTEr 8 ■ DEmonsTraTion of high availabiliTy TEChniquEs


images courtesy of sparkfun.com.

Write the Sketch


The example code is simplified to make it easier to experiment with. More specifically, I do not include any
code for reading sensors or writing to the database. I have left comments for where you would add these
elements. Recall, we always want to start with skeleton code like this when developing complex solutions.
If you lumped everything in one code file and something wasn’t working, you may not be able to easily
discover which part is causing the problem (or even if multiple parts are failing).
I also use a trick of programming called condition compilation. This allows me to have sections of the
code that can be used (compiled) one way but discarded if used (compiled) another. In this case, I wanted
one source file but conditionally use some parts for the master and other parts for the slave.
To mark sections as conditional, we use the #if defined clause and its opposite #if not defined
clause along with a #define to determine which code is included when we compile and upload. Thus, in the
following code, you will see a #define SLAVE that you can comment out and cause the code to compile for
the master. Again, leave #define SLAVE and the code is compiled as the slave; comment it out and you’ve got
the master.
Rather than throw all the code at you at once, let’s go through each piece and discuss what needs to be
done starting with the setup() code for each master and slave.
The code needed for the master and slave communication comes from the wire library. Both the
master and slave must initiate the wire protocol with wire.begin(), but the slave needs to register the
device number and provide a callback (a special method that is called when an event is trigger, in this case
a message received from the master). Both master and slave need to set up a PIN for the LED and start the
serial class. Thus, the setup() code uses the conditional compilation as discussed earlier. The code is shown
next. Notice how the code for the slave does more than the master and we have a section that is not in the
conditional compilation block. This code is compiled for either master or slave.


void setup() {
#if defined SLAVE
Wire.begin(address); // join i2c bus
Wire.onReceive(getHeartbeat); // register the heartbeat code
startTime = millis(); // initiate timer

Free download pdf