Maker.io main logo

piot 101 Raspberry Pi + Internet of Things

2017-05-17 | By Initial State Technologies

License: See Original Project Wireless Raspberry Pi

Courtesy of Initial State

Introduction to the Workshop

The Raspberry Pi is a low cost, credit-card sized computer that can be used to build amazing things. The Internet of Things (IoT) is the exploding network of objects, sensors, and "things" connected to the internet. This hands-on workshop will teach you the basics of using a Raspberry Pi and how to use a Pi to create an Internet of Things application.

Why is this important? The Internet of Things is predicted by Cisco to blossom into a multi-trillion dollar opportunity. Gartner Research believes that 50% of this opportunity will be realized by Makers and young startup companies (http://www.gartner.com/newsroom/id/2869521). Raspberry Pi has quickly become the device of choice for millions of Makers around the world due to its ease-of-use, features, and cost. This workshop will take you from Novice to IoT Maker in two hours.

In this workshop, you will:

  • learn the fundamentals of using a Raspberry Pi (booting up your Pi, using the Linux command prompt, remotely logging into your Pi, etc.)
  • wire up simple circuits using a breadboard (no previous experience required)
  • write and run simple Python scripts that will run on a Pi (no previous experience required)
  • build multiple live Internet of Things projects that stream data to a cloud service
  • build a real-time dashboard that displays all of your sensor data in one place

If you get stuck, send us an email at piot@initialstate.com, and we will be happy to help.

Part 1. Unboxing & Setup

Unboxing and Setup

Equipment

Here is a list of all the equipment that we'll be using in this workshop with links to where you can purchase each piece. The LCD + cables are optional if you already have a display that you want to use. The keyboard+mouse is also optional if you already have one to use.

Unboxing to Power On

Step 1: Insert into Case

Never touch an exposed circuit board without being properly grounded. Place the Raspberry Pi inside the clear plastic CanaKit case. This will protect the Raspberry Pi from electrostatic discharge (ESD). Here's a video of someone putting together a similar case to the one in your kit: www.canakit.com/pi-case

Step 2: Insert microSD card

The Raspberry Pi will boot from the operating system (o/s) installed on the MicroSD card. The CanaKit Ultimate Starter Kit includes a MicroSD card pre-loaded with the operating system that we will use, Raspbian. Raspbian is a version of Linux optimized for Raspberry Pi. Insert the MicroSD card into the Raspberry Pi.

Raspberry Pi and MicroSD Card

Raspberry Pi and MicroSD Card

Step 3: Plug In Keyboard + Mouse

Plug in the wireless keyboard/mouse USB receiver into one of the Pi’s USB ports. The Pi should auto-detect the keyboard/mouse when the Pi boots up.

Step 4: Connect Power For LCD

Connect the small end of the MicroUSB cable into the 5” LCD. Connect the large end of the MicroUSB cable into one of the Pi’s USB ports. This will power the LCD from the Pi. (*Note, do not plug the USB WiFi adapter yet as the LCD will not receive enough power from the Pi to turn on until Step 14.)

Step 5: Connect HDMI

Connect the HDMI cable between the 5” LCD and the Pi.

Step 6: Connect to Network

Connect the network cable to the Ethernet port of the Pi (if you are using a wired ethernet connection). If you are going to use the USB WiFi adapter, do not plug it in until Step 14 or the LCD will not turn on.

Step 7: Power On

Plug in the MicroUSB power supply into the Pi to turn it on.

Connecting the Power Supply

Initial Setup

Select Raspbian

Step 8: Select Raspbian

The first screen you will see when the Pi first turns boots up from the CanaKit MicroSD card will prompt you to select which operating system to install. Select Raspbian (RECOMMENDED) from the top of the list. This will begin a 10-15 minute installation of Raspbian.

Step 9: Set Keyboard Layout

At the bottom of the installation progress screen, you can select the language and keyboard layout. Choose English (USA) for the language and US for the keyboard. If you leave this setting at its default, English (UK), you will find several keys on the keyboard switched (such as the @ and “ keys). If you forget to change the keyboard layout, (http://blog.initialstate.com/messed- up-rpi-keyboard/) for instructions on how to correct this later.

Installation

Step 10: Starting the GUI

Once your Pi has completed the Raspbian installation, it will boot to a command prompt. By default, the administrator username is pi and the password is raspberry. If prompted, enter the username/password. Once at a command prompt, type startx and hit enter to start the GUI.

Start the GUI

LCD Setup

Step 11: Configure Resolution

You may have noticed that the GUI is not stretched across the full width of the LCD. This is because you have to manually specify the resolution of this LCD to your Pi. To do this, you will need to modify a configuration file, /boot/config.txt. The simple command line editor that will be used throughout this workshop is a program called nano.

At a command prompt, type sudo nano /boot/config.txt and hit enter. The “sudo” part of the command allows you to run commands as a “super user” with administrator privileges. This is a requirement for modifying the /boot/config.txt file. The “nano” part of the command starts the nano program to modify /boot/config.txt.

Use the arrow keys to navigate the blinking cursor to desired location. Make the following modifications/additions to the file:

Copy Code
# uncomment if hdmi display is not detected and composite is being output
hdmi_force_hotplug=1

# uncomment to force a specific HDMI mode (here we are forcing 800x480!)
hdmi_group=2
hdmi_mode=1
hdmi_mode=87
hdmi_cvt 800 480 60 6 0 0 0

 Once complete, hit CTRL + x, then y, then enter to save the file. If you made a mistake and do not want to save your changes, hit CTRL + x, then n, then enter to exit without saving your changes.

Step 12: Increase USB Power

Since we are going to power the LCD from the USB port of the Pi, we need to make another change to our /boot/config.txt file to provide enough power to drive the LCD, the wireless keyboard/mouse receiver, and a WiFi adapter (or other peripheral). Type sudo nano /boot/config.txt and hit enter. Add the following line to the bottom of this file:

Copy Code
max_usb_current=1

 Save your changes (CTRL + x, y, then enter).

Step 13: Reboot

Setup is almost complete. We simply need to reboot our Pi to ensure the LCD setup changes worked. At a command prompt, type sudo reboot and hit enter. Shutting down or rebooting your Pi requires the ‘sudo’ privilege prefix. Once reboot completes, your LCD should be full screen when you go into the GUI (startx).

Step 14 (optional): WiFi Setup

If you are going to use a WiFi adapter instead of a wired Ethernet connection, plug the adapter into an available USB port. Start the GUI (startx) and launch the WiFi config under Menu -> Preferences to go through the WiFi setup.

Part 2. Hello World

Overview The Pi can do so many amazing things, too many to cover in a single workshop. We are going to focus on using our Pi to build an Internet of Things (IoT) application. This means we will want to be able to remotely access our Pi from our laptop through its Internet connection to modify code and execute programs. Let’s get familiar with the command prompt and a command-line friendly text editor to write our first Python script to run on our Pi. If you are already familiar with using a Linux command prompt, SSH, and running a basic Python script, feel free to fast-forward to Section 3 where things will get much more interesting for you.

SSH

Pi IP Address

In order to remotely log into your Pi from your laptop, you will need your Pi’s IP address.

Step 1: Get IP Address of Pi

Go to your Pi’s command prompt by clicking on the LXTerminal icon at the top toolbar. Enter the command:

Copy Code
$ hostname -I

 

Bash Beginner Tip: The $ sign in the command above denotes the start of a bash command, you don't actually type this when typing in bash. In fact, if you look at your raspberry pi's terminal or your other machine's terminal, you'll see the dollar sign is already to the left of the cursor. If you ever see a # instead of a dollar sign before the bash command, it means that the current bash context has elevated, super user privileges, similar to prefixing each command with sudo.

The IP address will be returned to the screen. Write your IP address down for use throughout this workshop. In the screenshot above, the Pi’s IP address is 10.1.101.91.

Step 2: Setup SSH

We will be using the ssh protocol to communicate with our Pi over the local network.

SSH stands for Secure Shell and allows us to remotely log into our Pi and run commands.

If you're on Linux of Mac, the ssh tool comes standard. If you're on Windows, you'll need a client. We recommend PuTTY which can be downloaded from putty.org.

As of the Nov, 2016 release of Raspbian, SSH is disabled by default on your Raspberry Pi. To enable SSH, follow the instructions at https://www.raspberrypi.org/documentation/remote-access/ssh/

Step 3: (Linux/Mac) SSH

Step 1: Open a Terminal

On your laptop, open up your favorite terminal (if you don't have a favorite, just use the built in Terminal app).

Step 2: SSH

Enter the command (replace <ip_address> with the IP address of the pi):

Copy Code
$ ssh pi@<ip_address> 

This will attempt to connect to your Pi using the specified IP address and login with the username ‘pi’.

Step 3: Accept fingerprint

The first time you login to your Pi, you will receive a message similar to the following: 

Copy Code
$ ssh pi@10.1.101.91
The authenticity of host '10.1.101.91 (10.1.101.91)'
can't be established. RSA key fingerprint is
b2:03:15:12:71:f2:6c:5c:2e:82:69:cc:5c:e8:81:54. Are
you sure you want to continue connecting (yes/no)?

Enter yes, then enter your password.

The default password is raspberry for a new Pi. The default admin username is pi

After you get here, you can skip to After connecting.

Step 3: (Windows) SSH with PuTTY

Step 1: Install PuTTY

If you do not have PuTTY or a similar tty application for Windows, you'll need to install it from http://www.putty.org/

Step 2: Configure PuTTY session

Start the putty.exe and in the "Host Name (or IP address)" we'll put the Pi's IP address. Leave the "Port" set to 22 (this is the default port for the SSH protocol). After configuring, click "Open".

PuTTY Configuration

Step 3: Accept fingerprint

If this is your first time connecting to the Pi from your computer, you'll see a Security Alert similar to the following asking you to verify and accept the Pi's RSA fingerprint. Click "Yes".

PuTTY Security Alert

Step 4: Successful SSH

After connecting, you should see a terminal-like window similar to the following

Pi Terminal

Step 4: After connecting

If successful, you will see something similar to the following on your screen:

Copy Code
Linux raspberrypi 3.18.5-v7+ #225 SMP PREEMPT Fri Jan 30 18:53:55 GMT 2015 armv7l

The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law.
Last login: Wed Feb 25 22:24:20 2015 from 10.0.0.41
pi@raspberrypi ~ $

This means that you are now remotely connected to your Pi and ready to tell it what to do.

TIP: The IP address of your Pi can change based on your router’s settings. If you try to SSH into your Pi and fail to get a connection, the Pi’s IP address may have changed. There are several ways to get the current IP address of your Pi. The most straightforward method is to hook a keyboard and monitor up to your Pi and run the hostname –I command. Your router may have a built-in web server that you can log into to see the IP addresses of all connected devices.

Python Nano

When you logged into your Pi, you landed in the /home/pi directory. To see a list of subdirectories and files in this directory, enter the command:

Copy Code
$ ls

This will “list” everything in the current directory.

Copy Code
pi@raspberrypi ~ $ ls
Desktop piot python_games streamer

For the Pi that you are using at the workshop, there will be a directory called “piot” listed (if you are starting this workshop at home on a new Pi, you will need to create this directory using the command “git clone https://github.com/InitialState/piot-101.git piot”). We want to navigate into this directory by typing the following:

Copy Code
$ cd piot

cd will “change directory”. You can type cd .. to return to the parent directory that you just came from (if you do, cd back into the piot directory). Type “ls” to see all of the files in this directory. You will notice several files that end in .py. These are the Python scripts that you will be modifying and running throughout this workshop. These scripts are how we will tell the Pi what to do.

Note: Python is a very popular, high-level programming language that is commonly used by the Pi community. The purpose of this workshop is not to teach you Python but to introduce you to Python. If you are interested in learning more about Python, I recommend taking the free, online Python introductory course at http://www.codecademy.com (this is an awesome site for learning the basics of Python and other languages at your own pace).

For this workshop, we need to know how modify and run an existing Python script. Let’s create our first Python script using the simple command-line text editor, nano. Run the following:

Copy Code
$ nano hello.py

Nano will be invaluable for creating and modifying our Python scripts as well as other text files on our Pi. You can navigate up, down, left, and right using the arrow keys. To enter text at the current cursor position, simply start typing. You can easily copy and paste text inside of nano (edit -> copy/paste). This means you can copy text from this guide on your laptop and remotely paste it into a file on your Pi through nano ... quite handy.

Once you have loaded nano, enter the following line of Python code:

Copy Code
print "Hello World!"

Yep, we are creating the cheesy, predictable “Hello World” program as our first Python script. To save your changes, click CTRL+x, then y, then enter. Notice that you are responding to the prompts at the bottom of the screen to save your file.We are now ready to run our first Python script. At the command prompt, type:

Copy Code
$ python hello.py

Note: Just like this workshop is an introduction to Python, it is also just an introduction the using a Linux command line shell. To learn more command line magic, check out http://linuxcommand.org/learning_the_shell.php.

Part 3. Buttons & Lights

Buttons and Lights

Overview

One of the coolest aspects of the Pi is that we can build and attach circuits that it can talk to. We are going to use a breadboard to quickly build circuits that can be controlled from simple Python scripts running on the Pi. We will build a circuit that drives an input into the Pi, a button, as well as a circuit that the Pi drives as an output, a LED. Each circuit will have a simple Python script that we will run to control it.

NOTE: If you are running this tutorial from a fresh install (in other words, you are not physically at a workshop ... if you are then this has already been done for you, and you can skip ahead to the next page), clone all of the Python scripts with the following command:

Copy Code
$ cd ~
$ git clone https://github.com/InitialState/piot-101.git piot

Breadboard Basics

A breadboard allows you to wire up circuits by plugging in components and wires into the holes of the board. Components are connected together by being either on the same column if they are plugged into the outer two columns of the board or by being on the same row if they are plugged into the inner 10 columns of the board included in the Canakit Pi starter kit. The red rectangles above outline rows and columns that are physically connected together.

The breadboard used in this workshop has a breakout board attached to it that a ribbon cable will be plugged into. This connects the input/output (I/O) pins of the Pi to our breadboard with easy-to-read labels. This particular breakout board routes the voltage and ground lines to the outer two columns of the breadboard – a nice convenience.

Tip: Make sure the 40-pin ribbon cable connector is connected in the correct orientation, as in the picture above. The red wire should be closest to the short edge of the pi case.

NOTE: Make sure that your ribbon cable is plugged into your pi on both rows of pins. Otherwise, it won't work properly! If your Canakit came with the black pi case, it is really easy to accidentally miss the front or back row.

NOTE: The Raspberry Pi is a 3.3V (3V3) device, and the breakout board allows you to connect directly to the CPU on the Pi. You should only connect low power 3V3 devices directly to your Pi. Anything else (5V, or more than 48 mA total) could damage your Pi, so be careful what you attach!

Input Button

Connecting the GPIO

Before we build our first circuit, let’s shutdown our Pi to keep it safe.

IMPORTANT: Always build your circuit with the Pi shutdown and the power cord disconnected.

In the command prompt, type:

Copy Code
$ sudo shutdown -h now

The “sudo” prefix will run the command as a “super user”. Only administrators (i.e. super users) can shutdown the Pi this way. Do not simply yank the power cord out as this can corrupt the file system. Once the shutdown sequence has completed, remove the power cord from the micro USB port of the Pi.

Now we are ready to build our first circuit. For this circuit, you will need a button, a 10K ohm resistor (match the color of the resistor shown above), and two jumper wires. Attach a jumper wire between the top right pin of the button to pin 23. Attach the top left pin of the button to ground through the resistor (this will be a “pull- down” resistor). Attach the bottom right pin of the button to 3.3V. Ensure all pins and wires are firmly seated into the breadboard (especially the button, which can require a bit of force to sit flush into the breadboard. You may need to slightly bend the legs on the button to line up with the holes before pushing it all the way down). The wiring diagram and a photo of what your breadboard should look like can be found above.

When we press the button, the circuit that connects the 3.3V line into pin 23 will close. This will be received by the Pi as a digital logic ‘1’. When the button is not being pressed, pin 23 is 'pulled down' to Ground, or 0 V. In this case, the Pi will see the input as a digital logic ‘0’ coming into pin 23.

Plug the ribbon cable into your Pi and power it on once you have finished wiring up the button.

Tip: There is a guide inside your Canakit box that shows you how to read resistor values from the color-coding.

Reading the Button

SSH into your Pi and cd into the piot directory. There is a python script in this directory called button.py. This is the script we will use to read the button input. Let’s take a look at this script.

Copy Code
$ cd piot
$ nano button.py

button.py 

Copy Code
#Import library that lets you control the Pi's GPIO pins
import RPi.GPIO as io

# Disable messages about GPIO pins already being in use
io.setwarnings(False)
# Numbering scheme that corresponds to breakout board and pin layout
io.setmode(io.BCM)

button_io_pin = 23
io.setup(button_io_pin, io.IN) # Specify that button_io_pin will be an input
button_previous_input = 0

while True:
# Get the state of the button input
button_input = io.input(button_io_pin)
if (button_input != button_previous_input):
# When the button changes state, print its value
print button_input
button_previous_input = button_input

The lines that begin with ‘#’ are comment lines, a great way to document code. This script imports a special library, RPi.GPIO, that allows you to read and write the Pi’s I/O pins. We set the input button to pin 23 on line 9, which matches our breadboard circuit. Pin 23 is set to an input pin on line 10. The “while loop” on line 13 will run until you kill the script and read the state of pin 23 and print its value only when it changes.

Using indentation in Python is not just a way to make your code more readable but is actually a part of Python syntax. Every line of code that is has at least one tab after the while True: statement is part of that while loop. Notice lines 17-19 have an additional tab indentation. This makes these lines a part of the if statement on line 16 (as well as part of the while loop).

We are ready to test our code. Run the following command:

Copy Code
$ sudo python button.py

We have to use the sudo prefix because accessing the Pi’s I/O requires super user access.

Pressing the button over and over should result in a 1 and a 0 being printed to the screen each time.

Copy Code
1
0
1
0
1
0

To stop the script, press CTRL + c.

Tip: if your button is not working, make sure it is pressed firmly into the breadboard. The canakit buttons can be a little difficult to seat into the breadboard and make a good connection.

Adding an LED

We have driven a button input into our Pi. Now let’s control a LED output from our Pi. Make the following additions to your breadboard (after you have powered down your Pi!!).

Connecting the LEDs

The Python script that we will use for this circuit will turn the LED on and off when a button is pressed. Once your circuit is built, power your Pi back on, ssh into it, and cd into the piot directory. The Python script we will use is called button-led.py.

Copy Code
$ cd piot
$ nano button-led.py

 

button-led.py

Copy Code
# Import library that lets you control the Pi's GPIO pins
import RPi.GPIO as io
# Import time for delays
from time import sleep

# Disables messages about GPIO pins already being in use
io.setwarnings(False)
# Numbering scheme that corresponds to breakout board and pin layout
io.setmode(io.BCM)

led_io_pin = 17
button_io_pin = 23
# Specifies that led_io_pin will be an output
io.setup(led_io_pin, io.OUT)
# Specifies that button_io_pin will be an input
io.setup(button_io_pin, io.IN)

button_toggle = True
previous_button_input = 0

while True:
# Get the state of the button input
button_input = io.input(button_io_pin)

# Debounce the button
if (previous_button_input == 0 and button_input):
# Toggle the button on and off
button_toggle = not button_toggle
previous_button_input = button_input
sleep(0.05)

if button_toggle:
# Turn the LED on
io.output(led_io_pin, io.HIGH)
else:
# Turn the LED off
io.output(led_io_pin, io.LOW)

 

On line 4, we used a new library called time. This allows us to use the sleep command on line 29 (part of the button debounce logic). We specified the LED pin number as 17 on line 11 and set that pin to be an output on line 14. Instead of just reading if the button is on or off, line 27 toggles a variable, button_on, every time a button is pressed. Lines 31-36 either turn on or turn off the LED based on the state of button_on.Run this script and press the button to see if the LED turns on and off.

 

Copy Code
$ sudo python button-led.py

 

Tip: if your LED will not turn on, you may have it turned around backwards. Make sure the long end of the LED is connected to the 220 ohm resistor and the short end of the LED is connected to pin 17 of the Pi.

Tip: if your LED is really dim, you may have used a 10K ohm resistor instead of the 220 ohm resistor.

Part 4. IoT Temperature Sensor

The Temp Sensor

Overview

We made a “Hello World!” Python script in Section 2. Setting up a Pi to stream temperature to a cloud service is quickly becoming the de facto IoT “Hello World!” project.

The DS18B20 temperature sensor works well with the Raspberry Pi because it has a digital output, and the Pi has no on-board analog to digital convertors (ADC). Raspbian includes an interface to read the output of the sensor. We just have to write a little code to grab and parse out the temperature.

NOTE: If you are going through this at home: To ensure you have the latest code samples, ensure you've performed a git pull in your code directory. If you are working out of your own fork, make sure you merge any upstream changes.

Hardware Setup

The DS18B20 has three wires. The red wire connects to 3.3V. The blue/black wire connects to ground. The yellow wire connects to a pull-up resistor/pin 4.

If you have a DS18B20 that has red/black/blue wires, red to 3.3V, black to ground, and blue to pull-up resistor/pin 4.

Make sure your Pi is powered off before putting together your circuit.

Hardware Setup

Making Sure the DS18B20 Works

With this circuit wired up and connected, power on your Pi. The latest version of Raspbian (kernel 3.18) requires an addition to your /boot/config.txt file for the Pi to communicate with the DS18B20. Run the following to edit this file:

Copy Code
$ sudo nano /boot/config.txt

 If the following line is not already in this file (if it is, it is likely at the bottom of the file), add it and save the file.

Copy Code
dtoverlay=w1-gpio,gpiopin=4

Restart your Pi for the changes to take effect.

Copy Code
$ sudo reboot

To start the temperature sensor read interface we need to run two commands. Go to a command prompt on your Pi or SSH into your Pi. Type the following commands:

Copy Code
$ sudo modprobe w1-gpio
$ sudo modprobe w1-therm

The output of your temperature sensor is now being written to a file on your Pi. To find that file:

Copy Code
$ cd /sys/bus/w1/devices

In this directory, there will be a sub-directory that starts with “28-“. What comes after the “28-” is the serial number of your sensor. cd into that directory. Inside this directory, a file named w1_slave contains the output of your sensor. Use nano to view the contents of the file. Once you've entered into the file, it will look something like this:

Copy Code
a2 01 4b 46 7f ff 0e 10 d8 : crc=d8 YES 
a2 01 4b 46 7f ff 0e 10 d8 t=26125

The number after “t=” is the number we want. This is the temperature in 1/1000 degrees Celsius (in the example above, the temperature is 26.125 C). We just need a simple program that reads this file and parses out that number. We will get to that in just a second.

Tip: if you don't see a sub-directory that starts with "28-" but see multiple sub-directories that start with "00-", you might have the resistor plugged into ground instead of into power. If your circuit is wired correctly and you continue to get "00-" sub-directories, you might have a bad temperature sensor.

Initial State

We not only want to see what the current temperature is from our DS18B20 sensor, but we want to stream the temperature to a cloud service so we can see a pretty visualization of the current and past temperature data. Our temperature data needs a destination. We will use Initial State as that destination.

Step 1: Register for Initial State Account

Go to https://auth.initialstate.com/auth/#/login/ and create a new account.

Step 2: Install the ISStreamer

Install the Initial State Python module onto your Pi:

At a command prompt (don’t forget to SSH into your Pi first), run the following command: 

Copy Code
$ cd /home/pi/
$ \curl -sSL https://get.initialstate.com/python -o - | sudo bash

 

Step 3: Make some Automagic

After Step 2 you will see something similar to the following output to the screen:

Copy Code
pi@raspberrypi ~ $ \curl -sSL https://get.initialstate.com/python -o - | sudo bash
Password:
Beginning ISStreamer Python Easy Installation!
This may take a couple minutes to install, grab some coffee :)
But don't forget to come back, I'll have questions later!

Found easy_install: setuptools 1.1.6
Found pip: pip 1.5.6 from /Library/Python/2.7/site-packages/pip-1.5.6- py2.7.egg (python 2.7)
pip major version: 1
pip minor version: 5
ISStreamer found, updating...
Requirement already up-to-date: ISStreamer in /Library/Python/2.7/site-packages
Cleaning up...
Do you want automagically get an example script? [y/N]

 (if you installed Raspbian yourself, the output will be different and take longer as the extra components are installed)

When prompted to automatically get an example script, type y. This will create a test script that we can run to ensure that we can stream data to Initial State from our Pi. You will be prompted:

Copy Code
Where do you want to save the example? [default: ./is_example.py]: 

You can either type ./is_example.py or hit enter to accept the default.

You will be prompted for your username and password that you just created when you registered your Initial State account. Enter both and the installation will complete.

Step 4: Access Keys

Let’s take a look at the example script that was created.

Copy Code
$ nano is_example.py

On line 15, you will see a line that starts with streamer = Streamer(bucket_ ... . This lines creates a new data bucket named “Python Stream Example” and is associated with your account. This association happens because of the access_key=”...” parameter on that same line. That long series of letters and numbers is your Initial State account access key. If you go to your Initial State account in your web browser, click on your username in the top right, then go to “my account”, you will find that same access key at the bottom of the page under “Streaming Access Keys”.

Stream Key

Every time you create a data stream, that access key will direct that data stream to your account (so don’t share your key with anyone).

Step 5: Run the Example

Run the test script to make sure we can create a data stream to your Initial State account. Run the following:

Copy Code
$ python is_example.py

Step 6: Profit

Go back to your Initial State account in your web browser. A new data bucket called “Python Stream Example” should have shown up on the left in your log shelf (you may have to refresh the page). Click on this bucket and then click on the Waves icon to view the test data.

Python Example

You will want to step through the Waves tutorial to familiarize yourself with how to use this data visualization tool. You are now ready to start streaming real data from your Pi.

A Live IoT Data Stream

Everything is now ready for us to start streaming data. In the piot directory, there is a script called temperature.py that we will use. We will have to make one modification to this script to get it to work.

Copy Code
$ nano temperature.py

temperature.py

Copy Code
import os
import glob
import time
from ISStreamer.Streamer import Streamer

streamer = Streamer(bucket_name="Temperature Stream", bucket_key="piot_temp_stream031815", access_key="PUT_YOUR_ACCESS_KEY_HERE")

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines


def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c

while True:
temp_c = read_temp()
temp_f = temp_c * 9.0 / 5.0 + 32.0
streamer.log("temperature (C)", temp_c)
streamer.log("temperature (F)", temp_f)
time.sleep(.5)

You need to put your Initial State access key on line 6 in place of PUT_YOUR_ACCESS_KEY_HERE (copy the streaming key to your clipboard from 'My Account' and paste it into the code in nano in your terminal).

Tip: if you are using Putty, you can paste by right clicking the mouse.

Line 6 will create a bucket named “Temperature Stream” in your Initial State account (assuming you correctly specified your access_key on this same line). Lines 8 through 30 of this script simply interface with the DS18B20 sensor to read its temperature from the w1_slave file we discussed earlier. The read_temp_raw() function on line 15 reads the raw w1_slave file. The read_temp() function on line 21 parses out the temperature from that file. Line 34 calls these functions to get the current temperature. Line 35 converts the temperature from Celsius to Fahrenheit. Lines 35 and 36 streams the temperature to your Initial State account. Line 37 pauses the script for 0.5 seconds, setting how often the temperature sensor will be read and streamed.

Tip: a detailed explanation of how the DS18B20 works can be found at (https://learn.adafruit.com/adafruits-raspberry-pi-lesson-11-ds18b20-temperature-sensing/hardware)

We are ready to start streaming. Run the following command:

Copy Code
$ sudo python temperature.py

Go back to your Initial State account in your web browser and look for a new data bucket called Temperature Stream (you may need to refresh your browser). Open this data stream in Lines. You should see temperature data streaming in live. Vary the temperature of the sensor by holding it in your hand or putting it in a glass of ice. An example temperature stream is shown below.

Temp Stream example

Part 5. Magnetic Contact Switch

Magnetic Contact Switch

Overview

Another popular IoT project application is security. Personal surveillance camera systems and motion detectors are becoming increasingly easy and cheap to setup. We’re going to take a step in that direction by using a magnetic contact switch as a door sensor.

We learned how to collect data from a temperature sensor in Part 4 – collecting from the door sensor is even more simple. One side of the sensor has a switch that is closed whenever the other side, which has a magnet, is brought within range. You can detect whether or not the switch is closed, which means that we can see if something (like a door or lid) is open or closed.

NOTE: To ensure you have the latest code samples, ensure you've performed a git pull in your code directory. If you are working out of your own fork, make sure you merge any upstream changes.

Hardware Setup

The magnetic contact switch has 2 wires and it doesn’t matter which one goes where. You just want to make sure that one wire is going to one of the Raspberry Pi’s GPIO pins (in this case, GPIO 23/pin 16) and the other wire is connected to ground.

Make sure your Pi is powered off before putting together your circuit.

Hardware Setup

Making Sure the Switch Works

With this circuit wired up and connected, power on your Pi. We’ve already installed the RPi.GPIO library and ISStreamer, and, unlike the temperature sensor, this door sensor doesn’t need any initialization. It basically acts like a button.

In order to make sure it’s working, we’re going to add some extra statements to our final script that print to the terminal like in our “Hello World”. Go to the piot directory and use nano to edit the script door.py.

Copy Code
$ nano door.py

door.py

Copy Code
import time # so we can use "sleep" to wait between actions
import RPi.GPIO as io # import the GPIO library we just installed but call it "io"
from ISStreamer.Streamer import Streamer # import the ISStreamer

## name the bucket and individual access_key
#streamer = Streamer(bucket_name="Locker Protector", bucket_key="locker_protector", access_key="YOUR_ACCESS_KEY_HERE")

io.setmode(io.BCM) # set GPIO mode to BCM
door_pin = 23 # enter the number of whatever GPIO pin your're using
io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP) # use the built-in pull-up resistor

door=0 # initialize door

## Event loop
while True:
## if the switch is open
if io.input(door_pin):
#streamer.log("Door", "Open") # stream a message saying "Open"
#streamer.flush() # send the message immediately
door = 0 # set door to its initial value
time.sleep(1) # wait 1 second before the next action
## if the switch is closed and door does not equal 1
if (io.input(door_pin) == False and door != 1):
#streamer.log("Door", "Close") # stream a message saying "Close"
#streamer.flush() # send the message immediately
door = 1 # set door so that this loop won't act again until the switch has been opened

You’ll notice that the streamer statements are commented out with a #. This is because we want to test the switch before streaming anything.

Underneath each respective streamer.flush() statement, we are going to add:

Copy Code
        print "Open"
print "Close"

Save the script and run it.

Copy Code
$ sudo python door.py

If the switch and magnet are sufficiently far apart, then you should see “Open” start printing down the screen. Bring the two together (less than an inch apart) and you should see “Close” print once. Move them apart and “Open” will print again. Now we’re in business!

A Live Security Data Stream

In order to stream, you need to uncomment any lines with the word “streamer” at the beginning. Simply delete the # and print statements and change YOUR_ACCESS_KEY_HERE to the Initial State access_key that you used earlier.

Save the file and run it to begin streaming.

Copy Code
$ sudo python door.py

Go back to your Initial State account in your web browser and look for a new data bucket called Locker Protector (you may need to refresh your browser). Open this data stream in Waves. Move your contact switch apart and together to see “Open” messages streaming in live. An example stream is shown below.

Example Stream

Part 6. A Real Time Sensor Dashboard

Dashboard

Overview

This is the fun section where we put everything we learned in the previous sections together to create something that really starts to show the power of the Internet of Things. You will learn how easy it is to create a custom dashboard that lets you see all of your sensor/IoT data at-a-glance. You will learn how to instantly turn your sensor/IoT data into bar charts, line graphs, pie charts, histograms, etc. You will even learn how to make your sensor/IoT devices speak emojis. If you got this far, you would be crazy to skip this section.

Hardware Setup

Hardware Setup

Make sure your Pi is powered off before putting together your circuit.

Simply combine the two previous circuits that you previously built (the temperature probe and door sensor).

Stream It

Once everything is wired up (you should be getting pretty good at this by now), power up your Pi. The python script we will be using is inside the piot directory and is called sensors.py.

Copy Code
$ cd piot
$ ls

You should see sensors.py listed.

Note If you do not see sensors.py listed because you started this tutorial prior to Aug 19, 2015 (when it was created), you can find this file at https://github.com/InitialState/piot-101/blob/master/sensors.py (simply copy and paste it into a new file). Alternatively, you can re-clone your piot directory:

Copy Code
$ cd ~
$ git clone https://github.com/InitialState/piot-101.git piot

sensors.py

Copy Code
import os
import glob
import time
import RPi.GPIO as io
import thread
from ISStreamer.Streamer import Streamer

# --------- User Settings ---------
BUCKET_NAME = ":computer: Sensors"
BUCKET_KEY = "piot_sensor_stream082315"
ACCESS_KEY = "PUT_YOUR_ACCESS_KEY_HERE"
TEMPERATURE_TOO_HIGH_F = 85
TEMPERATURE_TOO_LOW_F = 50
# ---------------------------------

io.setmode(io.BCM)
door_pin = 23
io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP)

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines


def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c

def stream_temp(streamer):
while True:
temp_c = read_temp()
temp_f = temp_c * 9.0 / 5.0 + 32.0
if temp_f > TEMPERATURE_TOO_HIGH_F:
streamer.log("Status", ":fire:")
elif temp_f < TEMPERATURE_TOO_LOW_F:
streamer.log("Status", ":snowflake:")
else:
streamer.log("Status", ":thumbsup:")
streamer.log("temperature (C)", temp_c)
streamer.log("temperature (F)", temp_f)
print "Temperature: " + str(temp_f) + " F"
streamer.flush()
time.sleep(.5)

def main():
streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY)
# Start temperature stream thread
try:
thread.start_new_thread(stream_temp, (streamer, ))
except:
print "Error: unable to start temperature streamer thread"

# Door sensor
door_status = 1
while True:
## if the switch is open
if (io.input(door_pin) == True and door_status != 0):
streamer.log(":door: Door", "Open")
print "Door Open"
streamer.flush()
door_status = 0
## if the switch is closed
if (io.input(door_pin) == False and door_status != 1):
streamer.log(":door: Door", "Close")
print "Door Closed"
streamer.flush()
door_status = 1
time.sleep(2)

if __name__ == "__main__":
main()

Edit this file and place your access key in line 11 where it says "PUT_YOUR_ACCESS_KEY_HERE" (otherwise, you won't be streaming any sensor data into your account, and the rest of this section won't be very fun). You only have to modify line 11 as it assigns your access key to a global variable that is used in the Streamer constructor on line 62.

Run the script

Copy Code
$ sudo python sensors.py

This script streams the data from both sensors to Initial State and outputs the sensor values to the prompt. The prompt output will help you troubleshoot any issues you might have with wiring your circuit. You should see something similar to the following:

Copy Code
Temperature: 63.5 F
Temperature: 58.6616 F
Temperature: 55.0616 F
Temperature: 52.25 F
Door Open
Temperature: 50.1116 F
Temperature: 48.425 F
Temperature: 46.9616 F
Temperature: 45.8366 F
Temperature: 44.825 F
Temperature: 43.925 F

Bonus Information to up your nerd cred: Since we are collecting data from two sensors inside of one script, we had to do something a little special in the sensors.py code. The temperature sensor needs to report temperature on a regular interval (like a heartbeat). The door sensor needs to report open/closed when the event happens. Combining these two operations in sequence would be awkward (e.g. if we put the script to sleep for 10 seconds between temperature reads and a door sensor event happens when we are asleep, then the event is missed). To make this a bit cleaner, the temperature streaming code was launched as a "thread" on line 65 (thread.start_new_thread(stream_temp, (streamer, ))). The code inside of a thread executes, essentially, independently of the code outside of that particular thread. This allows the temperature streaming code to run on an interval (using the time.sleep(#) command to insert a controlled delay) without ever missing a door sensor event. You still have to be careful that you aren't blasting the processor with stuff to do in one thread (or outside of all threads) where it has no opportunity to execute the code in other threads. Doing this could peg the CPU at 100% usage. This is why there is a time.sleep(2) on line 84.

Building Your Dashboard

Go to your Initial State account and you should see a new data bucket named "computer sensors". The first thing to notice is that your bucket name has an emoji in it. Look at line 9 of sensors.py:

Copy Code
BUCKET_NAME = ":computer: Sensors"

The :computer: part of the bucket name is an emoji token that gets replaced with the actual emoji when displayed. You can get a list of all emoji tokens at http://emoji.codes. You can use emoji tokens in bucket names, signal/stream names, and signal/stream values. This is important because emojis can convey context efficiently, most commonly with just a single character. When creating a data visualization such as a dashboard, efficiently communicating context, emotion, urgency, etc. is not only important, it is fun.

Click on the "computer sensors" data bucket and select the Tiles visualization. You will see something similar to the following the first time you load a new bucket in Tiles:

Computer Sensors Dashboard

Congratulations, you just created a real-time dashboard (well that was easy, wasn't it?). Every signal/stream coming into that data bucket has a tile automatically created for it. This gives you a single view where you can see all of your data at-a-glance. You just need to customize how each tile is drawn, the size of each tile, and the order that you want the tiles to be in.

Let's start with resizing a tile. Simply click on any corner or edge of a tile and drag to resize it as a square or rectangle. Wide rectangles are useful for signals/streams that have a line graph drawn like the two temperatures.

Now let's re-order our tiles. Click on the name of the tile and drag to move the entire tile to another slot. Notice how tiles won't overlap but auto-pack. You can make your dashboard look something like this by changing tile sizes and order:

Changing tile size and order

Let's make one more tweak. Let's change the tile type. Mouse over the cog icon in the top right corner of the Door tile to see a list of available types. Change the tile type to bar chart, pie chart, and histogram to see the different types. The pie chart and bar chart give you different views for how long the Door stream has each value (in this case either Open or Close). The histogram shows you when an "event" happened for Door. The histogram is particularly useful when you simply want to see when or how often something happened in the Door stream. The "last value" type is pretty self-explanatory, useful when you only care what is happening not the history of what happened. For the last value type, notice the text at the bottom of the tile "Since Aug 18, 2015 2:12:06 PM". This tells you when the last event happened, often a helpful piece of information.

Dashboard

I am sure you noticed that you have not only your two temperature streams and a door stream but also a fourth stream named Status. Status isn't the output of a sensor, but a stream that our script created. Lines 49-54 of sensors.py drives this stream based on the temperature from the sensor:

Copy Code
        if temp_f > TEMPERATURE_TOO_HIGH_F:
streamer.log("Status", ":fire:")
elif temp_f < TEMPERATURE_TOO_LOW_F:
streamer.log("Status", ":snowflake:")
else:
streamer.log("Status", ":thumbsup:")

If the temperature gets too warm, Status changes to fire (TEMPERATURE_TOO_HIGH_F is set on line 12, feel free to change this number and restart the script). If the temperature gets too cold, Status changes to ICE (TEMPERATURE_TOO_LOW_F is set on line 13). If the temperature is neither too high or low, a Thumbs Up is sent. Heat up the temperature sensor in your hand and cool it down in ice to see the dashboard and the status tile update in real-time.

Temp Dashboard

Conclusion

Temperature Dashboard Conclusion

If you made it this far and completed every section, you just built something that, not long ago, took an entire engineering team months to build. Congratulations!! 

制造商零件编号 319030002
BASIC BREAD BOARD 16.5*5.5 CM
Seeed Technology Co., Ltd
¥58.14
Details
制造商零件编号 2028
BREAKOUT T-COBBLER RPI 40PIN
Adafruit Industries LLC
¥64.71
Details
制造商零件编号 WP154A4SUREQBFZGC
LED RGB CLEAR T-1 3/4 T/H
Kingbright
¥16.09
Details
制造商零件编号 CF14JT10K0
RES 10K OHM 5% 1/4W AXIAL
Stackpole Electronics Inc
¥0.81
Details
制造商零件编号 CF14JT220R
RES 220 OHM 5% 1/4W AXIAL
Stackpole Electronics Inc
¥0.81
Details
制造商零件编号 381
WATERPROOF DS18B20 DIGITAL TEMPE
Adafruit Industries LLC
¥80.99
Details
制造商零件编号 375
MAGNETIC CONTACT SWITCH (DOOR SE
Adafruit Industries LLC
¥32.15
Details
制造商零件编号 2260
GRAPHIC DISPLAY TFT RGB 5"
Adafruit Industries LLC
¥631.51
Details
制造商零件编号 3025033-01
CBL USB2.0 A PLUG-MCR B PLUG 1'
Qualtek
¥21.57
Details
制造商零件编号 1738
KEYBOARD&MOUSE WIRELESS BATT USB
Adafruit Industries LLC
¥162.39
Details
制造商零件编号 SC0012
CASE ABS RED WHT 3.228"LX4.252"W
Raspberry Pi
¥44.27
Details
制造商零件编号 SC0022
SBC 1.2GHZ 4 CORE 1GB RAM
Raspberry Pi
¥284.90
Details
Add all DigiKey Parts to Cart
TechForum

Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.

Visit TechForum