Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
In this fourth tutorial, you'll modify your "Smart Light" device into a "Smart Security" device and program new apps for the device.
The goals of this fourth tutorial are to help you:
Gain further experience by creating another practice IoT device and programming its apps
Become better prepared to create your own IoT device and apps for your team project
For decades, security systems have been used to monitor homes and businesses for emergencies (burglary, fire, flood, etc.). These systems use some combination of: motion sensors, door/window sensors, glass break sensors, video cameras, smoke detectors, flood sensors, etc. Today, many security systems are being connected to the internet to offer additional features.
You'll create a prototype of a Smart Security device by modifying your Smart Light device (which has an LED light and push button) to add a motion sensor and a speaker:
The LED light will be used to indicate whether the security system is currently "armed" (LED is on) or "disarmed" (LED is off).
The push button will be used to switch the security system between "armed" and "disarmed" mode. (The button will simulate a security system's keypad, which is used to enter a numeric passcode. For this prototype device, you'll simply press the button to toggle the system between modes, as if you had correctly entered a passcode.)
The motion sensor will detect whether something is moving within the surrounding area.
The speaker will be used to produce an alarm sound if motion is detected.
You'll use a copy of your Smart Light device app as starter code for your Smart Security device app. You'll modify the existing code controlling the LED and button before adding new code to control the motion sensor and speaker.
You'll also program a web app that interacts with your Photon over the internet to perform these tasks:
Monitor the security system's current mode ("armed" or "disarmed")
Remotely toggle the security system between "armed" or "disarmed" mode
Receive an event notification if the security system detects motion
View the date and time of the last motion event detected
Next, you'll add code in your Smart Security device app to control the motion sensor.
The basic steps to use a motion sensor in your app code are:
Declare a global variable to store the I/O pin number for the motion sensor.
Set the pin mode for the motion sensor pin in the setup()
function.
Use a digitalRead()
statement to check whether the sensor detects any motion, and add code statements that should be performed if motion is detected (or not detected).
Declare a global variable to store the I/O pin number for the motion sensor by adding this code statement before the setup()
function:
If you connected your motion sensor to a different I/O pin other than D3
, then modify this code statement to list the correct pin number for your motion sensor.
Set the pin mode for your motion sensor pin by adding this code statement within the setup()
function (between the curly braces):
The digitalRead()
method is used to check whether the sensor currently detects any motion.
The digitalRead()
method will return a value of either HIGH
or LOW
(which are treated as if they were int
values):
HIGH
indicates that motion is NOT currently detected.
LOW
indicates that motion is currently detected.
A variable named motionState
will store the value returned by the digitalRead()
method.
An if statement will be used to perform a set of actions if motion is detected (if motionState
has a value equivalent to LOW
).
You'll add a custom function named checkMotion()
that will contain all this code.
Add this checkMotion()
custom function after the loop()
function (you can add it before or after the toggleMode()
function):
Inside the if
statement, you'll need to add code to do something if motion is detected. In the next step of this tutorial, you'll add code here to make an "alarm sound" using the speaker. Later, you'll also add code to send an event notification to the web app that you'll be creating.
You'll notice that a delay()
of 2 seconds is performed when motion is detected. This delay is needed to allow the sensor to capture a new "snapshot" of the environment before checking the sensor again.
The checkMotion()
function will only be performed if it is called within another function, such as the loop()
function. However, the motion sensor should only be checked if the device's mode is currently set to "armed"
.
Add this code within the loop()
function (after the closing curly brace of the existing if
statement that checks the value of buttonState
):
This code will only call the checkMotion()
function if the value of deviceMode
is equivalent to "armed"
.
Save your smart-security
app code by clicking the Save icon in the left navigation bar.
Your Photon kit includes a small speaker that can produce tones or play simple music (note by note).
In this step, your team will connect the speaker to your Photon circuit board using the breadboard.
You'll need these components:
Speaker
2 jumper wires (use different colors to help identify them)
. The speaker can be connected to any I/O pin capable of PWM, but connect it to the D1 pin (which will be different from the wiring diagram).
Next, you'll add code in your Smart Security device app to control the speaker.
The basic steps to control a speaker in your app code are:
Declare a global variable to store the I/O pin number for the speaker.
Set the pin mode for the speaker pin in the setup()
function.
Use tone()
statements to produce sounds.
Declare a global variable to store the I/O pin number for the speaker by adding this code statement before the setup()
function:
If you connected your speaker to a different I/O pin other than D1
, then modify this code statement to list the correct pin number for your speaker.
Set the pin mode for your speaker pin by adding this code statement within the setup()
function (between the curly braces):
The speaker will be used to produce an "alarm sound" if the motion sensor detects motion.
The tone()
method is used to produce a sound of a specific frequency (pitch) for a specific duration of time. The speaker can produce tones ranging in frequency from 20Hz (very low pitch) to 20KHz (very high pitch), covering the full range of sounds that humans can hear.
Add this code statement within your checkMotion()
custom function (inside the curly braces of the if
statement that checks the value of motionState
– add the code before the delay()
):
The tone()
method requires three parameters inside its parentheses (in this order):
The I/O pin number, which can be the actual pin number (such as: D1
, etc.) or a variable that stores a pin number. In this case, the variable named speaker
is listed.
The frequency for the tone, which can be an integer value (whole number) or a variable that stores an integer. The value can be between 20-20000 hertz. Lower numbers will have a lower pitch, while higher numbers will have a higher pitch. In this case, the frequency will be 1000
hertz, which will be a "less annoying" pitch than what an alarm sound would typically use.
The duration for the tone, which can be an integer number (whole number) or a variable that stores an integer. The value represents the number of milliseconds that the tone will be played (1000 ms = 1 second). In this case, the duration will be 250
ms (0.25 seconds), which will be a much shorter duration than what an alarm sound would typically use.
Be sure your Photon device is connected to Wi-Fi and Particle Cloud.
Flash your app code to your Photon device by clicking the Flash icon in the left navigation bar. (Particle Build will first save and verify your code before flashing it.)
Once your Photon has downloaded the new app and restarted, the updated app will start running:
Press the button to "arm" your Smart Security device. (This simulates having entered a passcode into a keypad to arm the device.) The LED light should turn on when the device is in "armed" mode. Confirm that the speaker produces an alarm sound when motion is detected. The sensor should be able to detect motion in the environment up to 10 feet away.
Press the button again to "disarm" the device (the LED should turn off). Because of the 2 second delay required when motion is detected, you may have to press the button more than once (or hold the button down slightly longer). Once the device is in "disarmed" mode, confirm that motion near the sensor does not produce an alarm sound.
NEED LED & BUTTON: Be sure the LED and button from your Smart Light device are still connected. If not, to the D0 pin and to the D2 pin.
Your Photon kit includes a motion sensor that uses passive infrared (PIR) light to detect movement in the surrounding environment up to 10 feet away.
In this step, your team will connect the motion sensor to your Photon circuit board using the breadboard.
You'll need these components:
Motion sensor (with 3-pin connector)
3 jumper wires (use different colors to help identify them; it may help to match the sensor wires)
. The sensor can be connected to almost any I/O pin, but connect it to the D3 pin (which will be different from the wiring diagram).
5V REQUIRED: The motion sensor requires 5V of power to operate, so the sensor's red wire must be connected to the VIN pin or V-USB pin, depending on your Photon's power source.
If your Photon is being powered through the barrel jack, connect to the VIN pin.
If your Photon is being powered through the Micro-USB port, connect to the V-USB pin.
Next, you'll modify your Smart Security device app to allow a web app to interact with your Photon through the internet.
Remember that all your Photon's internet communications are routed through Particle Cloud, which provides these ways for your web app to interact with your Photon device:
A web app can get the value of a Photon device variable
A web app can call a custom function on a Photon device
A web app can get event notifications from a Photon device
The web app that you'll be creating for your Smart Security device will perform these tasks:
The web app will display whether the security device is currently armed or disarmed. The web app will do this by getting the value of the deviceMode
variable in your Photon device app.
The web app will display a toggle switch that can be clicked to remotely toggle the security device between armed and disarmed mode. The web app will do this by calling the toggleMode()
function in your Photon device app.
The web app will display a notification if the security device detects motion while the device is armed. The web app will also display the date and time when a motion event was last detected. The web app will do this by receiving event notifications sent from your Photon device app.
You'll need to add some code to your Photon device app to allow it to interact with your web app.
Your Photon app should have existing code statements from your Smart Light app which you modified that will share the deviceMode
variable and toggleMode()
function through Particle Cloud.
Be sure the following code statements are already listed within the setup()
function (do not add this code again if it already exists):
Your Photon device app can send an event notification using theParticle.publish()
method. This will create a "cloud event" in Particle Cloud that will stream the event notification to your web app.
By default, Particle Cloud will clear each cloud event after 60 seconds to prevent your web app from receiving outdated notifications.
An event notification can be sent with or without data:
An event notification sent without data acts like a simple alert that the event occurred.
An event notification sent with data will include additional information as a text string (up to 255 characters).
Particle Cloud will allow your Photon device to send about 1 event notification per second. If your device sends event notifications more frequently than this, Particle Cloud will intentionally slow down your event stream (with a 4-second delay), which can cause issues with your web app performance.
To prevent this, include a delay()
of at least 1 second after a Particle.publish()
statement (because a 1-second delay added by you is better than a 4-second delay added by Particle Cloud).
For your Smart Security device, your Photon app should send an event notification (without additional data) whenever the motion sensor detects motion.
Send an event notification through Particle Cloud by adding this code statement within your checkMotion()
custom function (after the tone()
statement but before the delay()
statement):
The Particle.publish()
method requires a parameter for the cloud event name, which can be up to 63 characters in length. The name must be listed within double quotation marks. In this case, "motion"
will be the name of the cloud event.
Since your code already has a delay()
statement on the next line for the motion sensor, this existing delay()
will also prevent your Photon app from sending event notifications too frequently.
Flash your app code to your Photon device by clicking the Flash icon in the left navigation bar.
Once your Photon has downloaded the app and restarted, the updated app will start running. You shouldn't notice any changes in the device's behavior, but your Photon app will now send a "motion"
event notification to Particle Cloud every time motion is detected while the device is armed.
Next, you'll use your Smart Light device app as starter code for your Smart Security device app. The LED and button code in the two apps will be nearly identical – you'll just make a few minor changes. After that, you'll be ready to start adding new code for the motion sensor and speaker.
One person on your team should log in to using your team's Particle account login.
Once you're logged in, you should see a new app template in the code editor. (If not, just click the "Create New App" button in the Code menu panel.)
Enter smart-security
as your app's title.
You'll use your smart-light
app as starter code for your smart-security
app:
The Code menu panel lists all your saved apps under "My apps." Click on your smart-light
app to load its code into the code editor panel. (If the Code menu panel is not visible, just click the Code icon in the left navigation bar to show the Code menu panel.)
In the code editor panel, select all the existing code in your smart-light
app, and copy it.
In the Code menu panel, click on your smart-security
app listed under "My apps" to load it into the code editor panel. (If the Code menu panel is not visible, just click the Code icon in the left navigation bar to show the Code menu panel.)
Select all the existing code in your smart-security
app, and then replace it by pasting in the copied code from your other app.
Save your smart-security
app code by clicking the Save icon in the left navigation bar.
The LED and button code in the Photon app will remain essentially the same. You'll just make some minor changes to the lightStatus
variable and toggleLight()
function:
Change the name of lightStatus
to deviceMode
. There should be 6 places in the code where this change needs to be made.
The possible values for lightStatus
were "off"
or "on"
. Find the 3 places in the code where "off"
is listed, and change each one to "disarmed"
instead. There is 1 place in the code where "on"
needs to be changed to "armed"
instead.
Change the name of toggleLight
to toggleMode
. There should be 4 places in the code where this change needs to be made.
In the comments at the top of the code, change Smart Light Device
to Smart Security Device
.
These modifications do not change how the code functions – it just makes the code make more sense when you read it, since this app will control a Smart Security device (instead of a Smart Light).
Be sure your Photon device is connected to Wi-Fi and Particle Cloud.
Flash your app code to your Photon device by clicking the Flash icon in the left navigation bar. (Particle Build will first save and verify your code before flashing it to your device.)
Once your Photon has downloaded the new app and restarted, the updated app will start running:
Confirm that the device still functions like the Smart Light did: the LED light should toggle between on and off each time the button is pressed. When the LED is turned on, it indicates the security system is in "armed" mode. When the LED is turned off, the security system is "disarmed."
In the next steps, you'll add code for the motion sensor and speaker to made the security system fully functional when it's "armed."
Next, you'll create a web app that will interact with your Smart Security device through Particle Cloud.
Your web app will consist of an HTML file namedindex.html
, a CSS file named style.css
, and a JavaScript file named script.js
.
Remember that Particle Build is only used to code your Photon device app. You'll need to use a different code editor to create the HTML, CSS, and JS files for your web app. Consult your teacher to determine which code editor will be most appropriate to use for your web app files.
, and paste it into a blank HTML file named index.html
.
The starter HTML contains blank lines where you'll add custom HTML for your specific web app.
Copy this HTML, and paste it into the blank lines within the <body>
of your starter HTML code:
COPY CODE: When using this IoT code guidebook, you can copy a code block simply by clicking the copy icon displayed in the upper right of the code block.
If you preview the web app at this point, it's very plain (because there's no CSS in the style.css
file) and it doesn't function yet (because there's no JS in the code.js
file).
Next, you'll add the CSS for your web app's stylesheet.
, and paste it into a blank CSS file named style.css
.
Copy this CSS, and add it after your starter CSS:
Your CSS should now have style declarations for several HTML elements:
The CSS for body
styles the <body>
section of your HTML.
The CSS for .card
styles elements in your HTML that have class="card"
. There are 2 <div>
elements that have this class. The first <div>
will be a "card" displaying information about your security system (current mode, toggle switch for mode, and time of last motion event). The second <div>
will be a "card" displaying a pop-up notification when motion is detected.
The CSS for #motion-alert
styles elements in your HTML that have id="motion-alert"
. The second <div>
has this id name and will be hidden (display: none
). When a motion event notification is received, your web app JS will use jQuery to briefly show this "card" and then hide it.
The rest of the CSS (for .switch
, .slider
, and input
) changes the checkbox input in your HTML to look and act like a toggle switch.
If you preview the web app at this point, you can see how the CSS has changed the appearance of the web app, but it still doesn't function yet (because there's still no JS in the code.js
file).
If you click your toggle switch, it will change appearance using CSS (but it requires JS to fully function).
Next, you'll add JavaScript code to allow your web app to interact with your Photon device through Particle Cloud. Remember that the web app will perform these tasks:
The web app will display whether the security device is currently armed or disarmed. The web app will do this by getting the value of the deviceMode
variable in your Photon device app.
The web app will display a toggle switch that can be clicked to remotely toggle the security device between armed and disarmed mode. The web app will do this by calling the toggleMode()
function in your Photon device app.
The web app will display a notification if the security device detects motion while the device is armed. The web app will do this by receiving event notifications sent from your Photon device app.
Copy this starter JS for your web app, and paste it into a blank JS file named script.js
.
IMPORTANT: You must modify this JS code to insert your actual Photon device ID and access token. Otherwise, your web app will not work properly.
Copy this JS, and paste it after your modified starter JS:
This custom JS does 5 main things:
Stores an audio file in a JS global variable named alertSound
Sets a time interval to call a JS function named checkMode()
Adds a JS function named checkMode()
that will get the value of a Photon variable
Adds a JS function named toggleMode()
that will call a Photon function
Starts listening for "motion"
event notifications sent by your Photon device
A variable named alertSound
is declared that stores an audio file named "notification.wav"
. Download a copy of this audio file, and place it in the same folder as your web app files.
The window.setInterval()
method will automatically call the function named checkMode()
every 500
ms (0.5 seconds).
The function named checkMode()
contains a call to the particle.getVariable()
method that will get the current value of the "deviceMode"
variable in your Photon app.
Inside the particle.getVariable()
method are JS and jQuery code statements (lines 8-15 above) that were added to perform actions based on the value returned for the Photon variable.
An if-else statement is used to determine whether data.body.result
has a value equivalent to "armed"
or "disarmed"
. Then jQuery statements (which start with $
) are used to dynamically change the information displayed in the first "card" by targeting specific id selectors:
$("#system-mode")
targets the HTML element with id="system-mode"
. The jQuery statements change this element's HTML to display either ARMED
or DISARMED
.
$("input [name=toggle])
targets the <input>
element with name="toggle"
. The jQuery statements change its "checked"
property to either true
(checked) or false
(unchecked), which changes the toggle switch slider position.
Since the window.setInterval()
method will keep calling this function every 0.5 seconds, your web app will continuously monitor the current mode of your Smart Security device.
The function named toggleMode()
contains a call to the particle.callFunction()
method that will call the "toggleMode"
function in your Photon app to remotely switch your device's mode between "armed" and "disarmed".
The <input type="checkbox">
in your web app HTML contains an onclick event attribute that will call this toggleMode()
function whenever the toggle switch in the web app is clicked.
The particle.getEventStream()
method is used to start listening for event notifications sent from your Photon app.
The particle.getEventStream()
method requires your Photon device ID, the name of your cloud event, and your Photon access token:
myDevice
is the global variable that stores your Photon device ID
"motion"
is the name of the cloud event that you want to receive notifications from
myToken
is the global variable that stores your Photon access token
If an event notification includes any data, this text string data gets temporarily stored in a local variable called: feed.data
Code statements added within the particle.getVariable()
method will be performed whenever an event notification is received.
In this case, JS and jQuery code statements (lines 29-33 above) were added that will perform these actions each time a new event notification is received:
Play the alertSound
Get the current date and time and store it in a variable named dateTime
Display the value of dateTime
in the HTML element with id="event-time"
Show the HTML element with id="motion-alert"
, wait for 1500
ms (1.5 seconds), and then fade out the element until it is hidden. This creates a visible "pop-up" notification in your web app.
NOTE: Since your Photon app is sending the "motion"
event notification without data, there aren't any JS or jQuery code statements using feed.data
(because no text string is being received).
Be sure your Photon device is connected to Wi-Fi and Particle Cloud.
Refresh your web app, and test it with your Photon device to make sure they interact correctly:
Verify that your web app displays the current mode ("armed" or "disarmed") of your Smart Security device. Use the push button connected to your Photon device to change the device mode. When the LED is turned on, the device is in "armed" mode. When the LED is turned off, the device is "disarmed." Verify that your web app updates automatically to show the correct device mode.
Verify that your web app can remotely change the device mode. Click the toggle switch in your web app, and verify that your Photon device automatically toggles modes (by checking the LED). It may take up to 2 seconds for the mode to switch due to the delay(2000)
in the Photon app.
While your Smart Security device is in "armed" mode, wave your hand over the motion sensor to trigger a motion event. Verify that your web app displays a motion notification pop-up (which will fade out after 1.5 seconds). Verify the web app displays the correct date and time for the last motion event notification.
If you have time and want to experiment with the other inputs and outputs in your Photon kit, you could explore the SparkFun Photon Experiment Guide. (You can skip ahead to Experiment 3 or later.)
There are also references in this guidebook that show and explain how to connect and code each of the physical inputs and physical outputs included in your Photon kit.
Your team should now be ready to start thinking of possible ideas for your IoT project challenge.