Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Smart Internet of Things Projects
Smart Internet of Things Projects

Smart Internet of Things Projects: Discover how to build your own smart Internet of Things projects and bring a new degree of interconnectivity to your world

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Smart Internet of Things Projects

Chapter 1. Making Your IoT Project Smart

We're going to begin by reviewing basic statistics. Then we will learn how to sense and actuate from Internet of Things (IoT) devices such as Arduino and Raspberry Pi. We will also introduce various Python libraries related to statistics and data. These libraries are useful for building our project throughout this book.

By the end of this chapter, you'll have learned about the following:

  • Introducing basic statistics and data science
  • Reviewing several IoT devices and platforms
  • Sensing and actuating through external devices on IoT devices
  • Building a smart IoT project

Let's get started!

Introducing basic statistics and data science

Let's say you want to know the temperature of your room, so you measure it every hour during the day using a particular tool. This data is necessary because you want to decide whether to buy an AC (Air Conditioning) machine or not. After measurement is done, you obtain a list of temperature data. The results of your measurements can be seen in the following table:

Time

Temperature (Celsius)

Time

Temperature (Celsius)

01:00

18

13:00

28

02:00

17

14:00

29

03:00

18

15:00

28

04:00

19

16:00

27

05:00

20

17:00

25

06:00

20

18:00

24

07:00

21

19:00

24

08:00

22

20:00

23

09:00

22

21:00

22

10:00

24

22:00

20

11:00

25

23:00

19

12:00

26

24:00

19

The preceding table shows of the temperature data in tabular form. You try to understand the meaning of the data. For this situation, you need some knowledge of statistics, along with some statistics terms such as mean, median, variance, and standard deviation.

Suppose we have a sample of n data, which is designated by x1, x2, x3, ..., xn. We can calculate mean, median, variance, and standard deviation using the following formulas:

Introducing basic statistics and data science

Tip

To compute median value, you should arrange the data in ascending order.

From the preceding table, you can calculate the mean, median, variance and standard deviation using the preceding formulas. You should obtain values of 22.5, 22, 12.348, and 3.514 respectively.

To understand the pattern of the data, you try to visualize it in graphics form, for instance, using Microsoft Excel. The result can be seen in the following figure:

Introducing basic statistics and data science

You can see that the average temperature of your room is 22.5 Celsius. The temperature maximum and minimum values are 19 and 17, respectively. With this information, you can think about what type of AC machine you want to buy.

Furthermore, you can extend your investigation by measuring your room's temperature for a week. After you have measured, you can plot the measurements in graphics form, for instance, using Microsoft Excel. A sample of temperature measurements is shown in the following figure:

Introducing basic statistics and data science

The graph shows room temperature changes every day. If you measure it every day for a year, you should see temperature trends in your room. Knowledge of data science can improve your ability to learn from data. Of course, some statistics and machine learning computing are involved to get insight how data behaviors are.

This book will help you to get started with how to apply data science and machine learning in real cases, with a focus on IoT fields.

Python for computational statistics and data science

Python is a widely used, general purpose programming language. Starting to program with Python is a good point. Python provides simple programming syntax and a lot of APIs, which we can use to expand our program.

To use Python on your computer, you can download and install it from https://www.python.org/downloads/ if your OS does not yet have it installed. After completing the installation, we can run the Python program via Terminal, or the Command Prompt on the Windows platform, by typing the following command:

$ python

Tip

Note: remove $ sign. Just type python on Terminal. This is applicable to Python 2.x.

Once you have executed the command, you should see the Python command prompt, as shown in the following screenshot:

Python for computational statistics and data science

If you installed Python 3, you usually run the program using the following command:

$ python3

You should see the Python 3 shell on your Terminal:

Python for computational statistics and data science

What's next?

There are lots of Python resources to help you learn how to write programs using Python. I recommend to reading the Python documents at https://www.python.org/doc/. You can also read Python books to accelerate your learning. This book does not cover topics about the basic Python programming language.

Python libraries for computational statistics and data science

Python has big communities. They help their members to learn and share. Several community members have been open sources related to computational statistics and data science, which can be used for our work. We will use these libraries for our implementation.

The following are several Python libraries for statistics and data science.

NumPy

NumPy is a fundamental package for efficient scientific computing in Python. This library has capabilities for handling N-dimensional arrays and integrating C/C++ and Fortran code. It also provides features for linear algebra, Fourier transform, and random number.

The official website for NumPy can be found at http://www.numpy.org.

Pandas

Pandas is a library for handling table-like structures called DataFrame objects. This has powerful and efficient numerical operations similar to NumPy's array object.

Further information about pandas can be found at http://pandas.pydata.org.

SciPy

SciPy is an expansion of the NumPy library. It contains functions for linear algebra, interpolation, integration, clustering, and so on.

The official website can be found at http://scipy.org/scipylib/index.html.

Scikit-learn

Scikit-learn is the most popular machine learning library for Python. It provides many functionalities, such as preprocessing data, classification, regression, clustering, dimensionality reduction, and model selection.

Further information about Scikit-learn can be found at http://scikit-learn.org/stable/.

Shogun

Shogun is a machine learning library for Python, which focuses on large-scale kernel methods such as support vector machines (SVMs). This library comes with a range of different SVM implementations.

The official website can be found at http://www.shogun-toolbox.org.

SymPy

SymPy is a Python library for symbolic mathematical computations. It has capabilities in calculus, algebra, geometry, discrete mathematics, quantum physics, and more.

The official website can be found at http://www.sympygamma.com.

Statsmodels

Statsmodels is a Python module we can use to process data, estimate statistical models and test data.

You can find out more about Statsmodels by visiting the official website at http://statsmodels.sourceforge.net.

Building a simple program for statistics

In the first section, you already measure room temperature. Now we will try to perform some simple computational statistics using Statsmodels. We will use our measurement results data and then build a linear regression for our data.

First, we should install Statsmodels. This library needs required libraries such as NumPy, SciPy, pandas, and patsy. We can install them using pip. Type the following command:

$ pip install numpy scipy pandas patsy statsmodels

If you get a problem related to security access, you can run this command using sudo:

$ sudo pip install numpy scipy pandas patsy statsmodels

If your computer doesn't have pip installed, you can install it by following the guidelines at https://pip.pypa.io/en/stable/installing/.

For testing, we create a Python program. Write the following scripts:

import numpy as np
import statsmodels.api as sm

# room temperature
Y = [18, 17, 18, 19, 20, 20, 21, 22, 22, 24, 25, 26, 28, 29, 28, 27, 25, 24, 24, 23, 22, 20, 19, 19]
X = range(1, 25)
X = sm.add_constant(X)

model = sm.OLS(Y, X)
results = model.fit()

# print
print(results.params)
print(results.tvalues)


print(results.t_test([1, 0]))
print(results.f_test(np.identity(2)))

We build a linear regression using sm.OLS(). We then do estimation using model.fit(). Finally, we print the computation result. Save the program in a file called ch01_linear.py.

Now you can run this program using the following command:

$ python ch01_linear.py

If you have installed Python 3, you can run this program using the following command:

$ python3 ch01_linear.py

You should see the program output shown in the following screenshot. I run this program using Python 3:

Building a simple program for statistics

IoT devices and platforms

The IoT platform has the capability to connect to an Internet network and interact with other platforms. Generally speaking, talking about IoT in terms of device platform is a huge topic. In this section, we will explore several IoT device platforms that are widely used in client side.

Arduino

Arduino is a widely used development board. This board is well known in the embedded community. Most Arduino boards are built using Atmel AVR, but some boards use other MCUs regarding to who joints venture with Arduino. Currently, Arduino boards are built by Arduino.cc and Arduino.org. Other companies also build boards, which are usually called Arduino-compatible. This is because the founder of Arduino already shared the board scheme so that people can build own Arduino. Please make sure you use a board and software from the same company.

To extend Arduino I/O and functionalities, we can use Arduino shields. There are many Arduino shields, with different purposes, for instance, Bluetooth, Wi-Fi, GSM, temperature, and humidity sensors. The benefit of using the Arduino shield is that it allows you to focus on board development. We just have to attach Arduino shield to the Arduino board without any soldering.

We're going to review several Arduino boards from Arduino.cc. We can read a comparison of all Arduino boards from Arduino.cc by visiting this site: http://www.arduino.cc/en/Products/Compare. We will review Arduino boards such as Arduino Uno, Arduino 101, and Arduino MKR1000.

The Arduino Uno model is widely used in Arduino development. It's built on top of a MCU ATmega328P microcontroller. The board provides several digital and analog I/O pins, to which we can attach our sensor and actuator devices. SPI and I2C protocols are also provided by the Arduino Uno. For further information about the board, I recommend you read the board specification at http://www.arduino.cc/en/Main/ArduinoBoardUno. You can see an Arduino Uno board in the following figure:

Arduino 101 is the same as Arduino Uno in terms of I/O pins. Arduino 101 runs Intel Curie, http://www.intel.com/content/www/us/en/wearables/wearable-soc.html, as its core module. This board has a built-in Bluetooth module. If you want your Arduino 101 connect to a Wi-Fi network, you should add an additional Wi-Fi shield. I recommend you use Arduino Wi-Fi Shield 101, http://www.arduino.cc/en/Main/ArduinoWiFiShield101.

The following figure shows an Arduino 101 board:

Arduino MKR1000 is a new board at the time of writing. This board uses the Atmel ATSAMW25 SoC, which provides a built-in Wi-Fi module. I recommend using this board as an IoT solution for the Arduino platform because the Wi-Fi module, WINC1500, is supported for SSL and ECC508 CryptoAuthentication. Further information about this board can be found at http://www.arduino.cc/en/Main/ArduinoMKR1000.

The following figure shows the Arduino MKR1000 board:

Raspberry Pi

The Raspberry Pi is a low-cost with credit card-sized computer created by Eben Upton. It's a mini computer for educational purposes. To see all Raspberry Pi models, you can go to https://www.raspberrypi.org/products/. You can see Raspberry Pi 3 Model B and Raspberry Pi Zero in the following explanation.

The Raspberry Pi 3 Model B is the third generation of Raspberry Pi. This board consists of a Quad-Core 64-bit CPU, Wi-Fi, and Bluetooth. It's highly recommended for your IoT solution.

The following figure shows a Raspberry Pi 3 Model B board:

The Raspberry Pi Zero is a small computer half the size of the Model A+. It runs with a single-core CPU and no network module, but it provides a micro HDMI to be connected to a monitor. Due to the lack of network module, you will need an extended module, for instance, Ethernet USB or Wi-Fi USB, to connect Raspberry Pi Zero to a network.

The following image shows a Raspberry Pi Zero board:

BeagleBone Black and Green

BeagleBone Black (BBB) Rev C is a development kit based on an AM335x processor, which integrates an ARM Cortex™-A8 core operating at up to 1 GHz. BBB is more powerful than Raspberry Pi. A BBB board also provides internal 4 GB 8-bit eMMC on-board flash storage.

BBB supports several OSes such as Debian, Android, and Ubuntu. To find out more about BBB, go to https://beagleboard.org/black.

The following figure shows a BeagleBone Black board:

SeeedStudio BeagleBone Green (BBG) is a joint effort by BeagleBoard.org and Seeed Studio. BBG has the same features as the BBB, except the HDMI port is replaced by Grove connectors, so the BBG's price is lower than the BBB. You can review and buy this board at http://www.seeedstudio.com/depot/SeeedStudio-BeagleBone-Green-p-2504.html.

The following figure shows a BBG board:

IoT boards based on ESP8266 MCU?

The ESP8266 is a low-cost Wi-Fi MCU with integrated TCP/IP. It's built by Espressif Systems, a Chinese manufacturer. You can find further information about this chip at http://espressif.com/en/products/hardware/esp8266ex/overview.

There are many boards based on the ESP8266 chip. The following is a list of board platforms that are built on top of an ESP8266 MCU:

If you're interested in the ESP8266 chip, I recommend you join the ESP8266 forum at http://www.esp8266.com. The following is a list of product forms for NodeMCU v2 and SparkFun ESP8266 Thing.

The following figure shows a NodeMCU v2 board:

Although NodeMCU v2 and SparkFun ESP8266 Thing boards have the same chip, their chip model is different. NodeMCU v2 uses an ESP8266 module. The SparkFun ESP8266 Thing board uses an ESP8266EX chip. In addition, the SparkFun ESP8266 Thing board provides a LiPo connector, which you can attach to an external battery.

The following figure shows a SparkFun ESP8266 Thing board:

IoT boards based on ESP8266 MCU?

SparkFun ESP8266 Thing board. Source: https://www.sparkfun.com/products/13231

IoT boards-based TI CC3200 MCU

TI CC3200 is a Wi-Fi MCU based on the ARM® Cortex®-M4 from Texas Instruments. This board is a complete solution for IoT. This chip supports for station, access point, and Wi-Fi direct modes. In terms of security, TI CC3200 supports WPA2 personal and enterprise security and WPS 2.0. You can review this module at http://www.ti.com/product/cc3200.

For IoT development, Texas Instruments provides the SimpleLink Wi-Fi CC3200 LaunchPad evaluation kit, which is a complete kit for development and debugging.

The following figure shows a SimpleLink Wi-Fi CC3200 LaunchPad board:

The TI CC3200 is also used by Readbear, http://redbear.cc, to develop RedBearLab CC3200 and RedBearLab Wi-Fi Micro boards. These boards have the same functionalities as the SimpleLink Wi-Fi CC3200 LaunchPad board, but it excludes the CC3200 debugger tool. These boards' prices are also lower than that of the SimpleLink Wi-Fi CC3200 LaunchPad board.

The following figure shows a RedBearLab CC3200 board:

Sensing and actuating on IoT devices

In this section, we will learn how to sense and actuate on IoT devices. This part is important because we can gather data through sensor devices or interact with the environment through actuator devices. For testing, I use Arduino, from Arduino.cc, and Raspberry Pi boards.

Sensing and actuating on Arduino devices

Most Arduino development uses Sketch. This is a simple programming language for building Arduino applications. If you have experience in C/C++, you'll be familiar with the programming syntax.

To start your development, you can download Arduino software from https://www.arduino.cc/en/Main/Software. After that, read about Arduino API at http://www.arduino.cc/en/Reference/HomePage.

Sensing and actuating on Arduino devices

Related to digital and analog I/O, you should be familiar with the following Sketch API:

  • digitalRead() reads data from a digital pin on Arduino
  • digitalWrite() writes data to a digital pin on Arduino
  • analogRead() reads analog data from an analog pin on Arduino
  • analogWrite() writes analog data to an analog pin on Arduino

In this section, I'll show you how to work with analog and digital I/O on Arduino. I use a light sensor. LDR or Photoresistor sensors are low-priced light sensor device. Even Seeedstudio has already designed one in module form, Grove – Light Sensor(P). You can review it at http://www.seeedstudio.com/depot/Grove-Light-SensorP-p-1253.html. This module has four pins, but you only connect the VCC and GND pins to the VCC and GND pins of your Arduino board. Then, the SIG pin is connected to an analog pin of the Arduino board. The following figure shows a Grove – Light Sensor(P):

You will need the following resources for testing:

Now you can connect digital 6 to digital 7. Then, the SIG pin from the LDR module is connected to A0. The VCC and GND pins of the LDR module are connected to 3V3 and GND. You can see the hardware wiring in the following figure:

Sensing and actuating on Arduino devices

This wiring is built using Fritzing, http://fritzing.org. It's available for Windows, Linux, and Mac. You can build your own wiring with some electronics components and boards. This tool provides a lot of electronics components. You can also add your own electronics components or downloads from the Internet.

My wiring implementation is shown in the following figure:

Sensing and actuating on Arduino devices

The next step is to write an Arduino program. Open your Arduino software, then, write the following program:

int dig_output = 7;
int dig_input = 6;
int analog_input = A0;

int digital_val = LOW;

void setup() {
  Serial.begin(9600); 

  pinMode(dig_output, OUTPUT);
  pinMode(dig_input, INPUT);
}

void loop() {

  digitalWrite(dig_output,digital_val);
  int read_digital = digitalRead(dig_input);
  Serial.print("Digital write: ");
  Serial.print(digital_val);
  Serial.print(" read: ");
  Serial.println(read_digital);

  int ldr = analogRead(analog_input);
  Serial.print("Analog read: ");
  Serial.println(ldr);  

  if(digital_val==LOW)
    digital_val = HIGH;
  else
    digital_val = LOW; 

  delay(1000);
}

Save this program as ArduinoIO. You can deploy this program to your Arduino board through Arduino software.

When finished, you can open the Serial Monitor tool from your Arduino software:

Sensing and actuating on Arduino devices

This program sends digital data (high and low values) from digital pin 7 to digital pin 6. You can read a light value from the LDR module via analogRead() on the A0 pin.

For the second sensing testing scenario, we will try to read temperature and humidity data from a sensor device. I use DHT-22. The RHT03 (also known as DHT-22) is a low-cost humidity and temperature sensor with a single wire digital interface. You can obtain this module from SparkFun, https://www.sparkfun.com/products/10167, and Adafruit, https://www.adafruit.com/products/393. You could also find this module in your local electronics store or online.

Sensing and actuating on Arduino devices

DHT22 module. Source: https://www.adafruit.com/products/385

Further information about the DHT-22 module, you can read the DHT-22 datasheet at http://cdn.sparkfun.com/datasheets/Sensors/Weather/RHT03.pdf.

Now we connect DHT-22 module to Arduino. The following is the wiring:

  • VDD (pin 1) is connected to the V3V pin on Arduino
  • SIG (pin 2) is connected to digital pin 8 on Arduino
  • GND (pin 4) is connected to GND on Arduino

You can see this wiring in the following figure:

Sensing and actuating on Arduino devices

You can see my wiring implementation in the following figure:

Sensing and actuating on Arduino devices

To access DHT-22 on Arduino, we can use the DHT Sensor library from Adafruit, https://github.com/adafruit/DHT-sensor-library. We can install this library from the Arduino software. Click the menu Sketch | Include Library | Manage Libraries so you will get a dialog.

Search dht in Library Manager. You should see the DHT sensor library by Adafruit. Install this library:

Sensing and actuating on Arduino devices

When installation is complete, you can start to write programs on the Arduino software. The following is a program sample for reading temperature and humidity from the DHT-22 module:

#include "DHT.h"

// define DHT22
#define DHTTYPE DHT22 
// define pin on DHT22
#define DHTPIN 8 

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600); 
  dht.begin();
}

void loop() {
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();


  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C\t");  
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.println(" *C ");  
}

Save this program as ArduinoDHT. Now you can compile and upload the program to your Arduino board. After that, open Serial Monitor to see the temperature and humidity data:

Sensing and actuating on Arduino devices

How does it work?

In the setup() function, we initialize the DHT module by calling dht.begin(). To read temperature and humidity, you can use dht.readTemperature() and dht.readHumidity(). You also can get a heat index using the dht.computeHeatIndex() function.

Sensing and actuating on Raspberry Pi devices

Raspberry Pi board is one of boards used for testing experiments in this book. In this section, we use Raspberry Pi to sense and actuate with external devices. I use a Raspberry Pi 3 board for testing.

Setting up

Before you use a Raspberry Pi board, you need to set up an OS on the board. OS software can be deployed on a microSD card. It's recommended to use an 8-GB microSD card . There's a lot of OS software you can use on a Raspberry Pi board. You can check it out at https://www.raspberrypi.org/downloads/.

For testing purposes, I use Raspbian, https://www.raspberrypi.org/downloads/raspbian/, as the OS on my Raspberry Pi board. Raspbian is an operating system, based on Debian, optimized for Raspberry Pi. Follow the installation guidelines at https://www.raspberrypi.org/documentation/installation/installing-images/README.md. Raspbian is just one OS for Raspberry Pi OS. You can try other Raspberry Pi OSes at https://www.raspberrypi.org/downloads/.

Accessing Raspberry Pi GPIO

If you use the latest version of Raspbian (Jessie or later), wiringPi module, http://wiringpi.com, is already installed for you. You can verify your wiringPi version on Raspberry Pi Terminal using the following command:

$ gpio -v

You should see your wiringPi module version. A sample of the program output can be seen in the following screenshot:

Accessing Raspberry Pi GPIO

Furthermore, you can verify the Raspberry GPIO layout using the following command:

$ gpio - readall

This command will display the Raspberry Pi layout. It can detect your Raspberry Pi model. A sample of the program output for my board, Raspberry Pi 3, can be seen in the following screenshot:

Accessing Raspberry Pi GPIO

For Raspberry Pi GPIO development, the latest Raspbian also has the RPi.GPIO library already installed—https://pypi.python.org/pypi/RPi.GPIO, for Python, so we can use it directly now.

To test Raspberry Pi GPIO, we put an LED on GPIO11 (BCM 17). You can see the wiring in the following figure:

Accessing Raspberry Pi GPIO

Now you can write a Python program with your own editor. Write the following program:

import RPi.GPIO as GPIO
import time


led_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)


try:
    while 1:
        print("turn on led")
        GPIO.output(led_pin, GPIO.HIGH)
        time.sleep(2)
        print("turn off led")
        GPIO.output(led_pin, GPIO.LOW)
        time.sleep(2)

except KeyboardInterrupt:
    GPIO.output(led_pin, GPIO.LOW)
    GPIO.cleanup()


print("done")

The following is an explanation of the code:

  • We set GPIO type using GPIO.setmode(GPIO.BCM). I used the GPIO.BCM mode. In GPIO BCM, you should see GPIO values on the BCM column from the GPIO layout.
  • We defined GPIO, which will be used by calling GPIO.setup() as the output mode.
  • To set digital output, we can call GPIO.output(). GPIO.HIGH is used to send 1 to the digital output. Otherwise, GPIO.LOW is used for sending 0 to the digital output.

Save this program into a file called ch01_led.py.

Now you can run the program by typing the following command on your Raspberry Pi Terminal.

$ sudo python ch01_led.py

We execute the program using sudo, due to security permissions. To access the Raspberry Pi hardware I/O, we need local administrator privileges.

You should see a blinking LED and also get a response from the program. A sample of the program output can be seen in the following screenshot:

Accessing Raspberry Pi GPIO

Sensing through sensor devices

In this section, we will explore how to sense from Raspberry Pi. We use DHT-22 to collect temperature and humidity readings on its environment.

To access DHT-22 using Python, we use the Adafruit Python DHT Sensor library. You can review this module at https://github.com/adafruit/Adafruit_Python_DHT.

You need required libraries to build Adafruit Python DHT Sensor library. Type the following commands in your Raspberry Pi Terminal:

$ sudo apt-get update
$ sudo apt-get install build-essential python-dev

Now you can download and install the Adafruit Python DHT Sensor library:

$ git clone https://github.com/adafruit/Adafruit_Python_DHT
$ cd Adafruit_Python_DHT/
$ sudo python setup.py install

If finished, we can start to build our wiring. Connect the DHT-22 module to the following connections:

  • DHT-22 pin 1 (VDD) is connected to the 3.3V pin on your Raspberry Pi
  • DHT-22 pin 2 (SIG) is connected to the GPIO23 (see the BCM column) pin on your Raspberry Pi
  • DHT-22 pin 4 (GND) is connected to the GND pin on your Raspberry Pi

The complete wiring is shown in the following figure:

Sensing through sensor devices

The next step is to write a Python program. You can write the following code:

import Adafruit_DHT
import time

sensor = Adafruit_DHT.DHT22

# DHT22 pin on Raspberry Pi
pin = 23


try:
    while 1:
        print("reading DHT22...")
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

        if humidity is not None and temperature is not None:
            print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))

        time.sleep(2)

except KeyboardInterrupt:
    print("exit")


print("done")

Save this program into a file called ch01_dht22.py. Then, you can run this file on your Raspberry Pi Terminal. Type the following command:

$ sudo python ch01_dht22.py

A sample of the program output can be seen in the following screenshot:

Sensing through sensor devices

How does it work?

First, we set our DHT module type by calling the Adafruit_DHT.DHT22 object. Set which DHT-22 pin is attached to your Raspberry Pi board. In this case, I use GPIO23 (BCM).

To obtain temperature and humidity sensor data, we call Adafruit_DHT.read_retry(sensor, pin). To make sure the returning values are not NULL, we validate them using conditional-if.

Building a smart temperature controller for your room

To control your room's temperature, we can build a smart temperature controller. In this case, we use a PID (proportional–integral–derivative) controller. When you set a certain temperature, a PID controller will change the temperature by turning either cooler or hotter. A PID controller program is developed using Python, which runs on the Raspberry Pi board.

Assume cooler and heater machines are connected via a relay. We can activate cooler and heater machine by sending HIGH signal on a relay.

Let's build!

Introducing PID controller

PID control is the most common control algorithm widely used in industry, and has been universally accepted in industrial control. The basic idea behind a PID controller is to read a sensor, then compute the desired actuator output by calculating proportional, integral, and derivative responses and summing those three components to compute the output.

An example design of a general PID controller is depicted in the following figure:

Introducing PID controller

Furthermore, a PID controller formula can be defined as follows:

Introducing PID controller

Kp, Ki , Kd represent the coefficients for the proportional, integral, and derivative. These parameters are non-negative values. The variable e represents the tracking error, the difference between the desired input value i, and the actual output y. This error signal e will be sent to the PID controller.

Implementing PID controller in Python

In this section, we will build a Python application to implement the PID controller. In general, our program flowchart can be described by the following figure:

Implementing PID controller in Python

We should not build a PID library from scratch. You can translate PID controller formula into Python code easily. For implementation, I use the PID class from https://github.com/ivmech/ivPID. The following is the content of the PID.py file:

import time

class PID:
    """PID Controller
    """

    def __init__(self, P=0.2, I=0.0, D=0.0):

        self.Kp = P
        self.Ki = I
        self.Kd = D

        self.sample_time = 0.00
        self.current_time = time.time()
        self.last_time = self.current_time

        self.clear()

    def clear(self):
        """Clears PID computations and coefficients"""
        self.SetPoint = 0.0

        self.PTerm = 0.0
        self.ITerm = 0.0
        self.DTerm = 0.0
        self.last_error = 0.0

        # Windup Guard
        self.int_error = 0.0
        self.windup_guard = 20.0

        self.output = 0.0

    def update(self, feedback_value):
        """Calculates PID value for given reference feedback

        .. math::
            u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt}

        .. figure:: images/pid_1.png
           :align:   center

           Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py)

        """
        error = self.SetPoint - feedback_value

        self.current_time = time.time()
        delta_time = self.current_time - self.last_time
        delta_error = error - self.last_error

        if (delta_time >= self.sample_time):
            self.PTerm = self.Kp * error
            self.ITerm += error * delta_time

            if (self.ITerm < -self.windup_guard):
                self.ITerm = -self.windup_guard
            elif (self.ITerm > self.windup_guard):
                self.ITerm = self.windup_guard

            self.DTerm = 0.0
            if delta_time > 0:
                self.DTerm = delta_error / delta_time

            # Remember last time and last error for next calculation
            self.last_time = self.current_time
            self.last_error = error

            self.output = self.PTerm + (self.Ki * self.ITerm) + (self.Kd * self.DTerm)

    def setKp(self, proportional_gain):
        """Determines how aggressively the PID reacts to the current error with setting Proportional Gain"""
        self.Kp = proportional_gain

    def setKi(self, integral_gain):
        """Determines how aggressively the PID reacts to the current error with setting Integral Gain"""
        self.Ki = integral_gain

    def setKd(self, derivative_gain):
        """Determines how aggressively the PID reacts to the current error with setting Derivative Gain"""
        self.Kd = derivative_gain

    def setWindup(self, windup):
        """Integral windup, also known as integrator windup or reset windup,
        refers to the situation in a PID feedback controller where
        a large change in setpoint occurs (say a positive change)
        and the integral terms accumulates a significant error
        during the rise (windup), thus overshooting and continuing
        to increase as this accumulated error is unwound
        (offset by errors in the other direction).
        The specific problem is the excess overshooting.
        """
        self.windup_guard = windup

    def setSampleTime(self, sample_time):
        """PID that should be updated at a regular interval.
        Based on a pre-determined sampe time, the PID decides if it should compute or return immediately.
        """
        self.sample_time = sample_time

For testing purposes, we create a simple program for simulation. We need required libraries such as numpy, scipy, pandas, patsy, and matplotlib libraries. First, you should install python-dev for Python development. Type the following commands in your Raspberry Pi Terminal:

$ sudo apt-get update
$ sudo apt-get install python-dev

When done, you can install numpy, scipy, pandas, and patsy libraries. Open your Raspberry Pi Terminal and type the following commands:

$ sudo apt-get install python-scipy
$ pip install numpy scipy pandas patsy

The last step is to install the matplotlib library from source code. Type the following commands on your Raspberry Pi Terminal:

$ git clone https://github.com/matplotlib/matplotlib
$ cd matplotlib
$ python setup.py build
$ sudo python setup.py install

Once the required libraries are installed, we can test our PID.py file. Type the following program:

import matplotlib
matplotlib.use('Agg')

import PID
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline


P = 1.4
I = 1
D = 0.001
pid = PID.PID(P, I, D)

pid.SetPoint = 0.0
pid.setSampleTime(0.01)

total_sampling = 100
feedback = 0

feedback_list = []
time_list = []
setpoint_list = []

print("simulating....")
for i in range(1, total_sampling):
    pid.update(feedback)
    output = pid.output
    if pid.SetPoint > 0:
        feedback += (output - (1 / i))

    if 20 < i < 60:
        pid.SetPoint = 1

    if 60 <= i < 80:
        pid.SetPoint = 0.5

    if i >= 80:
        pid.SetPoint = 1.3

    time.sleep(0.02)

    feedback_list.append(feedback)
    setpoint_list.append(pid.SetPoint)
    time_list.append(i)

time_sm = np.array(time_list)
time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)
feedback_smooth = spline(time_list, feedback_list, time_smooth)

fig1 = plt.gcf()
fig1.subplots_adjust(bottom=0.15)

plt.plot(time_smooth, feedback_smooth, color='red')
plt.plot(time_list, setpoint_list, color='blue')
plt.xlim((0, total_sampling))
plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5))
plt.xlabel('time (s)')
plt.ylabel('PID (PV)')
plt.title('TEST PID')


plt.grid(True)
print("saving...")
fig1.savefig('result.png', dpi=100)

Save this program into a file called test_pid.py. Then, run this program.

$ python test_pid.py

This program will generate result.png as a result of the PID process. A sample of the output form, result.png, is shown in the following figure. You can see that the blue line represents desired values and the red line is an output of PID:

Implementing PID controller in Python

How does it work?

First, we define our PID parameters, as follows:

P = 1.4
I = 1
D = 0.001
pid = PID.PID(P, I, D)

pid.SetPoint = 0.0
pid.setSampleTime(0.01)

total_sampling = 100
feedback = 0

feedback_list = []
time_list = []
setpoint_list = []

After that, we compute the PID value during sampling time. In this case, we set the desired output value as follows:

  • Desired output 1 for sampling from 20 to 60
  • Desired output 0.5 for sampling from 60 to 80
  • Desired output 1.3 for sampling more than 80
    for i in range(1, total_sampling):
        pid.update(feedback)
        output = pid.output
        if pid.SetPoint > 0:
            feedback += (output - (1 / i))
    
        if 20 < i < 60:
            pid.SetPoint = 1
    
        if 60 <= i < 80:
            pid.SetPoint = 0.5
    
        if i >= 80:
            pid.SetPoint = 1.3
    
        time.sleep(0.02)
    
        feedback_list.append(feedback)
        setpoint_list.append(pid.SetPoint)
    time_list.append(i)
    	

The last step is to generate a report and is saved to a file called result.png:

time_sm = np.array(time_list)
time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)
feedback_smooth = spline(time_list, feedback_list, time_smooth)

fig1 = plt.gcf()
fig1.subplots_adjust(bottom=0.15)

plt.plot(time_smooth, feedback_smooth, color='red')
plt.plot(time_list, setpoint_list, color='blue')
plt.xlim((0, total_sampling))
plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5))
plt.xlabel('time (s)')
plt.ylabel('PID (PV)')
plt.title('TEST PID')


plt.grid(True)
print("saving...")
fig1.savefig('result.png', dpi=100)

Controlling room temperature using PID controller

Now we can change our PID controller simulation using the real application. We use DHT-22 to check a room temperature. The output of measurement is used as feedback input for the PID controller.

If the PID output positive value, then we turn on heater. Otherwise, we activate cooler machine. It may not good approach but this good point to show how PID controller work.

We attach DHT-22 to GPIO23 (BCM). Let's write the following program:

import matplotlib
matplotlib.use('Agg')

import PID
import Adafruit_DHT
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline

sensor = Adafruit_DHT.DHT22

# DHT22 pin on Raspberry Pi
pin = 23

P = 1.4
I = 1
D = 0.001
pid = PID.PID(P, I, D)

pid.SetPoint = 0.0
pid.setSampleTime(0.25)  # a second

total_sampling = 100
sampling_i = 0
measurement = 0
feedback = 0

feedback_list = []
time_list = []
setpoint_list = []

print('PID controller is running..')
try:
    while 1:
        pid.update(feedback)
        output = pid.output

        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        if humidity is not None and temperature is not None:
            if pid.SetPoint > 0:
                feedback += temperature + output

            print('i={0} desired.temp={1:0.1f}*C temp={2:0.1f}*C pid.out={3:0.1f} feedback={4:0.1f}'
                  .format(sampling_i, pid.SetPoint, temperature, output, feedback))
            if output > 0:
                print('turn on heater')
            elif output < 0:
                print('turn on cooler')

        if 20 < sampling_i < 60:
            pid.SetPoint = 28  # celsius

        if 60 <= sampling_i < 80:
            pid.SetPoint = 25  # celsius

        if sampling_i >= 80:
            pid.SetPoint = 20  # celsius

        time.sleep(0.5)
        sampling_i += 1

        feedback_list.append(feedback)
        setpoint_list.append(pid.SetPoint)
        time_list.append(sampling_i)

        if sampling_i >= total_sampling:
            break

except KeyboardInterrupt:
    print("exit")


print("pid controller done.")
print("generating a report...")
time_sm = np.array(time_list)
time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)
feedback_smooth = spline(time_list, feedback_list, time_smooth)

fig1 = plt.gcf()
fig1.subplots_adjust(bottom=0.15, left=0.1)

plt.plot(time_smooth, feedback_smooth, color='red')
plt.plot(time_list, setpoint_list, color='blue')
plt.xlim((0, total_sampling))
plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5))
plt.xlabel('time (s)')
plt.ylabel('PID (PV)')
plt.title('Temperature PID Controller')


plt.grid(True)
fig1.savefig('pid_temperature.png', dpi=100)
print("finish")

Save this program to a file called ch01_pid.py. Now you can this program:

$ sudo python ch01_pid.py

After executing the program, you should obtain a file called pid_temperature.png. A sample output of this file can be seen in the following figure:

Controlling room temperature using PID controller

If I don't take any action either turning on a cooler or turning on a heater, I obtain a result, shown in the following figure:

Controlling room temperature using PID controller

How does it work?

Generally speaking, this program combines our two topics: reading current temperature through DHT-22 and implementing a PID controller. After measuring the temperature, we send this value to the PID controller program. The output of PID will take a certain action. In this case, it will turn on cooler and heater machines.

Summary

In this chapter, we have reviewed some basic statistics and explored various Python libraries related to statistics and data science. We also learned about several IoT device platforms and how to sense and actuate.

For the last topic, we deployed a PID controller as a study sample how to integrate a controller system on an IoT project. In the following chapter, we will learn how to build a decision system for our IoT project.

References

The following is a list of recommended books from which you can learn more about the topics in this chapter:

  1. Richard D. De Veaux, Paul F. Velleman, and David E. Bock, Stats Data and Models, 4th Edition, 2015, Pearson Publishing.
  2. Sheldon M. Ross, Introductory Statistics, 3rd Edition, Academic Press, 2010.
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to extract and analyse data from physical devices and build smart IoT projects
  • Master the skills of building enticing projects such as a neural network autonomous car, computer vision through a camera, and cloud-based IoT applications
  • This project-based guide leverages revolutionary computing chips such as Raspberry Pi, Arduino, and so on

Description

Internet of Things (IoT) is a groundbreaking technology that involves connecting numerous physical devices to the Internet and controlling them. Creating basic IoT projects is common, but imagine building smart IoT projects that can extract data from physical devices, thereby making decisions by themselves. Our book overcomes the challenge of analyzing data from physical devices and accomplishes all that your imagination can dream up by teaching you how to build smart IoT projects. Basic statistics and various applied algorithms in data science and machine learning are introduced to accelerate your knowledge of how to integrate a decision system into a physical device. This book contains IoT projects such as building a smart temperature controller, creating your own vision machine project, building an autonomous mobile robot car, controlling IoT projects through voice commands, building IoT applications utilizing cloud technology and data science, and many more. We will also leverage a small yet powerful IoT chip, Raspberry Pi with Arduino, in order to integrate a smart decision-making system in the IoT projects.

Who is this book for?

If you are hobbyist who is keen on making smart IoT projects, then this book is for you. You should have a basic knowledge of Python.

What you will learn

  • Implement data science in your IoT projects and build a smart temperature controller
  • Create a simple machine learning application and implement decision system concepts
  • Develop a vision machine using OpenCV
  • Build a robot car with manual and automatic control
  • Implement speech modules with your own voice commands for IoT projects
  • Connect IoT to a cloud-based server

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 30, 2016
Length: 258 pages
Edition : 1st
Language : English
ISBN-13 : 9781786466518
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 30, 2016
Length: 258 pages
Edition : 1st
Language : English
ISBN-13 : 9781786466518
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Smart Internet of Things Projects
€32.99
Practical Internet of Things Security
€36.99
Internet of Things with Python
€41.99
Total 111.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Making Your IoT Project Smart Chevron down icon Chevron up icon
2. Decision System for IoT Projects Chevron down icon Chevron up icon
3. Building Your Own Machine Vision Chevron down icon Chevron up icon
4. Making Your Own Autonomous Car Robot Chevron down icon Chevron up icon
5. Building Voice Technology on IoT Projects Chevron down icon Chevron up icon
6. Building Data Science-based Cloud for IoT Projects Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(3 Ratings)
5 star 33.3%
4 star 0%
3 star 0%
2 star 66.7%
1 star 0%
ruben Feb 03, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book
Amazon Verified review Amazon
Anthony Oct 31, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Mostly, a cookbook - rather than really teaching concepts and explaining options, the focus here is on directions to wire hardware together, install and run software - fine as that, but as it becomes dated online sources are a better bet.
Amazon Verified review Amazon
Venkatesh Deekonda Nov 15, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Buy this book only if you are comfortable with technical terms related to IoT boards. No indepth explanation of concepts, lots of links provided for additional information, why would I buy your book when I can access the links? Poorly edited, one of the low quality books from packt.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.