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
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Ecuador

Standard delivery 10 - 13 business days

$19.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Ecuador

Standard delivery 10 - 13 business days

$19.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

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
$19.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
$199.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
$279.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 $ 147.97
Smart Internet of Things Projects
$43.99
Practical Internet of Things Security
$48.99
Internet of Things with Python
$54.99
Total $ 147.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela