A smart JPEG camera for home security

By in raspberry-pi    

First Prize IoT Builders Contest 2016 (IBM Watson IoT)

Screenshot 2016-11-05 18.18.12.png
Screenshot 2016-11-05 18.26.44.png
Screenshot 2016-11-05 18.28.35.png
thumb_IMG_0615_1024.jpg
Screenshot 2016-11-04 22.09.36.png
Screenshot 2016-11-04 22.35.22.png
Screenshot 2016-11-05 18.06.44.png
14877793_1118884861498137_1672939215_n.jpg

Introduction

This instructable will cover the basic steps that you need to follow to get started with open sources such as Watson nodes(Visual Recognition V3, Text To Speech) for IBM Bluemix, Node-RED, OpenCV, MQTT v3.1. MQTT(Message Queueing Telemetry Transport) is a Machine-To-Machine(M2M) or Internet of Things (IoT) connectivity protocol that was designed to be extremely lightweight and useful when low battery power consumption and low network bandwidth is at a premium. It was invented in 1999 by Dr. Andy Stanford-Clark and Arlen Nipper and is now an Oasis Standard.

I’ve already published an instructable of the Smart Gas Valve For Safety. In addition, I’m going to communicate between A Smart JPEG Camera and A Smart Gas Valve for M2M Communication by MQTT. Specifically, this instructable will cover how to code the Node-RED on Raspberry Pi2 as a MQTT client by connecting to your home wireless network and how to send sensor data. I will be using A Smart Gas Valve for M2M communication by MQTT.

Step 1: Table of Contents

  • Step 0: Introduction
  • Step 1: Table of Contents
  • Step 2: Bill of Materials
  • Step 3: Setting up the Camera & PIR Sensor with Raspberry Pi
  • Step 4: Programming NodeRED on Raspberry Pi2
  • Step 5: Setting up MQTT v3.1 on Raspberry Pi2
  • Step 6: Checking your NodeRED codes with MQTT on Raspberry Pi2
  • Step 7: Programming Python JPEG Camera
  • Step 8: Adding IBM Watson, IBM NoSQL DB, Play-Audio, and Twilio
  • Step 9: Adding autostart files for every boot
  • Step 10: Testing M2M Communication
  • Step 11: (Optional) Using OpenCV
  • Step 12: Download list
  • Step 13: List of references

Step 2: Bill of Materials

  • Wifi dongle X 1ea
  • PIR motion sensor X 1ea
  • Android smartphone’s portable battery X 2ea
  • Nod-RED software X 1ea
    • Free open source
    • Use the version pre-installed in Raspbian Jessie image since November 2015
    • Installation guide
  • MQTT v3.1 software X 1ea
    • Free open source
    • Installation guide includes at Step 5
  • NodeRED’s IBM Watson Nodes for Bluemix
    • Text to speech node X 1ea
    • Visual Recognition X 1ea
  • Speaker X 1ea
  • Minion X 1ea
    • You can easily buy it from eBay.

Step 3: Setting up the Camera & PIR Sensor with Raspberry Pi

Setting up the  Camera & PIR Sensor with Raspberry Pi
Screenshot 2016-10-29 17.50.26.png

Assembly steps for Smart JPEG Camera

(1) Connect the Raspberry Pi2 with a PIR motion sensor as shown above in the circuit diagram.

(2) Connect the PIR motion sensor with Raspberry Pi2.

  • Raspberry Pi2 PIR motion Sensor
    • 5V —————- VCC
    • GND ————- GND
    • GPIO 18 ——– OUT

(4) Assemble carefully the Pi camera with Raspberry Pi2.

(5) Connect a portable battery with Raspberry Pi2. (Use any portable battery to connect with the same size connector cable on Raspberry Pi2. )

Assembly steps for Smart Gas Valve : here

Step 4: Programming NodeRED on Raspberry Pi2

Programming NodeRED on Raspberry Pi2
581db15415be4d4ed700153d.jpeg
581db1e345bceb7607000d17.jpeg
581db2994fbadef11c001536.jpeg
581db31c4936d4c09200053f.jpeg
581db24315be4d1908000c68.jpeg
581db3dd4fbadef11c00153e.jpeg
Screenshot 2016-11-04 08.36.16.png

How to start Node-RED on web-browser.

(1) Write down command shown below to a terminal window. node-red-start

(2) You can find an IP address as below. ‘Once Node-RED has started, point a browser at http://169.254.170.40:1880’ (It depends on your IP address)

(3) Open your web browser.

(4) Copy the IP address and paste on the web browser.

(5) It will display a visual editor of Node-RED on the web browser.

(6) You can start coding with visual editor on the web browser.

(7) Try dragging & dropping any node from the left-hand side to right-hand side. It’s really easy to code. ( You can conveniently use the visual editor offline as well as online. ) Download the ‘SmartGasValve_NodeRED.txt’ file. (1) Click the number (1) at the right-hand side corner shown in NodeRED on the web browser.

(2) Click the Import button on the drop down menu.

(3) Open the Clipboard shown in the above 1st picture.

(4) Lastly, paste the given JSON format text of ‘SmartJPGCameraNoCredits_NodeRED_ver0.1.txt‘ in Import nodes editor.

Step 5: Setting up MQTT v3.1 on Raspberry Pi2

Setting up MQTT v3.1 on Raspberry Pi2
Screenshot 2016-10-25 23.12.34.png
Screenshot 2016-10-25 23.13.03.png
Screenshot 2016-10-25 23.11.12.png
Screenshot 2016-10-25 23.10.09.png

Setting up MQTT v3.1 on Raspberry Pi2

This message broker(Mosquitto) is supported by MQTT v3.1 and it is easily installed on the Raspberry Pi and somewhat less easy to configure. Next, we step through installing and configuring the Mosquitto broker. We are going to install & test the MQTT “mosquitto” on the terminal window.

curl -O http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
rm mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo curl -O http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update

Next install the broker and command line clients:

  • mosquitto – the MQTT broker (or in other words, a server)
  • mosquitto-clients – command line clients, very useful in debugging
  • python-mosquitto – the Python language bindings
sudo apt-get install mosquitto mosquitto-clients python-mosquitto

As is the case with most packages from Debian, the broker is immediately started. Since we have to configure it first, stop it.

sudo /etc/init.d/mosquitto stop

Now that the MQTT broker is installed on the Pi we will add some basic security.
Create a config file:

cd /etc/mosquitto/conf.d/

sudo nano mosquitto.conf

Let’s stop anonymous clients connecting to our broker by adding a few lines to your config file. To control client access to the broker we also need to define valid client names and passwords. Add the lines:

allow_anonymous false

password_file /etc/mosquitto/conf.d/passwd

require_certificate false

Save and exit your editor (nano in this case).
From the current /conf.d directory, create an empty password file:

sudo touch passwd

We will use the mosquitto_passwd tool to create a password hash for user pi:

sudo mosquitto_passwd -c /etc/mosquitto/conf.d/passwd pi

You will be asked to enter your password twice. Enter the password you wish to use for the user you defined.

Testing Mosquitto on Raspberry Pi

Now that Mosquitto is installed we can perform a local test to see if it is working:
Open three terminal windows. In one, make sure the Mosquitto broker is running:

mosquitto

In the next terminal, run the command line subscriber:

mosquitto_sub -v -t 'topic/test'

You should see the first terminal window echo that a new client is connected.
In the next terminal, run the command line publisher:

mosquitto_pub -t 'topic/test' -m 'helloWorld'

You should see another message in the first terminal window saying another client is connected. You should also see this message in the subscriber terminal:

topic/test helloWorld

We have shown that Mosquitto is configured correctly and we can both publish and subscribe to a topic.
When you finish testing all, let’s set up below that.

sudo /etc/init.d/mosquitto start

Step 6: Checking your NodeRED codes with MQTT on Raspberry Pi2

Checking your NodeRED codes with MQTT on Raspberry Pi2
Screenshot 2016-10-25 23.25.14.png
Screenshot 2016-11-05 20.48.11.png
Screenshot 2016-10-25 23.26.11.png
Screenshot 2016-10-25 23.26.28.png
Screenshot 2016-11-05 20.46.30.png

When you have already used the JSON format of the ‘SmartGasValve_NodeRED.txt’ on Node-RED, it’s automatically set up & coded each data. I have already set up the each data in each node.

(1) Click each node.

(2) Check information inside each node has been prefilled.

(3) Please don’t change the set data.

(The above can be customized for more advanced users.)

Step 7: Programming Python JPEG Camera

Programming Python JPEG Camera
Screenshot 2016-10-26 01.35.49.png
Screenshot 2016-10-26 00.46.23.png
Screenshot 2016-10-26 01.35.31.png
14885984_1118885038164786_1036372151_n.jpg

Programming Python JPEG Camera

First of all, you should test the camera module in the terminal window.

raspistill -o test.jpg

You should see the test.jpg in ‘/home/pi’

cd /home/pi
mkdir pythonPir
cd pythonPir
sudo nano pircameraNodeRED.py

Type the below (the enclosed file) Or Put ‘pircameraNodeRED.py’ file into ‘/home/pi/pythonPir’ folder.

import RPi.GPIO as GPIO 
import time
import picamera
import datetime 

timeFormat = 0

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)  # For M2M Communication from Gas Valve signal
GPIO.setup(18, GPIO.IN)
camera = picamera.PiCamera()

while True:
        input17 = GPIO.input(17)  #Pin number 17 activates
        input18 = GPIO.input(18)  #Pin number 18 activates
        now = datetime.datetime.now()
        timeFormat = now.strftime("%Y%m%d_%H%M_%S.%s") #To put date and time in images

        if input17 == True or input18 == True:  #If PIR Sensor detects something, the Picamera will take.
                print('Motion_Detected_%s' %timeFormat)
                camera.capture('image_%s.jpg' %timeFormat) #To take a picture

                time.sleep(1) #sleeping time 1 second

When you finish typing, you should press the keys ‘Control‘ + ‘x‘ and press ‘y‘ to save this file.

Making an image file server

cd /home/pi
mkdir camserver
sudo nano requirements.txt

Type the below (the enclosed file) Or Put ‘requirements.txt’ file into ‘/home/pi/camserver’ folder.

numpy==1.10.1
websocket-client==0.35.0
websocket-server==0.4
ibmiotf==0.2.3
pip install --user -r requirements.txt

Execute an image file server in /home/pi/ below.

cd /home/pi
python -m SimpleHTTPServer 7000

Step 8: Adding IBM Watson, IBM NoSQL DB, Play-Audio, and Twilio

Adding IBM Watson, IBM NoSQL DB, Play-Audio, and Twilio
Screenshot 2016-11-04 08.35.52.png
Screenshot 2016-11-04 08.36.16.png
Screenshot 2016-11-04 08.33.28.png
Screenshot 2016-11-04 08.35.43.png

Searching the Nodes

Node-RED comes with a core set of useful nodes, but there are a growing number of additional nodes available for installing from both the Node-RED project as well as the wider community. You can search for available nodes in the Node-RED library or on the npm repository.

  • For example, we are going to search Twilio at the npm web. Click here.
  • Then, we are going to install Twilio on Raspberry pi.

Installing npm packaged node

To add additional nodes you must first install the npm tool, as it is not included in the default installation. The following commands install npm and then upgrade it to the latest 2.x version.

sudo apt-get update
sudo apt-get install npm
sudo npm install -g npm@2.x
hash -r
cd /home/pi/.node-red
  • For example, ‘npm install node-red-{example node name}’
  • Copy the ‘npm install node-red-node-twilio’ from the npm web. Paste it on a terminal window.
  • Ex: node-red-node-watson, node-red-contrib-play-audio, node-red-dashboard, and node-red-node-pidcontrol.
npm install node-red-node-twilio
  • You will need to restart Node-RED for it to pick-up the new nodes.
node-red-stop

node-red-start
  • Close your web browser and reopen the web browser.

Step 9: Adding autostart files for every boot.

Adding autostart files for every boot.

How to make autostart files at every boot.

  • Mosquitto
cd /etc/xdg/autostart/
sudo nano flyMosquitto.desktop

Type the below (this will enclose the file) Or Put ‘flyMosquitto.desktop’ file into autostart folder.

[Desktop Entry] 
Type=Application
Name=flyMosquitto
Comment=Fly my mosquitto
Exec=cd /etc/mosquitto/conf.d/
Exec=mosquitto
  • Node-RED
sudo systemctl enable nodered.service
  • Python JPEG Camera
cd /etc/xdg/autostart/
sudo nano pircameraNodeRED.desktop

Type the description below or put the ‘pircameraNodeRED.desktop’ file into /etc/xdg/autostart/ folder.

[Desktop Entry]
Type=Application
Name=pircameraNodeRED.py
Comment=Start my security camera
NoDisplay=false
Exec=python /home/pi/pythonPir/pircameraNodeRED.py
NotShowIn=GNOME;KDE;XFCE;
Name[en_US]=pircamera.py
  • Image file Server
cd /etc/xdg/autostart/
sudo nano imageFileServer.desktop

Type the description below or put the ‘imageFileServer.desktop’ file into /etc/xdg/autostart/ folder.

[Desktop Entry]
Type=Application 
Name=imageFileServer 
Comment=Start an image file server 
NoDisplay=false 
Exec=cd /home/pi 
Exec=python -m SimpleHTTPServer 7000

Step 10: Testing M2M Communication.

Testing M2M Communication.
Screenshot 2016-10-29 18.29.58.png
IMG_0395.JPG
IMG_0400.JPG

Importing the enclosed files in each NodeRED.

(1) Using a smart JPEG camera

Import the ‘M2M_SmartJPGCamera.txt‘ into the NodeRED of the smart JPEG camera.

(2) Using a smart gas valve

Import the ‘M2M_SmartGasValve.txt‘ into the NodeRED of the smart gas valve.

(3) Check an IP address of the smart gas valve in the Raspberry Pi2.

Type ‘ifconfig’ on a terminal window as shown below.

ifconfig

When you see the IP address, copy the IP address in a terminal window.

(4) Put the IP address into the MQTT node in other Raspberry Pi2.

  1. Click the MQTT node.
  2. Put the IP address into Server.

Step 11: (Optional) Using OpenCV

(Optional) Using OpenCV
Screenshot 2016-11-05 18.11.14.png

Installing & Using OpenCV on Raspberry Pi2

We have already used the IBM Watson Visual Recognition. Watson Visual Recognition is very excellent whereas we can’t use it without connecting wifi. OpenCV is possible to use without internet connection but It’s not very easy for a beginner to install & code into OpenCV. So, I’m going to install the OpenCV.

  • Download ‘opencv-3.1.0.zip from opecv.org
  • Install dependencies
sudo apt-get update
sudo apt-get install build-essential
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev python-dev python-numpy libjpeg-dev libpng-dev libtiff-dev libjasper-dev
  • (Optional) Install OpenCV 2
sudo apt-get install python-opencv
  • Install OpenCV 3
unzip ~/Downloads/opencv-3.1.0.zip
cd opencv-3.1.0/
mkdir build
cd build/
cmake -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTS=NO -DBUILD_PERF_TESTS=NO ..
make -j3
sudo make install
sudo ldconfig
  • Check which version of OpenCV you have in Python
python
import cv2
cv2.__version__
  • Run the simple face detect sample, and look at its code to see how it works:
  • Before, you should connect an USB-cam with Raspberry Pi2
cd /home/pi
cd opencv-3.1.0
python ./facedetect.py
Advertisements

PID Control For CPU Temperature of Raspberry Pi

[ PID Control For CPU Temperature of Raspberry Pi ]

By in raspberry-pi

PID Control For CPU Temperature of Raspberry Pi
2
3
4
5
6
7

Introduction

My motivation for PID Control For CPU Temperature of Raspberry Pi came for many reasons such as very hot CPU, very noisy fan’s sound and fast battery consumption because the hot CPU makes the system really unstable while using Raspberry Pi for a long time. So, I have optimized the failing by using PID node on Node-RED. It’s visually helpful for a trainee to understand the PID control system for an educational purpose.

This will cover the basic steps that you need to follow to get started with open sources like PID node, MQTT node in the Node-RED. Also, it’s really painful and hard to tune 3 gains like KP, KI, and KD as manual tuning(Trial and error) method. There are many tuning methods such as Manual tuning, Ziegler–Nichols, Tyreus Luyben, Cohen–Coon, Åström-Hägglund and Software tools such as Simulink in Matlab or Excel PID Simulator (enclosed). I’ve already provided my source codes in the Download List but If you use a different fan, you should tune PID gains because most physical fan’s characteristics are different. You can get more information from the linked web (PID controller).

MQTT(Message Queueing Telemetry Transport) is a Machine-To-Machine(M2M) or Internet of Things (IoT) connectivity protocol that was designed to be extremely lightweight and useful when low battery power consumption and low network bandwidth is at a premium. It was invented in 1999 by Dr. Andy Stanford-Clark and Arlen Nipper and is now an Oasis Standard. I’ve already published about how to approach the MQTT below the linked webs.

http://www.instructables.com/id/Smart-JPEG-Camera-for-Home-Security/

http://www.instructables.com/id/Smart-Gas-Valve-Checker-for-Home-Safety/

Step 1: Table of Contents

Step 0: Introduction

Step 1: Table of Contents

Step 2: Bill of Materials

Step 3: Setting up an acrylic clear case, a fan with Raspberry Pi

Step 4: Programming NodeRED on Raspberry Pi2

Step 5: Setting up MQTT v3.1 on Raspberry Pi2

Step 6: Checking your NodeRED codes with MQTT on Raspberry Pi2

Step 7: Adding & Setting up PID node, Dashboard on Raspberry Pi2

Step 8: Using a dashboard for PID control

Step 9: Tuning PID controller

Step 10: Download list

Step 11: List of references

Step 2: Bill of Materials

Step 3: Setting up an acrylic clear case with a circuited fan with Raspberry Pi

8
9
10
11

Assembly steps

(1) I suggest you should use a breadboard before soldering and wiring all.

(2) Connect the Raspberry Pi2 with a PNP 1015 transistor, a fan, and a variable 102(1k) resistor as shown above in the circuit diagram.

(3) I used a glue gun to attach with the clear case.

(4) Lastly, connect a portable battery with Raspberry Pi2. (Use any portable battery to connect with the same size connector cable on Raspberry Pi2. )

Step 4: Programming NodeRED on Raspberry Pi2

12
13
14

How to start Node-RED on web-browser.

(1) Write down command shown below to a terminal window.

node-red-start

(2) You can find an IP address as below. ‘Once Node-RED has started, point a browser at http://169.254.170.40:1880’ (It depends on your IP address)

(3) Open your web browser.

(4) Copy the IP address and paste on web-browser.

(5) It will display a visual editor of Node-RED on web-browser.

(6) You can start coding with visual editor on web-browser.

(7) Try dragging & dropping any node from the left-hand side to right-hand side. It’s really easy to code. ( You can conveniently use the visual editor offline as well as online. ) Download the ‘PID_Control_For_CPU_TEM_ver0.5.txt’ file. (1) Click the number (1) at the right-hand side corner shown in NodeRED on web-browser. (2) Click the Import button on the drop down menu. (3) Open the Clipboard shown in the above 1st picture. (4) Lastly, paste the given JSON format text of ‘PID_Control_For_CPU_TEM_ver0.5.txt’ in Import nodes editor.

Step 5: Setting up MQTT v3.1 on Raspberry Pi2

Setting up MQTT v3.1 on Raspberry Pi2

This message broker(Mosquitto) is supported by MQTT v3.1 and it is easily installed on the Raspberry Pi and somewhat less easy to configure. Next we step through installing and configuring the Mosquitto broker. We are going to install & test the MQTT “mosquitto” on terminal window.

curl -O http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
rm mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d
sudo curl -O http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update

Next install the broker and command line clients:

  • mosquitto – the MQTT broker (or in other words, a server)
  • mosquitto-clients – command line clients, very useful in debugging
  • python-mosquitto – the Python language bindings
sudo apt-get install mosquitto mosquitto-clients python-mosquitto

As is the case with most packages from Debian, the broker is immediately started. Since we have to configure it first, stop it.

sudo /etc/init.d/mosquitto stop

Now that the MQTT broker is installed on the Pi we will add some basic security.

Create a config file:

cd /etc/mosquitto/conf.d/
sudo nano mosquitto.conf

Let’s stop anonymous clients connecting to our broker by adding a few lines to your config file. To control client access to the broker we also need to define valid client names and passwords. Add the lines:

allow_anonymous false
password_file /etc/mosquitto/conf.d/passwd
require_certificate false

Save and exit your editor (nano in this case).

From the current /conf.d directory, create an empty password file:

sudo touch passwd

We will to use the mosquitto_passwd tool to create a password hash for user pi:

sudo mosquitto_passwd -c /etc/mosquitto/conf.d/passwd pi

You will be asked to enter your password twice. Enter the password you wish to use for the user you defined.

Testing Mosquitto on Raspberry Pi

Now that Mosquitto is installed we can perform a local test to see if it is working: Open three terminal windows. In one, make sure the Mosquitto broker is running:

mosquitto

In the next terminal, run the command line subscriber:

mosquitto_sub -v -t 'topic/test'

You should see the first terminal window echo that a new client is connected.In the next terminal, run the command line publisher:

mosquitto_pub -t 'topic/test' -m 'helloWorld'

You should see another message in the first terminal window saying another client is connected. You should also see this message in the subscriber terminal:

topic/test helloWorld

We have shown that Mosquitto is configured correctly and we can both publish and subscribe to a topic.When you finish testing all, let’s set up below that.

sudo /etc/init.d/mosquitto start

Step 6: Checking your NodeRED codes with MQTT on Raspberry Pi2

15
16
17

1819

When you will use the JSON format of the ‘PID_Control_For_CPU_TEM_ver0.5.txt‘ on Node-RED, it’s automatically set up & coded each data. I have already set up the each data in each node.

(1) Click each node.

(2) Check information inside each node has been prefilled.

(3) Please don’t change the set data. (The above can be customized for more advanced users.)

Step 7: Adding & Setting up PID node, Dashboard on Raspberry Pi2

Searching the Nodes

Node-RED comes with a core set of useful nodes, but there are a growing number of additional nodes available for installing from both the Node-RED project as well as the wider community. You can search for available nodes in the Node-RED library or on the npm repository.

  • For example, we are going to search ‘node-red-node-pidcontrol‘ at the npm web. Click here.
  • Then, we are going to install npm package, node-red-node-pidcontrol, node-red-dashboard on Raspberry Pi.

To add additional nodes you must first install the npm tool, as it is not included in the default installation. The following commands install npm and then upgrade it to the latest 2.x version.

sudo apt-get update
sudo apt-get install npm
sudo npm install -g npm@2.x
hash -r
cd /home/pi/.node-red
  • For example, ‘npm install node-red-{example node name}’
  • Copy the ‘npm install node-red-node-pidcontrol’ from the npm web. Paste it on a terminal window.
  • Ex: node-red-dashboard, and node-red-node-pidcontrol
npm install node-red-node-pidcontrol node-red-dashboard
  • You will need to restart Node-RED for it to pick-up the new nodes.
node-red-stop
node-red-start
  • Close your web browser and reopen the web browser.

Step 8: Using a dashboard for PID control

21
22
23
24
25

The dashboard is a visual UI tool like gauge, chart. There is a basic tutorial of a Node-RED dashboard using node-red-dashboard. http://developers.sensetecnic.com/article/a-node-red-dashboard-using-node-red-contrib-ui/

How to use the dashboard on Raspberry Pi.

(1) Click the number (1) of the gauge node.

(2) Set the group property.

(3) Set the properties from (3) to (7) shown from above the picture.

(4) Click the number (8) to go the dashboard window.

(5) Press the number (9) to display the gauge on the web browser.

(6) You can see the gauge which displays ‘40.1’ from the web browser.

(7) The chart to display on the web browser is same as the gauge (1 – 9 steps).

Step 9: Tuning PID controller

26
27
screenshot-2016-11-14-03-23-03
Screenshot 2016-11-14 23.34.39.png
screenshot-2016-11-14-03-20-28
screenshot-2016-11-18-02-00-28
screenshot-2016-11-14-03-11-13
7

There are many tuning methods such as manual tuning, Ziegler–Nichols, Tyreus Luyben, Cohen–Coon, Åström-Hägglund and software tools such as Simulink in Matlab or Excel PID Simulator(enclosed). I’ve used 2 tuning methods like manual tuning, Ziegler-Nichols method and software tools such as Matlab, Simulink, and Excel. (According to Wikipedia: PID Controller)

  • Manual Tuning(Trial and error)

How do the PID parameters affect system dynamics?

We are most interested in four major characteristics of the closed-loop step response. They are

– Rise Time: the time it takes for the plant output y to rise

– Overshoot: how much the peak level is higher than the steady state, normalized against the steady – state.
– Settling Time: the time it takes for the system to converge to its steady state.

– Steady-state Error: the difference between the steady-state output and the desired output.

(NT: No definite trend. Minor change.)

How do we use the table?

Typical steps for designing a PID controller are Determine what characteristics of the system needs to be improved.

– Use KP to decrease the rise time.

– Use KD to reduce the overshoot and settling time.

– Use KI to eliminate the steady-state error.

– This works in many cases, but what would be a good starting point? What if the first parameters we choose are totally crappy? Can we find a good set of initial parameters easily and quickly?

  • Ziegler–Nichols method

– Ziegler and Nichols conducted numerous experiments and proposed rules for determining values of KP, KI, and KD based on the transient step response of a plant.

– They proposed more than one methods, but we will limit ourselves to what’s known as the first method of Ziegler-Nichols in this tutorial. It applies to plants with neither integrators nor dominant complex-conjugate poles, whose unit-step response resemble an S-shaped curve with no overshoot. This S-shaped curve is called the reaction curve. This S-shaped curve is called the reaction curve.

– The S-shaped reaction curve can be characterized by two constants, delay time L and time constant T, which are determined by drawing a tangent line at the inflection point of the curve and finding the intersections of the tangent line with the time axis and the steady-state level line.

The Ziegler-Nichols Tuning Rule Table

Using the parameters L and T, we can set the values of KP, KI, and KDaccording to the formula shown in the table above.

These parameters will typically give you a response with an overshoot about 25% and good settling time. We may then start fine-tuning the controller using the basic rules that relate each parameter to the response characteristics. KP, KI, and KD based on the transient step response of a plant.

  • PID tuning software

– Matlab: PID Controller Tuning

– Simulink: PID Controller Tuning

– Excel PID simulator

– Etc

  • PID control VS On/Off control

On/Off control: An on-off controller is the simplest form of temperature control device. The output from the device is either on or off, with no middle state. An on-off controller will switch the output only when the temperature crosses the setpoint. For heating control, the output is on when the temperature is below the setpoint, and off above setpoint. Since the temperature crosses the setpoint to change the output state, the process temperature will be cycling continually, going from below setpoint to above, and back below. In cases where this cycling occurs rapidly, and to prevent damage to contactors and valves, an on-off differential, or “hysteresis,” is added to the controller operations. This differential requires that the temperature exceeds setpoint by a certain amount before the output will turn off or on again. On-off differential prevents the output from “chattering” or making fast, continual switches if the cycling above and below the setpoint occurs very rapidly. On-off control is usually used where a precise control is not necessary, in systems which cannot handle having the energy turned on and off frequently, where the mass of the system is so great that temperatures change extremely slowly, or for a temperature alarm. One special type of on-off control used for alarm is a limit controller. This controller uses a latching relay, which must be manually reset, and is used to shut down a process when a certain temperature is reached.

PID control: This controller provides proportional with integral and derivative control, or PID. This controller combines proportional control with two additional adjustments, which helps the unit automatically compensate for changes in the system. These adjustments, integral and derivative, are expressed in time-based units; they are also referred to by their reciprocals, RESET, and RATE, respectively. The proportional, integral and derivative terms must be individually adjusted or “tuned” to a particular system using trial and error. It provides the most accurate and stable control of the three controller types, and is best used in systems which have a relatively small mass, those which react quickly to changes in the energy added to the process. It is recommended in systems where the load changes often and the controller is expected to compensate automatically due to frequent changes in setpoint, the amount of energy available, or the mass to be controlled.

IOT based home automation project

[ IOT based home automation project]

We live in an exciting time where more and more everyday items “things” are becoming smart! “Things” have sensors and can communicate to other “things” and can provide control to more “things”. The Internet of Things, IoT, is upon us in a huge way and people are rapidly inventing new gadgets that enhance our lives. The price of microcontrollers with the ability to talk over a network keeps dropping and developers can now tinker and build things inexpensively.
IoT based home automation project is done using low cost ESP8266 ESPino ESP-12 WiFi Module, It uses relays and few simple components, complete code is provided, for more details on software setup go through IoT getting started tutorial. You can control four electrical devices and also you can monitor temperature. ESP-12 is low cost module we are using here.

Block Diagram

Components Required

1. ESP-12 WiFi Module
2. LM1117-3.3V
3. Sugar Cube Relay – Qty.4
4. Resistors 10K, 1K,4.7K
5. Capacitor 1000uF, 10uF, 104 (0.1uF)
6. PBT-2 Connectors Qty. 5
7. ULN2003
8. 12V Power Supply

With advancement of Automation technology, life is getting simpler and easier in all aspects. In today’s world Automatic systems are being preferred over manual system. With the rapid increase in the number of users of internet over the past decade has made Internet a part and parcel of life, and IoT is the latest and emerging internet technology. Internet of things is a growing network of everyday object-from industrial machine to consumer goods that can share information and complete tasks while you are busy with other activities. Wireless Home Automation system(WHAS) using IoT is a system that uses computers or mobile devices to control basic home functions and features automatically through internet from anywhere around the world, an automated home is sometimes called a smart home. It is meant to save the electric power and human energy. The home automation system differs from other system by allowing the user to operate the system from anywhere around the world through internet connection.

Circuit Diagram

From the circuit diagram it is very clear that we have used few components, LM1117-3.3V is used for providing power supply to the ESP-12 WiFi Module. ULN2003 provides relay driving.

Circuits Diagram

 

IoT Based Home Automation Code

main.c

/*
 * Copyright (c) 2015, circuits4you.com
 * All rights reserved.
/* Create a WiFi access point and provide a web server on it. */

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

#include "mainPage.h"

const int Load1=16;
const int Load2=14;
const int Load3=12;
const int Load4=13;

/* Set these to your desired credentials. */
const char *ssid = "HomeServer";
const char *password = "homeautomation";

ESP8266WebServer server(80);
String L1Status,L2Status,L3Status,L4Status,Temperature;
//=======================================================================
//                    handles main page 192.168.4.1
//=======================================================================
/* Just a little test message.  Go to http://192.168.4.1 in a web browser
 * connected to this access point to see it.
 */
void handleRoot() {
  String s = MAIN_page;
  s.replace("@@L1@@", L1Status);
  s.replace("@@L2@@", L2Status);
  s.replace("@@L3@@", L3Status);
  s.replace("@@L4@@", L4Status);
  s.replace("@@TEMP@@", Temperature);
  server.send(200, "text/html", s);
}

//=======================================================================
//                    Handle Set Date/Time Settings
//=======================================================================
void handleForm() {
  String t_state = server.arg("submit");

  Temperature = String(analogRead(A0)/10);   //Do calibration here

//Change Load-1 State as per request
  if(t_state=="ON1")
  {
    L1Status="ON";
    digitalWrite(Load1, HIGH);       //Load1 Turned on
  }

  if(t_state=="OFF1")
  {
    L1Status="OFF";
    digitalWrite(Load1, HIGH);      //Load1 Turned off
  }
//Change Load-2 State as per request
  if(t_state=="ON2")
  {
    L2Status="ON";
    digitalWrite(Load2, HIGH);       //Load1 Turned on
  }

  if(t_state=="OFF2")
  {
    L2Status="OFF";
    digitalWrite(Load2, HIGH);      //Load1 Turned off
  }
//Change Load-3 State as per request
  if(t_state=="ON3")
  {
    L3Status="ON";
    digitalWrite(Load3, HIGH);       //Load1 Turned on
  }

  if(t_state=="OFF3")
  {
    L3Status="OFF";
    digitalWrite(Load3, HIGH);      //Load1 Turned off
  }
//Change Load-4 State as per request
  if(t_state=="ON4")
  {
    L4Status="ON";
    digitalWrite(Load4, HIGH);       //Load1 Turned on
  }

  if(t_state=="OFF4")
  {
    L4Status="OFF";
    digitalWrite(Load4, HIGH);      //Load1 Turned off
  }

  server.sendHeader("Location", "/");
  server.send(302, "text/plain", "Updated-- Press Back Button");  //This Line Keeps It on Same Page

  delay(500);
}
//=======================================================================
//                    Power on setup
//=======================================================================

void setup() {
  delay(1000);
  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  server.on("/", handleRoot);
  server.on("/form", handleForm);

  server.begin();
  pinMode(Load1, OUTPUT);
  pinMode(Load2, OUTPUT);
  pinMode(Load3, OUTPUT);
  pinMode(Load4, OUTPUT);
}

//=======================================================================
//                    Main Program Loop
//=======================================================================
void loop() {
  server.handleClient();
}
//=======================================================================

 

mainPage.h

const char MAIN_page[] PROGMEM = R"=====(
<HTML>
<TITLE>
REMOTE LED ON/OFF CONTROL
</TITLE>
<BODY>
<CENTER>
<FORM>
<TABLE>
<TR><TD colspan=2><B>IoT Based Home Automation System</B></TD></TR>
<TR><TD>Temp: @@TEMP@@ C</TD><TD>Load Status</TD></TR>

<TR><TD>
<INPUT TYPE=SUBMIT VALUE="ON1">
<INPUT TYPE=SUBMIT VALUE="OFF1">
</TD>
<TD>@@L1@@</TD></TR>

<TR><TD>
<INPUT TYPE=SUBMIT VALUE="ON2">
<INPUT TYPE=SUBMIT VALUE="OFF2">
</TD>
<TD>@@L2@@</TD></TR>

<TR><TD>
<INPUT TYPE=SUBMIT VALUE="ON3">
<INPUT TYPE=SUBMIT VALUE="OFF3">
</TD>
<TD>@@L3@@</TD></TR>

<TR><TD>
<INPUT TYPE=SUBMIT VALUE="ON4">
<INPUT TYPE=SUBMIT VALUE="OFF4">
</TD>
<TD>@@L4@@</TD></TR>


<TR><TD colspan=2><B><CENTER>blog.circuits4you.com</CENTER></B></TD></TR>
</TABLE>
</FORM>

</CENTER>
</BODY>
</HTML>
)=====";

 

Testing

1. Turn on the circuit
2. Turn on WiFi on your mobile or Laptop
3. Enter 192.168.4.1 Ip in browser
4. You will find this page and operate the relays
5. Connect Relay output to the electrical load

iot home automation results
Web Page in browser