Home IoT & Hardware Smart Internet of Things Projects

Smart Internet of Things Projects

By Agus Kurniawan
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Making Your IoT Project Smart
About this book
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.
Publication date:
September 2016
Publisher
Packt
Pages
258
ISBN
9781786466518

 

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:

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:

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:

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:

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:

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:

 

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:

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.

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:

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:

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:

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.

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:

You can see my wiring implementation in the following figure:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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

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:

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:

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:

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:

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.

About the Author
  • Agus Kurniawan

    Agus Kurniawan is an independent technology consultant, author, and lecturer. He has over 18 years' experience working on various software development projects, including delivering training courses and workshops, and delivering technical writing. He has done a few research activities related to wireless networking, software, and security in multiple universities. Currently, he is pursuing a Ph.D. program in Computer Science in Germany. He has previously written five books for Packt.

    Browse publications by this author
Latest Reviews (1 reviews total)
Smart Internet of Things Projects
Unlock this book and the full library FREE for 7 days
Start now