The Internet of Things - Getting Started with Spark Core and Photon (2015)

Getting Started with Spark Core and Photon (2015)

Chapter 5. The Internet of Things

Aside from actually programming the Photon/Core over the Internet, everything we have done up to now with the these could have been done with a device such as an Arduino without any internet connection. While the Photon/Core is actually pretty good in the role of an Arduino replacement, to not use its Internet of Things capabilities is to miss out on its most exciting feature.

In this chapter, you will learn how to communicate with a Photon or Core over the Internet to both issue commands to the device and also take readings from its sensors.

Spark Functions

Many IoT devices require you to do some pretty hairy network programming to have your device communicate with the Internet. Not so the Photon and Core. Spark have managed to provide a simple and easy to use framework for using your Photon/Core over the Internet.

In a later section of this chapter, you will learn about reading information from the Photon/Core. In this section I will concentrate on sending instructions to the Photon over the Internet. For example in the next project you will be able to send an HTTP post to a URL that then turns on an LED on the Photon.

The key to telling your Photon or Core to do things is the concept of a “Function." To distinguish Spark Functions from C language functions in your programs, I will use an uppercase F when referring to Spark Functions.

A Function associates a command that you can send to the Photon/Core with a C function on that device’s app. Whenever the device receives that command, it runs the associated C function. Rather like a regular C function, the function in the app also receives a parameter. The parameter is always of type String, and it’s up to your function in the program as to how it uses that parameter, if indeed it uses the parameter at all.

Actions and Functions

Note that in earlier versions of the Spark software, Functions used to be called actions. This change was made to tie in better with the naming conventions of IFTTT (see Chapter 6).

You can define up to four Functions in the same program. This may sound restrictive, but remember, you can pass data to the function in its parameter and therefore do different things depending on that data.

In Project 6 you will make a simple example that will allow you to turn the built-in LED on pin D7 of the Photon/Core on and off from a command line. But first, if you are a Windows user, you will need to set up your environment.

Sending actions to a Photon/Core requires you to send HTTP post requests to the Spark service. A handy way to do this is using the command line tool called curl. If you are a Mac or Linux user, then the good news is that ‘curl’ will already be installed and ready to use. If you are running Windows, then you will need to install curl as described below.

Open your web browser on http://curl.haxx.se/download.html and scroll down to find the Win section of the downloads. Unless you have a really old computer, you will probably need the Win64 - Generic download.

Download the zip file and extract the single file it contains (curl.exe) to somewhere convenient, such as the desktop. Now start a command prompt by clicking the Start menu followed by the Run... option and enter cmd.

This will open a command window like the one shown in Figure 5-1. Change directory to wherever you saved curl.exe (in this case Desktop) and then run the command curl just to check that it’s ready to use.

Figure 5-1. Figure 5-1. Running curl on Windows

The command curl is used to send HTTP requests without having to use a browser. You will use this tool to sent commands over the Internet to your Photon/Core in the next project.

Project 6. Control an LED Over the Internet

This project just turns the LED attached to pin D7 of your Photon/Core on or off in response to commands over the Internet. Although in this case, its just an LED, the basic principal is pretty powerful, with the right hardware, you could be turning anything on or off.

The program for this app is called p_06_LED_function. The easiest way to get this onto your Photon/Core is to click on the Libraries button in the Web IDE and then find the library called PHOTON_BOOK. You will find all the project programs used in this book as examples.

Select the file p_06_LED_action and then click the button USE THIS EXAMPLE. A copy of the program will open up in the editor and you can then flash it to your Photon/Core. Note that this will be your own copy of the original program, so you can modify it if you wish.

Software

The code for p_06_LED_Function is as follows.

int ledPin = D7;

void setup() {

pinMode(ledPin, OUTPUT);

Spark.function("led", ledSwitcher);

}

void loop() {

}

int ledSwitcher(String command) {

if (command.equalsIgnoreCase("on")) {

digitalWrite(ledPin, HIGH);

return 1;

}

else if (command.equalsIgnoreCase("off")) {

digitalWrite(ledPin, LOW);

return 1;

}

return -1;

}

The code first defines a variable ledPin for the pin D7. This is the pin on the Photon/Core that has a tiny blue LED next to it. The setup function then defines this ledPin to be an OUTPUT.

The second line of setup is interesting:

Spark.function("led", ledSwitcher);

This is the line that defines the Function, giving it the name led. The second parameter ledSwitcher is the name of the C function in the program to be run when the led Function is invoked over the internet.

The loop function is completely empty. You could do something in here if you wanted, for example make a different LED blink, but it is perfectly ok to leave it empty. This program will only do something when the Function command is received.

When the ledSwitcher function is called as a result of a message arriving, it receives a String as its parameter. In the HTTP request that we are going to send, we will make sure that we either send “on” to turn the LED on or “off” to turn it off. Therefore the ledSwitcher function needs to check the value of the command parameter and perform the appropriate digital write to the pin connected tot eh LED. If the command is either “on” or “off” or for that matter versions of those words in any letter case, the function will then return 1 indicating success. Any other value of command will result in the value -1 being returned by the function.

The return value will actually be returned as part of the response to the HTTP request and this provides valuable information about whether the Function worked or not.

Security

Obviously, it would be potentially dangerous to allow every Spark user to have access to everyone’s Photons. For this reason, there are two long tokens that help secure your Photon.

The first token is a device ID for the Photon or Core. Each of your devices will have a different device ID. To find the device ID for your device, click on the Core’s button on the IDE and select the device whose ID you want. The ID of that Photon/Core will then be displayed. Note that my devices are called A, B, C and D.

Figure 5-2. Figure 5-2. Finding Your Device ID

To invoke a Function on that Photon/Core, you are going to need to know this ID. A good place to keep this temporarily is as a comment after the last line of your program. For example:

// Device ID=55ff74062678501139071667

The second token is not specific to a Photon/Core, but rather to your whole Spark account. You will find this if you click on the Settings button on the Web IDE, as shown in Figure 5-3.

Figure 5-3. Figure 5-3. Finding Your Access Token

You can at any time generate a new Access Token by clicking on the Reset Token button. In any case, the Access Token will expire after 90 days. (This may change.)

You will also need this token when sending web requests, so you can paste another comment line with it into your program.

// Device ID=55ff74062678501139071667

// Access Token=cb8b348000e9d0ea9e354990bbd39ccbfb57b30e

Trying it Out

Now that you have the program running on the Photon/Core, it will just be sitting there waiting for a led Function to arrive. Let’s give it what it wants by sending an HTTP request to the Spark web service. To do this, we will need to use the two tokens that we just discovered.

If you fetched p_06_LED_Function from the PHOTON_BOOK examples library, then you will see these lines at the end of the program:

// To test with curl

// curl https://api.spark.io/v1/devices/<deviceid>/led

-d access_token=<accesstoken> -d params=on

These lines tell us how to use curl to send an HTTP request to control the LED. But first you need to substitute your device ID and access token into the curl command. Once you have changed the comment command to include your tokens, it will look something like this:

// curl https://api.spark.io/v1/devices/55ff74062678501139071667/led

-d access_token=cb8b348000e9d0ea9e354990bbd39ccbfb57b30e

-d params=on

Note that I have split this over three lines for readability, but the command that you paste into your command line must all be on one line.

Paste the curl command (don’t include the // comment characters at the start) onto your command line as shown in Figure 5-4.

Figure 5-4. Figure 5-4. Controlling an LED with curl

If all is well the tiny blue LED on your Photon/Core should light up almost immediately and you will see a response from your device containing the information that the return_value is 1.

To turn the LED off again, issue the same command (use up arrow on your keyboard to recall the last command) and change on to off then press ENTER to run the modified command.

You’ll probably want to repeat this a few times, because its pretty cool.

Interacting with loop

Now that Project 6 is working in its most basic form, lets make a small change to the program, so that instead of just turning the LED on and off, the led Function will set the LED blinking or stop it blinking. You can find the app code for this in the book examples with the name P_06_LED_FUNCTION_BLINK.

int ledPin = D7;

boolean blinking = false;

void setup() {

pinMode(ledPin, OUTPUT);

Spark.function("led", ledSwitcher);

}

void loop() {

if (blinking) {

digitalWrite(ledPin, HIGH);

delay(200);

digitalWrite(ledPin, LOW);

delay(200);

}

}

int ledSwitcher(String command) {

if (command.equalsIgnoreCase("on")) {

blinking = true;

return 1;

}

else if (command.equalsIgnoreCase("off")) {

blinking = false;

return 1;

}

return -1;

}

This program has some code in the loop function. The code uses the flag variable called blinking. If blinking is set to true, the the LED will blink once. This will keep happening as long as blinking is true.

Now, the ledSwitcher function does not directly turn the LED on or off, but instead changes the value of the blinking flag.

Flash the program onto your Photon/Core and try issuing the same curl commands as you did for the previous program. Now the commands will start and stop the LED blinking rather than simply turn it on or off.

Running Functions from a Web Page

Although curl is good for testing out Functions, its in no way a slick user experience. What would be much nicer would be a web page that has buttons on it, so that when we click a button it controls the LED (see Figure 5-5).

Figure 5-5. Figure 5-5. Controlling an LED from a Webpage

There is a large Javascript library from Spark that encompasses everything from logging in and claiming devices through to calling Functions. You can learn more about this from the Spark documentation here: http://docs.spark.io/javascript/, but for now, to keep things simple, let’s use the more familiar jQuery Javascript library on a web page to send HTTP posts in much the same way as when we were using curl, but with a more pleasant user interface.

Start by re-flashing p_06_LED_function onto your Photon/Core. This is the program that simply responds to the “led” Function by either turning the tiny blue LED on D7 on or off, depending on the value of its parameter.

Although eventually, you might want to host the controlling page on a web server somewhere, you can test out the program just with an HTML file on your computer and your browser. The HTML page for this can be found in the “html” section of the downloads for this book available from the book’s Github repository at https://github.com/simonmonk/photon_book

Download the file from Github onto your own computer. If you are familiar with GitHub, then you may just want to clone the repository onto your computer to access all the example code in one go. If you do not have git installed on your computer and don’t want it, then you can just download a zip archive of all the example code by going to the URL above and then clicking on the Download ZIP button at the bottom right of the webpage.

However you did it, find the ch_05_led_control.html file and open it in a text editor. You also need to replace the values near the top for accessToken and deviceID with your own access token and device id.

Save the changes to the file and then open it in your browser by double-clicking on it. It should look just like Figure 5-5.

When you click on the ON button it should light the tiny blue LED and when you click on OFF, not surprisingly, it should turn the LED off.

Remember, the code running on the Photon/Core has not changed. All we have done here is use an HTML page to send the HTPP post when we press a button rather than use curl.

The HTML for the page is listed below:

<html><head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

<script>

var accessToken = "cb8b348000e9d0ea9e354990bbd39ccbfb57b30e";

var deviceID = "55ff74066678505539081667";

var url = "https://api.spark.io/v1/devices/" + deviceID + "/led";

function switchOn(){

$.post(url, {params: "on", access_token: accessToken });

}

function switchOff(){

$.post(url, {params: "off", access_token: accessToken });

}

</script></head>

<body>

<h1>On/Off Control</h1>

<input type="button" onClick="switchOn()" value="ON"/>

<input type="button" onClick="switchOff()" value="OFF"/>

</body></html>

If you have never seen HTML before then take a look at an HTML primer such as http://www.w3schools.com/html/html_intro.asp

The HTML file listed above contains a mixture of HTML itself, including text that will appear on the page such as the heading and button labels. It also contains some code written in the JavaScript programming language.

Javascript programs are often embedded in a web page to give it some intelligence, or fancy user interface effects. In this case, the Javascript is going to send the web requests to the Spark web service and hence to your Photon/Core.

If you have done any JavaScript programming in a web setting, you are likely to have come across the jQuery JavaScript library. This library includes loads of useful features for manipulating web pages. It also has a feature that allows it to make HTTP posts, which is just what you need to talk to your Photon/Core.

The jQuery library is imported from one of its homes on the Internet, and then we come to a second section of JavaScript, where some variables are defined for the access token and device ID. You should have already changed these values. The third variable url is constructed by splicing the value of deviceID into the middle of the url.

Next there are two nearly identical JavaScript functions. As you can see, JavaScript uses the same curly braces for blocks of code and has functions like C but with a different syntax.

If you look at the switchOn function, you can see that it contains the following.

$.post(url, {params: "on", access_token: accessToken });

The $ symbol is how you access the jQuery library functions, one of which is called post. It takes two parameters: the url and what looks like another block of code. This is a Javascript object and is a way of grouping together two values associated with names. The first value of “on” has the name params and the second links the value of the accessToken variable with the name access_token.

The names params and access_token will become post data to the HTTP post command. These are equivalent to the -d options used in curl.

The body section of the HTML file is responsible for actually displaying the heading and buttons on the web page. Each of the input buttons has an onClick event. When you click on one of the buttons it runs the JavaScript function switchOn or switchOff depending on which button you click.

Security

Now that you can create a webpage on your local hard drive to control your device, the temptation is to place the HTML file onto a web server, so that it can be accessed from anywhere.

You can do this, but not without compromising your security. Anyone doing “View Source” would immediately get access to your Device ID and Access Token. Its just there in the web page for all to see.

If this matters to you, then you should host the page behind a login screen, or on a web server that just runs within your network.

Project 7. Control Relays from a Webpage

In this project, you will build on what you have learned about using Functions, using web pages to control a relay. The software for the project is very similar the the LED example that we have just been through. There is just a bit of renaming of code, to make it more specific to relays rather than LEDs, and the code is extended so that all four relays on the relay shield can be controlled.

The real difference to the project is that it uses a Photon/Core attached to a relay shield. This will allow us to switch all sorts of things on and off.

AC Can Kill You

Although the relays on the relay board are technically capable of switching 120V AC at 10A, you should not use the board to control AC devices unless you are qualified to do so.

Some of the screw terminals on the board will be “hot” (also called “live”) if connected to AC, so anything made using this module that does control AC must be properly boxed and earthed so that there is no chance of any exposed metal being touched by unwary fingers.

Be warned every year hundreds of people in the US alone die accidentally from 120V AC electrocution, not to mention the many more people who receive serious burns.

You can still have lots of fun with the relay module, but I strongly suggest that you stick to using it to switch low voltage DC devices.

Note that one of the relays has an old-fashioned 12V electric bell attached to it. Figure 5-7 shows a simple web interface for controlling the relays.

Figure 5-7. Figure 5-7. A Webpage for Controlling Relays

Parts

To build this project, you are going to need the following parts in addition to your Photon/Core.

Part

Description

Appendix A code

Relay Shield

Spark shield to control 4 relays

M1

12V Power Supply

12V 1A Power supply

Q1

J1

DC jack to screw adapter (female)

H1

J2

DC jack to screw adapter (male)

H2

Bell

12V DC electric bell

Q2

Wire

Short lengths of multi-core wire.

H3

Table 5-1. Parts Bin

These days, most door bells are of the electronic variety, rather than a good old-fashioned bell complete with a solenoid driven sounder. You should still be able to find such things in your local hardware store, though. Look for something on the packaging that tells you the current that the bell is likely to consume and make sure that the power supply you get will be sufficient to provide this current plus 0.2A for the Photon/Core and relay shield. Most bells should be fine. The extremely noisy bell I used consumed much less than 1A.

Many intruder alarm sirens and strobe lights also operate from 12V, so this may be an interesting alternative to the electric bell.

You can use male-to-male jumper wires for some of the connections to the bell and relay shield, but these tend to have low current-handling capabilities; so some multi-core hookup wire or twin bell wire pulled apart into two strands is better. If you get into making electronics, you will find yourself scavenging odd bits of wire to keep for situations like this. You can also buy hookup wire in various colors.

RELAYS

A relay is basically an electromagnet that closes switch contacts. The fact that the coil of the electromagnet and the contacts are electrically isolated from one another makes relays great for things like switching AC-powered devices on and off from digital outputs like those of the Photon/Core. The coil of a relay takes just too much current to be driven directly from the digital output of a Photon, so the relay shield also has a small transistor to switch the relay coil. You will learn more about transistors in Chapter 12.

Whereas the coil of a relay is often energized by between 5V and 12V, the switch contacts can control high power high voltage loads. For example, the relay photographed in Figure 6-7 claims a maximum current of 10A at 120V AC as well as up to 10A at 24V DC.

Relays often have three switch terminals, COM (common), N.O. (normally open), N.C. (Normally Closed). When the relay coil is activated, the COM and N.O. terminals will be connected to each other. When there is no power to the relay coil, the N.C. and COM terminals will be connected. So, generally you will want to use the N.O. and COM connections to switch whatever you are controlling, so that when the power to the Photon/Core is off, the device being switched will also be off.

Design

You could also substitute 12V DC lighting or any other kind of 12V equipment for the bell. Just make sure that if the thing you are connecting has a positive and negative connection, then the positive connection goes to the power supply and the negative connection to the relay. In this case, the bell does not have a positive and negative.

As you can see, the 12V power supply provides power to both the Relay board and one side of the relay contacts that will switch the electric bell.

When the relay activates, the COM and N.O. (Normally Open) contacts of the relay will be connected together completing the circuit from the bell to the 12V power supply, making the bell sound.

Construction

This is an easy project to make: no soldering is required, and everything is hooked up using screw terminals. Use Figure 5-9 as a reference while you wire things up.

Step 1. Test and Wire the Bell

If the bell does not have flying leads, you will have to attach leads to it. This will depend on your bell, but it may well have screw terminals too. Having attached wires to it, it is not a bad idea to connect the two wires directly to the power supply, just to check that you have the right connections and that the power supply and bell are compatible.

Step 2. Complete the Wiring

The remainder of the wiring centers around the J1 adapter. The tricky bit here is that each of the screw connectors on the adapter must hold two wires. The positive connection on J1 must have one wire going off to the positive connection of J2 and another wire to the bell. The negative terminal of J1 must contain one lead to the negative connection on J1 and another wire to the COM screw terminal of relay 1.

Be very careful to make sure that the positive (+) connections of J1 and J2 are connected together.

Step 3. Plug in the Power Supply

Plug the DC jack from the power supply into J1 and switch it on. If you have a smartphone, you can use the Tinker App to turn pin D0 on and off. This should turn the bell on and off. Pin D0 is connected to Relay 1 on the Relay Shield.

Now you are ready for the software!

Software

The software for this project is in two parts, the app to be run on the Photon/Core and the HTML web page containing Javascript commands that will communicate with the Photon/Core.

Photon Software

The code for the Photon/Core is remarkably compact. The full listing is given below. You can find this code along with all the code used in the book. See the introduction to project 6 for instructions on getting hold of this.

int relayPins[] = {D0, D1, D2, D3};

void setup() {

for (int i = 0; i < 4; i++) {

pinMode(relayPins[i], OUTPUT);

}

Spark.function("relay", relaySwitcher);

}

void loop() {

}

int relaySwitcher(String command) {

if (command.length() != 2) return -1;

int relayNumber = command.charAt(0) - '0';

int state = command.charAt(1) - '0';

digitalWrite(relayPins[relayNumber-1], state);

return 1;

}

The first interesting thing about this program is that it uses an array to access the four digital pins used to control the relays. The pins that control the relay are D0 to D3, where D0 controls relay 1, D1 relay 2 and so on.

The setup function uses a loop to initialize all four pins as outputs and then defines a Spark Function called relay that will invoke the C function relaySwitcher.

The relaySwitcher function is able to switch any of the four relays on and off, not just the one we have connected to a bell. To do this, it uses its command parameter. The relaySwitcher function expects the command parameter to be exactly two characters long, so the first thing the function does is to check that this is the case. If command isn’t two characters long, then -1 is returned to indicate an error.

Assuming that the command parameter is two characters, then the first character will be the number of the relay to control (1 to 4) and the second character will be 1 to turn the relay on or 0 to turn it off.

The code uses a useful trick to convert the character value of the relay number which is of type char to an int.

int relayNumber = command.charAt(0) - '0';

The trick is to subtract the character value of “0” from the character value of the first character in the command (command.charAt(0)).

The digitalWrite command uses the array and the relay number to decide which pin to set to either 0 or 1 from the value passed in the second character of the command.

Webpage Software

When it comes to the webpage software to control the relays, we will start gently, with a modified version of the HTML and Javascript that we used in the section Running Functions from a Webpage. The problem with that solution is that if something goes wrong, perhaps the Photon/Core isn’t connected to the network, then there is no way of knowing from the webpage whether the command was successful and the relay actually turned on.

To get around this problem, there will be a second more complicated version of the webpage that uses the response from the device to provide feedback on the success or failure of the Function command.

Both versions are available from the book’s Github page at https://github.com/simonmonk/photon_book in the “html” section of the repository. The first version (listed below) is called ch_06_relays.html and the improved version is called ch_06_relays_fb.html.

<html><head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

<script>

var accessToken = "cb8b348000e9d0ea9e354990bbd39ccbfb57b30e";

var deviceID = "54ff72066672524860351167";

var url = "https://api.spark.io/v1/devices/" + deviceID + "/relay";

function setRelay(message){

$.post(url, {params: message, access_token: accessToken });

}

</script>

</head>

<body>

<h1>Relay Control</h1>

<table>

<tr>

<td><input type="button" onClick="setRelay('11')"

value="Relay 1 ON"/></td>

<td><input type="button" onClick="setRelay('10')"

value="Relay 1 OFF"/></td>

</tr>

<tr>

<td><input type="button" onClick="setRelay('21')"

value="Relay 2 ON"/></td>

<td><input type="button" onClick="setRelay('20')"

value="Relay 2 OFF"/></td>

</tr>

<tr>

<td><input type="button" onClick="setRelay('31')"

value="Relay 3 ON"/></td>

<td><input type="button" onClick="setRelay('30')"

value="Relay 3 OFF"/></td>

</tr>

<tr>

<td><input type="button" onClick="setRelay('41')"

value="Relay 4 ON"/></td>

<td><input type="button" onClick="setRelay('40')"

value="Relay 4 OFF"/></td>

</tr></table>

</body></html>

The first part of the webpage is exactly the same as the example from Running Functions from a Webpage. Variables are defined for the accessToken and deviceID that you will need to change to match your own access token and device ID.

The separate functions that turned the LED on and off are replaced by a single Javascript function called setRelay. The setRelay function is passed as a parameter called message that will contain the two character code for controlling the relay. The first character being the relay number and the second 1 or 0 to indicate on or off.

The buttons in the user interface call setRelay with the right value for the button being pressed.

After editing the deviceID and accessToken variables for your values, open the file in your browser by double clicking on it. The browser window should look like Figure 5-10.

Figure 5-10. Figure 5-10. A Basic Web Interface for Relays

When you click on the Relay 1 ON button, the relay should click, the little light next to it come on and most importantly the bell will sound. You’ll probably want to turn it off again quickly, so click on Relay 1 OFF.

Try the other buttons to make sure that you can control all the relays.

One snag with this interface to the relays is that if you turn off the power to the relay shield and hence the Photon/Core, the webpage will carry on behaving exactly as it currently does, without any indication that nothing is actually happening at the other end of the connection.

This second version of the web page, which is the interface shown in Figure 5-7, has a single button for each relay. Clicking on the button toggles the relay for that button on and off, and changes the color of the button to indicate that the relay is on. However, the button does not change color to indicate that the relay is on until it receives confirmation from the Photon/Core that the Function worked successfully.

The code for this webpage (ch_06_relays_fb.html) is not listed in full below as it’s some 60 lines long. You may wish to have the file open in an editor while the code is explained.

<style type="text/css">

.on { background:green; }

.off { background:red; }

input[type=button] {

color: white;

font-size: 2.5em;

}

</style>

The style block defines the colors to be used with the button for its on and off states and also increases the size of the font on the buttons.

Before looking at the Javascript function toggleState, where all the action happens, it is perhaps worth looking at how it is called from one of the buttons:

<input type="button" id="btn" value="Relay 1" class="off"

onclick="toggleState(this, '1')" />

When a button is clicked, toggleState is called with two parameters. The first parameter is this, which refers to the button being pressed. The toggleState function will need this to determine the current state of the button. The second parameter is the relay number as a string.

The toggleState function is listed below:

function toggleState(item, relayNumber){

function setRelay(message){

$.post(url, {params: message, access_token: accessToken}, callback);

}

function callback(data, status){

if (data.return_value == 1) {

if (item.className == "on") {

item.className="off";

}

else {

item.className="on";

}

}

else

{

alert("Could not Connect to Photon");

}

}

if(item.className == "on") {

setRelay(relayNumber + "0");

} else {

setRelay(relayNumber + "1");

}

}

In this case, the functions setRelay and callBack are defined within toggleState, so that they can have access to toggleState’s variables, in particular to its item parameter. The setRelay function doesn’t actually need this, but it makes sense to keep both functions together as they are closely related.

The setRelay function is very like the earlier version of this function in the simplified version of this page. There is one important difference and that is that the call to $.post now includes an additional parameter of callback. This is a reference to the other function inside toggleState. Thecallback function will automatically be run when the web request to the Photon/Core completes. We will return to the callback function shortly, but first let’s look at the main body of the toggleState function.

if(item.className == "on") {

setRelay(relayNumber + "0");

} else {

setRelay(relayNumber + "1");

}

The item variable contains a reference to the button that was clicked and its className will either be on or off depending on the current state of the button. The setRelay function is then called, appending 0 or 1 to the relay number as appropriate. Note that at this point the appearance of the button has not changed; this will only happen if the communication with the device is successful.

When the request to the Photon/Core completes, the callback function will be invoked. Its first parameter (data) will be the response from the Photon/Core via the Spark web service. This is the same response that you are used to seeing as a result of a curl command to invoke a Function. Thecallback function picks out the return_value from this response and as long as it is 1, indicating success (-1 indicates failure), the button appearance is changed by setting its className.

If callback does not get a response of 1, then it alerts an error message saying “Could not connect to Photon.”

Remembering to change the accessToken and deviceID variable in your file, open a browser on the page and try turning some relays on and off.

Project 8. Morse Code Text Messages

Projects 5 and 6 both flashed out a Morse Code message, but suffered from the limitation that the message was fixed. The only way to change the message was to alter the value of the message variable in the program and then flash it onto your Photon/Core.

In this project the message to be sent as Morse Code is sent as the parameter to a Spark Function. The maximum length of this parameter is 64 characters, so you will need to keep your message below that number of characters.

The project also has a web page where you can specify the message to send (Figure 5-11).

Figure 5-11. Figure 5-11. Sending Morse from a Webpage

For added fun the project will also gain a buzzer so that the Morse is both flashed and beeped.

Parts

To build this project, you are going to need the following parts in addition to your Photon/Core.

Part

Description

Appendix A code

LED1

Red or any other color LED

C2

R1

220Ω resistor

C1

R2

1kΩ resistor

C5

S1

Piezo buzzer

C4

Male-to-male jumper wires

H4

Half-sized breadboard

H5

Table 5-2. Parts Bin

These components are all included in the Maker’s Kit and apart from the buzzer are the same as for Project 4.

Software

Most of the code here is our now standard Morse sending code. You can find the full program to flash onto your device under the file name P_08_Morse_Function in the PHOTON_BOOK library in the Web IDE.

The first difference between this and our earlier Morse programs is the addition of a new pin for the buzzer.

int buzzerPin = D1;

Because sending a Morse message can take a while, it would be better if the handler for the Function to send a Morse message would return immediately with a status number of 1 or -1 rather than wait for the entire message to be sent. That way, the web page from which the message is sent could provide confirmation that the Morse code was sending on the Photon/Core. To allow this to happen there needs to be a new Boolean value that we can set to true to indicate that flashing should start.

boolean flashing = false;

The setup function now needs an extra line to initialize this pin as an output. The setup function also contains the line to define the Spark Function that will be invoked whenever the Photon/Core receives a Function command to send a message. This will call the function startFlashing.

void setup() {

pinMode(ledPin, OUTPUT);

pinMode(buzzerPin, OUTPUT);

Spark.function("morse", startFlashing);

}

The loop function will be responsible for doing the flashing, but only if the flashing variable is set to true.

void loop() {

if (flashing) {

flashMessage(message);

flashing = false;

}

}

The startFlashing function handles the Spark Function called flash. The startFlashing function does not actually do the flashing, instead it first checks that the length is less than or equal to the maximum allowed parameter size of 64 characters. If its not too long, the flashing variable is set to true, so that the main loop can start flashing (and buzzing) the message. If all is good, 1 is returned, otherwise -1 is returned to indicate an error.

int startFlashing(String param) {

if (message.length() <= 64) {

message = param;

flashing = true;

return 1;

}

else {

return -1; // message too long

}

}

The only other change to the code is in the flash function that must now buzz at the same time.

void flash(int duration) {

digitalWrite(ledPin, HIGH);

tone(buzzerPin, 1000);

delay(duration);

noTone(buzzerPin);

digitalWrite(ledPin, LOW);

}

Buzzing is accomplished using the tone and noTone commands. These commands can only be used on the pins D0, D1, A0, A1, A4, A5, A6, A7, RX and TX.

The function tone takes two parameters, the pin to play a tone on and the frequency of that tone in Hertz (cycles per second). Once started using tone, the pin will continue to oscillate until the noTone command, with a parameter of that pin, is called.

Flash the program onto your Photon or Core so that the app is installed before you start attaching hardware to it.

You saw the webpage for controlling the Morse sender in Figure 5-11. The code for this is listed below. This can be found with the book downloads in the “html” section of the repository. The file is called p_08_morse_function.html.

<html>

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

<script>

var accessToken = "cb8b348000e9d0ea9e354990bbd39ccbfb57b30e";

var deviceID = "54ff72066672524860351167"

var url = "https://api.spark.io/v1/devices/" + deviceID + "/morse";

function callback(data, status){

if (data.return_value == 1) {

alert("Your Message is being sent");

}

else

{

alert("Could not Connect to Photon");

}

}

function sendMorse(){

message = $("#message").val();

$.post(url, {params: message, access_token: accessToken},

callback);

}

</script>

</head>

<body>

<h1>Morse Code Sender</h1>

<input id="message" value="Hello World" size="64"/>

<input type="button" value="Send" onclick="sendMorse()" /> <br/>

</body>

</html>

The webpage code follows much the same pattern as the previous examples. The url is constructed using the accessToken and deviceID variables that must be changed to match those of your account and device.

In this example, the callback function does not need to be nested within the sendMorse function as it does not need access to any of its variables or parameters. The callback function pops up an alert dialog to indicate success or failure.

The sendMorse function first extracts the message to be sent from the field on the webpage with the id of message and then supplies this as the parameter to the HTTP request that will trigger the morse Function on the Photon/Core.

Hardware

Figure 5-12 shows the breadboard layout for the project.

Figure 5-12. Figure 5-12. Breadboard Layout for Morse with Buzzer

You can tell the 220Ω and 1kΩ resistors apart because the 220Ω resistor has stripes that are red, red, brown and the 1kΩ resistor brown, black, red. The buzzer can be placed either way around, but remember that the LED must have the longer positive lead on the same row as the resistor R1.

When the breadboard is fully assembled, power up the Photon/Core, its time to try out the project.

Using the Project

Open the webpage for this project in your browser and enter a message into the text field and press the send button. After a few moments, the Morse code message that you typed will start to be sounded by the buzzer, while at the same time flashed by the LED. Remember that the maximum message length is 64 characters.

Spark Variables

So far, all of our Internet of Things projects have been about telling the Photon/Core to do something using Functions. Being able to read information from the Photon/Core is just as important. Projects 9 and 10 are both concerned with using sensors with a Photon over the Internet.

To fetch information from a Photon/Core you need to use Spark Variables. Defining variables in your app allow you to send requests to your Photon/Core that will bring back a value. Rather like Functions, Spark Variables can easily be confused with regular C variables, so I will use an uppercase V when referring to Spark Variables.

Variables have other similarities with Functions. They have an identifier which is a short string used to identify the Variable, so that you know what to ask for in a web request. They are also defined in the setup function, but rather than being associated with a C function, they are associated with a C variable, whose value they will report. It is the job of your app to keep updating the values in the C variable, so that when a request comes in for a Variable, the value returned is up to date.

In the next project you will see how this works, in a simple example, but first you need to learn a little about how you can connect sensors to a Photon/Core and take readings from them.

Analog Inputs

You will find six pins down the left hand side of the Photon labelled A0 to A5. The Core actually has two extra analog inputs A6 and A7. Although these pins can be used as digital inputs or outputs just like D0 to D7, the A pins are capable of analog input.

Whereas a digital input can only tell if something is on or off, an analog input can measure the voltage at a pin as a number between 0 and 4095, where a reading of 0 indicates 0V and 4095 means 3.3V.

Maximum Voltage of 3.3V

Do not be tempted to attach an analog input to a voltage higher than 3.3V. This is likely to damage your Photon.

If a sensor whose output voltage varies somewhere in the range 0 to 3.3V, you can connect it to one of the analog pins and read the voltage and therefore work out a value for the property that the sensor is measuring.

As an example of this, load up the file “ch_05_analog_ins” from the PHOTON_BOOK example library. This is listed below:

int reading = 0;

int analogPin = A0;

void setup() {

Spark.variable("analog", &reading, INT);

}

void loop() {

reading = analogRead(analogPin);

}

Here the program starts with a C variable (reading). This will be the C variable whose value will be returned when a web request Function is sent to the Photon/Core. The other variable (analogPin) just identifies the analog pin to use, in this case, A0.

The link between the C variable and the Spark Variable takes place in the setup function. The first parameter (“analog”) is the name given to the Variable and the second parameter (&reading) identifies the C variable that the analog Variable is to use. The & symbol is a C language feature that indicates the memory address of a variable. If the second parameter were just reading rather than &reading, then the value of reading would just be substituted into that parameter and since reading is 0 at the time, the Variable values would never change. Using & allows the Photon/Core’s firmware to defer fetching the value of the variable until it needs it for the Variable.

Flash the program onto your Photon/Core. To test it, you can just use a web browser, because unlike Functions, Variables use HTTP “get” requests, which you can issue simply by entering a URL into the address bar of your browser. So, open a browser window and enter the URL below into it.

https://api.spark.io/v1/devices/<DEVICE ID>/analog?access_token=<ACCESS TOKEN>

Remember to substitute your device ID and access token into the URL. The result from the web page will look like Figure 5-13.

Figure 5-13. Figure 5-13. Requesting a Variable using the Browser

Refresh the page a few times and you should see the value of “result” change a little each time. This is not really surprising as the analog does not have anything connected to it, it is said to be “floating.”

Using a male to male jumper wire, connect A0 first to GND (Figure 5-14a) and then to 3.3V (Figure 5-14b), and each time refresh the web page. You should find that with A0 connected to GND you will get a result of 0 and with it connected to 3.3V something close to 4095.

Figure 5-14. Figure 5-14a. Connecting A0 to GND

Figure 5-15. Figure 5-14b. Connecting A0 to 3.3V

In project 9, we will use a photoresistor as a light sensor, whose value can be retrieved using a Variable web request.

Project 9. Measuring Light over the Internet

In this project, you will use a photoresistor to measure light intensity and display a graphical representation of the light level on a web page, as the voltage at pin A0 (Figure 5-15).

Figure 5-16. Figure 5-15. Displaying the Voltage at A0

Parts

To build this project, you are going to need the following parts in addition to your Photon or Core.

Part

Description

Appendix A code

R1

Photo resistor (1kΩ)

C6

R2

1kΩ resistor

C5

Male-to-male jumper wires

H4

Half-sized breadboard

H5

Table 5-3. Parts Bin

These components may be included in the Maker’s Kit.

Software

The app for this project can be found in the file P_09_Lightmeter within the PHOTON_BOOK library in the Web IDE.

int reading = 0;

double volts = 0.0;

int analogPin = A0;

void setup() {

Spark.variable("analog", &reading, INT);

Spark.variable("volts", &volts, DOUBLE);

}

void loop() {

reading = analogRead(analogPin);

volts = reading * 3.3 / 4096.0;

}

This code is very similar to that of the example in the previous section. However, this version has two Variables, reading and volts. In fact, you can have up to 10 Variables in your app.

The reading Variable is associated with the reading C variable and returns just the same result as the previous example, however, the second Variable (volts) will return the actual voltage at the analog pin. To calculate this voltage, the raw reading is first multiplied by 3.3 and then divided by 4096 (the maximum range of reading).

The fancy graphical display is courtesy of a really handy Javascript plugin called JustGage (http://justgage.com/) The webpage for this can be found in the file p_09_light_meter.html along with the JustGage javascript libraries.

<html>

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

<script src="raphael.2.1.0.min.js"></script>

<script src="justgage.1.0.1.min.js"></script>

<script>

var accessToken = "cb8b348000e9d0ea9e354990bbd39ccbfb57b30e";

var deviceID = "54ff72066672524860351167"

var url = "https://api.spark.io/v1/devices/" + deviceID + "/volts";

function callback(data, status){

if (status == "success") {

volts = parseFloat(data.result);

volts = volts.toFixed(2);

g.refresh(volts);

setTimeout(getReading, 1000);

}

else {

alert("There was a problem");

}

}

function getReading(){

$.get(url, {access_token: accessToken}, callback);

}

</script>

</head>

<body>

<div id="gauge" class="200x160px"></div>

<script>

var g = new JustGage({

id: "gauge",

value: 0,

min: 0,

max: 3.3,

title: "Volts"

});

getReading();

</script>

</body>

</html>

The JustGage library and the Raphael library that it uses are both imported and variable-defined for the accessToken and deviceID. Don’t forget to change these values for your account and device.

Jumping now to the end of the file, the Javascript function getReading is called. This constructs the HTTP request to be sent and attached the callback function to it.

When the request responds, the callback function checks to see if the request was successful and if it was, it retrieves the voltage reading from the result, converting it from a string to a float using the command parseFloat. Because the number may have a lot of digits after the decimal point, the number is truncated to two decimal places using the toFixed function.

The gauge display is updated with the new voltage reading by calling g.refresh, after which another call to getReading is scheduled for one second later using setTimeout.

The gauge control itself requires a div tag with an id of gauge where it should draw itself and a short section of script that initializes it. Here you can change the minimum and maximum values for the gauge as well as the title.

Hardware

Figure 5-16 shows the breadboard layout for project 9. Both the resistor and photoresistor can be connected either way around. They form a voltage divider (see side-bar) that changes the voltage at A0 depending on the quantity of light falling on the photoresistor.

Figure 5-17. Figure 5-16. Breadboard Layout for Project 9

Once you have connected up the breadboard, power up your Photon/Core and the project is ready to use.

PHOTO RESISTORS AND VOLTAGE DIVIDERS

In this project, a fixed value resistor is used with a photoresistor whose resistance varies according to how much light falls on it. They are in an arrangement called a voltage divider (see Figure 5-17).

Figure 5-18. Figure 5-17. Voltage Dividers

If the photoresistor had just the right amount of light falling on it to make its resistance the same as R2 (1kΩ) then the 3.3V would be split equally across the two resistors and the voltage at A0 would be half of 3.3V (1.66V). The lower the resistance of the photoresistor (more light) the less voltage it will grab and therefore the more voltage there will be across R2 and therefore the higher the voltage at A0.

Excessive Data Polling

Repeatedly reading data in this way is called polling. In this case, the web page is requesting a Variable value from a Photon/Core every second. If you imaging tens or hundreds of thousands of Photon users all doing this kind of thing at the same time, the Spark service is going to be hammered pretty hard.

So bursts of polling once a second while you are using it are fine, but the socially responsible thing to do would be to make sure that you close the browser window when you are not using it, or set the polling rate to say once every 10 seconds if it’s going to be running all the time.

Using the Project

Open the webpage p_09_light_meter.html and the window should look like Figure 5-15.

Cover the photoresistor with your hand and you should see the reading fall, hold it up to the light and the meter should swing over to the right.

There are other types of resistive sensor that could be substituted for the photoresistor, including strain gauges, variable resistors (like volume controls) and even some gas detectors.

In the next project, you will use a different type of sensor to provide remote temperature monitoring.

Project 10. Measuring Temperature over the Internet

This project is very similar to the last, but rather than measure light intensity with a photoresistor, it uses a digital temperature sensor chip. The gauge display is perfect for this. Figure 5-18 shows the display in degrees F, but this can easily be changed to degrees C.

Figure 5-19. Figure 5-18. An Internet Thermometer

Parts

To build this project, you are going to need the following parts in addition to your Photon/Core.

Part

Description

Appendix A code

IC1

DS18B20 temperature sensor

C7

R1

4.7kΩ resistor

C9

C1

100nF (0.1uF) capacitor

C8

Male-to-male jumper wires

H4

Half-sized breadboard

H5

Table 5-4. Parts Bin

These components may be included in the Maker’s Kit.

The temperature sensor used is actually a chip enclosed in a water-tight container with a lead attached to it, so you can place the sensor some distance away from the Photon/Core if you want.

Software

The app for this project can be found in the file P_10_Thermometer_Dallas within the PHOTON_BOOK library in the Web IDE. The name Dallas is used, because this common type is made by Dallas Semiconductors.

The program includes two Variables, one that reports the temperature in degrees F and one in degrees C.

#include "OneWire/OneWire.h"

#include "spark-dallas-temperature/spark-dallas-temperature.h"

double tempC = 0.0;

double tempF = 0.0;

int tempSensorPin = D2;

OneWire oneWire(tempSensorPin);

DallasTemperature sensors(&oneWire);

void setup() {

sensors.begin();

Spark.variable("tempc", &tempC, DOUBLE);

Spark.variable("tempf", &tempF, DOUBLE);

}

void loop() {

sensors.requestTemperatures();

tempC = sensors.getTempCByIndex(0);

tempF = tempC * 9.0 / 5.0 + 32.0;

}

The first thing to note about this program is that it uses two libraries, indicated by the #include statements at the top. Libraries are a way of sharing code for anyone to use, and, because interfacing to DS18B20 chip is a little tricky, Tom de Boer has converted an original Arduino library to work with the Photon and Core. This library (spark-dallas-temperature) relies on another library called OneWire to handle the serial communication with the temperature sensor chip.

For your app to work, as well as having the #include commands at the top, you also need to add the libraries to the app. To do this, first click on the Library button in the Web IDE and then type “Dallas” into the search box beneath “Community Libraries” (Figure 5-19).

Figure 5-20. Figure 5-19. Using the DallasTemperature Library in an App

Click on the INCLUDE IN APP button and then scroll down to P_10_THERMOMETER_DALLAS, select it and then click ADD TO THIS APP. Repeat the same process, searching for the library OneWire.

Turning to the code itself, after the variable tempSensorPin has been defined as D2, the definition below is called to start the OneWire serial bus running on that pin.

OneWire oneWire(tempSensorPin);

The next line instructs the DallasTemperature library to use that interface when communicating to temperature sensors. You can actually connect a whole load of temperature sensors to the same pin if you want.

The setup function contains a call to sensors.begin() to start the sensors monitoring the temperature.

The loop function contains the code to actually get hold of a reading. This is a two-stage process. First sensors.requestTemperatures is called that gets readings from all the sensors (even though in this case there is only one). The second step is to access the reading itself usinggetTempCByIndex. The index supplied as a parameter is 0 for the first sensor attached to the Photon/Core. If there was a second DS18B20 attached, it would be index 1 and so on.

The temperature in degrees F is then calculated using a standard formula.

The webpage is almost identical to the light sensor page, but with a few changes to reflect the fact that it is the temperature being displayed. The webpage can be found in the file p_10_thermometer.html.

Hardware

The breadboard layout for the project is shown in Figure 5-20.

Figure 5-21. Figure 5-20. Breadboard Layout for Project 9

The temperature sensor actually has four connectors. One is a connection to the braided screening within the cable. This does not need to be connected. The other wires are red (positive supply), black (GND) and yellow (the data signal). The resistor must be connected between the data signal and positive supply and the capacitor between the positive supply and GND.

Using the Project

To use the project, just upload the app to the Photon/Core and open the webpage p_10_thermometer.html in your browser.

If you want to change the temperature display to be in degrees C rather than F, then open p_10_thermometer.html in an editor and make the following changes:

Change the lines:

var url = "https://api.spark.io/v1/devices/" + deviceID + "/tempf";

to read:

var url = "https://api.spark.io/v1/devices/" + deviceID + "/tempc";

In other words, use the “tempc” Variable in place of the “tempf” Variable.

You also need to change the title of the gauge and its range, so modify the script block at the end of the file to look like this:

<script>

var g = new JustGage({

id: "gauge",

value: 0,

min: 0,

max: 30,

title: "Degrees C"

});

getReading();

</script>

Reload the page in your browser and it should now look like Figure 5-21.

Figure 5-22. Figure 5-21. The Temperature in Centigrade

Summary

In this chapter, you have used analog inputs attached to sensors and digital outputs controlling LEDs and buzzers to make some simple IoT projects. In the next chapter you will learn more about the Internet of Things and how to use the Photon and Core with the popular If This Then That (IFTTT web service).