You are on page 1of 116

PLC & SCADA WIRELESS

CONTROL SYSTEM

Group Members
Muhammad Uzair Khan

ECI-IT-11-084

Nasir Taj

ECI-IT-12-009

Abdul Saboor Abbasi

ECI-IT-11-???

Bilal Ahmad

ECI-IT-11-063

Project Supervisor
Engr. Asghar Khan

DEPARTMENT OF ELECTRICAL ENGINEERING


HAMDARD UNIVERSITY KARACHI, ISLAMABAD CAMPUS

PLC & SCADA WIRELESS CONTROL


SYSTEM

Submitted By
M.Uzair Khan, Nasir Taj, A.Saboor Abbasi & Bilal Ahmad
Towards partial fulfillment of requirement for the award of degree of
Bachelors of Electrical Engineering

DEPARTMENT OF ELECTRICAL ENGINEERING


HAMDARD UNIVERSITY KARACHI, ISLAMABAD CAMPUS

CERTIFICATE
This is to certify that this project report entitled PLC & SCADA Wireless Control System by
Muhammad Uzair Khan, Nasir Taj, Abdul Saboor Abbasi and Bilal Ahmad submitted in partial
fulfillment of the Requirements for The Bachelors of Electrical Engineering from Hamdard
University Karachi, Islamabad Campus is the record of candidates own work carried out by them
under our supervision & guidance. In our opinion the work submitted has reached a level
required for being accepted for exam. The matter embodied in this project has not been
submitted to any other university or institute.

Final Grade Received

_________________________

Committee:
1. Project Supervisor
_________________________
2. Examiner 1
_________________________
3. Examiner 2
_________________________

Signature
_________________________
Signature
_________________________
Signature
_________________________

Table of Contents

List of Figures............................................................................................................................vii
List of Tables...............................................................................................................................ix
List of Abbreviations & Notations...............................................................................................x
Dedication..................................................................................................................................xii
Acknowledgements...................................................................................................................xiii
Abstract.....................................................................................................................................xiv
CHAPTER 1 INTRODUCTION

TO

PLC & SCADA.................................................................1

1.1

Programmable Logic Controller - PLC.............................................................................1

1.2

Supervisory Control & Data Acquisition - SCADA.........................................................1

1.3

Foundation........................................................................................................................2

1.4

Project Materials...............................................................................................................3

1.4.1 Block Diagram..................................................................................................................4


CHAPTER 2 THEORETICAL BACKGROUND............................................................................5
2.1

Capacitors..........................................................................................................................5

2.1.1 Function............................................................................................................................5
2.1.2 Capacitors in Parallel........................................................................................................6
2.1.3 Capacitors in Series...........................................................................................................7
2.2

Resistors............................................................................................................................7

2.2.1 Function............................................................................................................................7
2.2.2 Connecting and Soldering.................................................................................................7
2.2.3 Resistor Values The resistor color code.........................................................................7
2.2.4 Tolerance of resistors (4rth band of color code)...............................................................8
2.2.5 Power rating of resistors...................................................................................................9
2.3

Relay.................................................................................................................................9

2.3.1 Advantages of relay........................................................................................................10


2.3.2 Disadvantages of relay....................................................................................................10
iv

CHAPTER 3 METHODOLOGY.................................................................................................32
3.1

Introduction.....................................................................................................................32

3.2

Arduino Software IDE....................................................................................................32

3.3

Development...................................................................................................................33

3.3.1 Arduino Development Environment...............................................................................33


3.3.2 Writing Sketches.............................................................................................................34
3.3.3 Sketch Book....................................................................................................................37
3.4

Boards.............................................................................................................................39

CHAPTER 4 VOICE.................................................................................................................46
4.1

Microsoft Speech API v5.1 (SAPI 5.1)...........................................................................46

4.2 Speech Synthesis..................................................................................................................47


4.3 Enumerating Voices..........................................................................................................50
4.4 Making Your Computer Talk............................................................................................54
4.5 Voice Events.....................................................................................................................58
4.6 Animating Speech.............................................................................................................59
4.7 Keeping Track Of Spoken Text........................................................................................64
4.8 Speaking Dialogs..............................................................................................................67
4.9 Speech Recognition..............................................................................................................70
4.9.1 Grammars......................................................................................................................71
4.10 Continuous Dictation Recognition.................................................................................73
4.13 Command and Control Recognition...............................................................................81
CHAPTER 5 PROGRAMMING & CODING..............................................................................87
5.1

Transmitter Coding.........................................................................................................87

5.2

Receiver Coding..............................................................................................................88

CHAPTER 6 INDUSTRIAL SCOPE...........................................................................................92


APPENDICES..........................................................................................................................93
Appendix A...............................................................................................................................94
A)

ZigBee Layers.................................................................................................................94

A-i)

Physical layer..................................................................................................................94

A-ii)

MAC Layer....................................................................................................................95

A-iii) Network Layer...............................................................................................................95


v

A-iv) Application Layer............................................................................................................96


A-v) Data Link layer................................................................................................................97

BIBLIOGRAPHY......................................................................................................98

vi

List of Figures

Figure 2.1
5

Capacitor Symbol.......

Figure 2.2

Capacitor Picture Diagram 5

Figure 2.3

Different Capacitor Pictures. 6

Figure 2.4

Charging & Discharging....... 6

Figure 2.5

Resistor.. 8

Figure 2.6

Color Code..... 8

Figure 2.7

Relay Symbol.....10

Figure 2.8

Relay Picture Diagram...10

Figure 2.9

Relay Configuration...11

Figure 2.10

Relay Operation..... 11

Figure 2.11

Diode Symbol 12

Figure 2.12

LED Picture Diagram........................ 13

Figure 2.13

LED Schematic Symbol.... 13

Figure 2.14

Bridge Rectifier......... 14

Figure 2.15

Transformer............... 17

Figure 2.16

Step Down Transformer............................. 17

Figure 2.17

7812 Circuit Diagram................................ 18

Figure 2.18

7812 Pin Diagram.............................. 19

Figure 2.19

7812 in Parallel Circuit Diagram......................... 19

Figure 2.20

Arduino Uno R3 Front.............................. 20

Figure 2.21

Arduino Uno R3 Back............................. 22

Figure 2.22

Pin Configuration of ATmega 328............................ 28

Figure 2.23

FATEK PLC Structure.............................. 29

Figure 2.24

FATEK PLC with CB-22 Board........................... 30

Figure 3.1

Transmitter Circuit Diagram............................. 43

Figure 3.2

Receiver Circuit Diagram.............................. 44

Figure 3.3

PLC Connections............................... 45

Figure 4.1

Speech Test 1................................. 49

Figure 4.2

Speech Test 2................................. 50

Figure 4.3

Speech Test 3................................. 63

Figure 4.4

Speech Test 4................................. 64

Figure 4.5

Dictation Test................................. 75

List of Tables

Table 2.1

Summary of ATmega328. .. 3

List of Abbreviations & Notations

I Current

V Voltage

R Resistance

Vcc Power Supply Voltage

Vss Ground Voltage

Vee Power Supply to Control Contrast (V)

LCD Liquid Crystal Display

RD Read AC

WR Write

ADC Analog to Digital Convertor

Amp Amplifier

Sen Sensor

LDR Light Dependent Resistor

LED Light Emitting Diode

D Diode

C Capacitance

Enc Encoder

Dec Decoder

Osc Oscillator

VR Voltage Regulator

SFR Special Function Register

PLC- Programmable Logic Controller

SCADA Supervisory Control & Data Acquisition Z Impedance


Hz Hertz

Fc Carrier Frequency

GND Ground

F Farad

Ohm (Resistance Unit)

L Inductance

G Conductance

P Power

K Co-efficient

Db Decibel

Vpp Voltage peak to peak

pF Pico Farad

Amp Ampere (Current Unit)

f Frequency

KHz Kilo Hertz

Kb Kilo Byte
Mb Mega Byte

Dedication

First of all we would to like to thank Allah Almighty the most gracious and the most merciful.
Specially dedicated to our families for their support and encouragement throughout our life.

Acknowledgements

Our project has been a result of our own hard work but this project could not have become a
reality without the support and help of many of our friends and faculty members. We take this
opportunity to acknowledge their help and thank them for their good will.

We would also like to express our special thanks of gratitude to Sir Asghar Khan for his support
and conceptual help at various technical problems. The very concept of the project as well as its
realization would not have been possible without him.

Lastly we would like to thank all the faculty members of Hamdard Institute of Engineering and
Technology (HIET) for their support throughout the Degree.

Apart from our faculty members we would also like to thank our classmates and friends for being
with us in this journey and making it memorable.

Abstract

Human necessities are increasing day by day whereas the factories are running out of resources.
To meet these demands industries need to improve the quality and quantity of their production.
Programmable logic controllers (PLCs) have been used for many decades for standard control in
industrial and factory environments. Over the years, PLCs have become computational efficient
and powerful, and a robust platform with applications beyond the standard control and factory
automation. This project deals with a hardboard industry designed automatic with the help of
PLC. This project focuses on an innovative and intelligent monitoring system of process using
SCADA (Supervisory control and data acquisition).
The project design a smart wireless industrial automation system (WIAS). This is fueled by the
Need to provide supporting systems for the industry. The automation centers on recognition of
Voice commands and uses low power RF ZigBee wireless communication modules which are
Relatively cheap. The home automation system is intended to control all lights and electrical
Appliances in an industry using voice commands.
Wireless industrial automation systems have drawn considerable attentions of the researchers for
More than a decade. The major technologies used to implement these systems include PLC,
SCADA & ZigBee.
Among these technologies the PLC & SCADA based systems have become very popular because
Of its low cost and low power consumption. In this proposal ZigBee based wireless home
Automation systems have been addressed.
The work through this project covered Programmable logic controllers and automated systems,
Supervisory control and data acquisition system (SCADA), Implementation of practical setup,
Results analysis and conclusions.

1 Introduction to PLC & SCADA


C HAPTER 1
INTRODUCTION TO PLC & SCADA

.1 Programmable Logic Controller - PLC


Programmable logic controllers (PLCs) have been an integral part of factory automation and
industrial process control for decades. PLCs control a wide array of applications from simple
lighting functions to environmental systems to chemical processing plants. These systems
perform many functions, providing a variety of analog and digital input and output interfaces;
signal processing; data conversion; and various communication protocols. All of the PLC's
components and functions are centered around the controller, which is programmed for a specific
task [1].
The basic PLC module must be sufficiently flexible and configurable to meet the diverse needs
of different factories and applications. Input stimuli (either analog or digital) are received from
machines, sensors, or process events in the form of voltage or current. The PLC must accurately
interpret and convert the stimulus for the CPU which, in turn, defines a set of instructions to the
output systems that control actuators on the factory floor or in another Industrial environment.
Modern PLCs were introduced in the 1960s, and for decades the general function and signal-path
flow changed little. However, twenty-first-century process control is placing new and tougher
demands on a PLC: higher performance, smaller form factor, and greater functional flexibility.
There must be built-in protection against the potentially damaging electrostatic discharge (ESD),
electromagnetic interference and radio frequency interference (RFI/EMI), and high-amplitude
transient pulses found in the harsh industrial setting.

.2

Supervisory Control & Data Acquisition - SCADA

The term SCADA stands for Supervisory Control and Data Acquisition. A SCADA system is a
common process automation system which is used to gather data from sensors and instruments
located at remote sites and to transmit and display this data at a central site for control or
monitoring purposes. The collected data is usually viewed on one or more SCADA Host
computers located at the central or master site.
PLC & SCADA Wireless Control System

2 Introduction to PLC & SCADA

A real world SCADA system can monitor and control hundreds to hundreds of thousands of I/O
points. A typical Water SCADA application would be to monitor water levels at various water
sources like reservoirs and tanks and when the water level exceeds a preset threshold, activate
the system of pumps to move water to tanks with low tank levels.
Common analog signals that SCADA systems monitor and control are levels, temperatures,
pressures, flow rate and motor speed. Typical digital signals to monitor and control are level
switches, pressure switches, generator status, relays & motors.
There is typically another layer of equipment between the remote sensors and instruments and
the central computer. This intermediate equipment exists on the remote side and connects to the
sensors and field instruments. Sensors typically have digital or analog I/O and these signals are
not in a form that can be easily communicated over long distances. The intermediate equipment
is used to digitize then packetize the sensor signals so that they can be digitally transmitted via
an industrial communications protocol over long distances to the central site.

.3 Foundation
Home/ Industrial automation is one of the major growing industries that can change the way
people live. Some of these home/Industrial automation systems target those seeking luxury and
sophisticated home/Industrial automation platforms; others target those with special needs like
the elderly and the disabled. The aim of the reported PLC AND SCADA BASED WIRELESS
VOICE COMMANDS CONTROLLED SYSTEM is to provide those with special needs with a
system that can respond to voice commands and control the on/off status of electrical
devices/machines, such as lamps, fans, television etc., in the home/Industry. The system should
be reasonably cheap, easy to configure, and easy to run.
The proposed project is based on the concept of home/factory automation and monitoring. In this
project, we are going to develop a project basically dependent on rf tx/tx, Microcontroller, relay,
voice recognition through computer etc. Here microcontroller is the heart of this project, Firstly
the power supply of 12v DC is very essential for this set up, this power supply trigger the
microcontroller atmega328, then the controller is directly connected with device control, rf at
receiver side gives the information regarding devices that can be operated by microcontroller &
device control here acting as a switch with the help of relays.

PLC & SCADA Wireless Control System

3 Introduction to PLC & SCADA

Home/Industrial Automation industry is growing rapidly; this is fueled by provide supporting


systems for the elderly and the disabled, especially those who live alone. Coupled with this, the
world population is confirmed to be getting older. Home automation systems must comply with
the household standards and convenience of usage. This paper details the overall design of a PLC
AND SCADA BASED WIRELESS VOICE COMMANDS CONTROLLED SYSTEM which
has been built and implemented. The automation centers on recognition of voice commands and
uses low-power RF TX/Rx wireless communication modules which are relatively cheap. The
home automation system is intended to control all lights and electrical appliances in a home or
office or industry using voice commands. The system will be tested and verified.

.4 Project Materials
The project consists of the following circuits:1.
2.
3.
4.

Transmitter circuit
Receiver circuit
PLC
Relays circuit

1.1 Block Diagram

Computer
With voice
application

Computer
Scada
PLC & SCADA Wireless Control System

4 Introduction to PLC & SCADA

Interface circuit

Wireless
transmitter

Receiver and
Control circuit

Power

PLC

12Vdc

Industrial machines load controlling Circuitry

Load1

Load2

Load3

Load4

PLC & SCADA Wireless Control System

5 Theoretical Background
C HAPTER 2
THEORETICAL BACKGROUND

.1 Capacitors
Capacitors store electric charge. They are used with resistors in timing circuits because it takes
time for a capacitor to fill with charge

2.11 Function
Capacitors store electric charge. They are used with resistors in timing circuits because it takes
time for a capacitor to fill with charge. They are used to smooth varying DC supplies by acting as
a reservoir of charge. They are also used in filter circuits because capacitors easily pass AC
(changing) signals but they block DC (constant) signals.

Fig 2.1 Capacitor Symbol


Small value capacitors are un-polarized and may be connected either way round. They are not
damaged by heat when soldering, except for one unusual type (polystyrene). They have high
voltage ratings of at least 50V, usually 250V or so. It can be difficult to find the values of these
small capacitors because there are many types of them and several different labeling systems.

Fig 2.2 Capacitor Picture Diagram

PLC & SCADA Wireless Control System

6 Theoretical Background

Fig 2.3 Different Capacitors Symbols

Fig 2.4 Charging & Discharging

2.11.2

Capacitors in Parallel

Capacitors in a parallel configuration each have the same applied voltage. Their capacitances add
up. Charge is apportioned among them by size. Using the schematic diagram to visualize parallel
Plates, it is apparent that each capacitor contributes to the total surface area.

2.11.3

Capacitors in Series
PLC & SCADA Wireless Control System

7 Theoretical Background

Connected in series, the schematic diagram reveals that the separation distance, not the plate
area, adds up. The capacitors each store instantaneous charge build-up equal to that of every
other capacitor in the series. The total voltage difference from end to end is apportioned to each
capacitor according to the inverse of its capacitance. The entire series acts as a
capacitor smaller than any of its components.

.2 Resistors
2.21 Function
Resistors restrict the flow of electric current, for example a resistor is placed in series with a
light-emitting diode (LED) to limit the current passing through the LED.

2.22 Connecting and Soldering


Resistors may be connected either way round. They are not damaged by heat when soldering.

2.23 Resistor Values The resistor color code


Resistance is measured in ohms; the symbol for ohm is an omega . 1
values are often given in k

and M . 1 k

= 1000

1M

is quite small so resistor

= 1000000 .

Resistor values are normally shown using colored bands.


Each color represents a number as shown in the table.
Most resistors have 4 bands:

The first band gives the first digit.

The second band gives the second digit.

The third band indicates the number of zeros.

The fourth band is used to shows the tolerance (precision) of the resistor, this may be
ignored for almost all circuits but further details are given below.
PLC & SCADA Wireless Control System

8 Theoretical Background

Fig 2.5 Resistor


This resistor has red (2), violet (7), yellow (4 zeros) and gold bands. So its value is 270000
=270

. On circuit diagrams the

is usually omitted and the value is written 270K.

Small value resistors (less than 10 ohm)


The standard
colour code
cannot show

The Resistor
Color Code

values of less Color


than 10 . To

Number

Black

small values

Brown

two special

Red

Orange

Yellow

Green

Blue

Violet

Grey

White

show these

colors are
used for the
third band:
gold which
means 0.1
and silver
which means
0.01. The
first and
second bands
represent the
digits as normal.
For example:
red, violet, gold bands represent 27 0.1 = 2.7
green, blue, silver bands represent 56 0.01 = 0.56
PLC & SCADA Wireless Control System

9 Theoretical Background

2.24 Tolerance of resistors (4rth band of color code)


The tolerance of a resistor is shown by the fourth band of the colour code. Tolerance is the
precision of the resistor and it is given as a percentage. For example a 390

resistor with a

tolerance of 10% will have a value within 10% of 390 , between 390 - 39 = 351
39 = 429

and 390 +

(39 is 10% of 390).

A special colour code is used for the fourth band tolerance: silver 10%, gold 5%, red 2%,
brown 1%. If no fourth band is shown the tolerance is 20%.
Tolerance may be ignored for almost all circuits because precise resistor values are rarely
required.

Fig 2.6 Color Code

2.25 Power rating of resistors


Electrical energy is converted to heat when current flows through a resistor. Usually the effect is
negligible, but if the resistance is low (or the voltage across the resistor high) a large current may
pass making the resistor become noticeably warm. The resistor must be able to withstand the
heating effect and resistors have power ratings to show this.
Power ratings of resistors are rarely quoted in parts lists because for most circuits the standard
power ratings of 0.25W or 0.5W are suitable. For the rare cases where a higher power is required
it should be clearly specified in the parts list, these will be circuits using low value resistors
(less than about 300 ) or high voltages (more than 15V).
The power, P, developed in a resistor is given by:
P = I R where:

P =

or

P = V / R

power
current

developed
through

resistance

of

in
the
the

the

resistor
resistor

resistor

in
in

in

watts

(W)

amps

(A)

ohms

( )

PLC & SCADA Wireless Control System

10 Theoretical Background

V = voltage across the resistor in volts (V)

.3 Relay
A relay is an electrically operated switch. Current flowing through the coil of the relay creates a
magnetic field which attracts a lever and changes the switch contacts. The coil current can be on
or off so relays have two switch positions and they are double throw (changeover) switches.
Relays allow one circuit to switch a second circuit which can be completely separate from the
first. For example a low voltage battery circuit can use a relay to switch a 230V AC mains
circuit. There is no electrical connection inside the relay between the two circuits; the link is
magnetic and mechanical.
The coil of a relay passes a relatively large current, typically 30mA for a 12V relay, but it can be
as much as 100mA for relays designed to operate from lower voltages. Most ICs (chips) cannot
provide this current and a transistor is usually used to amplify the small IC current to the larger
value required for the relay coil. The maximum output current for the popular 555 timer IC is
200mA so these devices can supply relay coils directly without amplification.

Fig 2.7 Relay Circuit Symbol

Fig 2.8 Relay Picture Diagram

2.31 Advantages of relay


PLC & SCADA Wireless Control System

11 Theoretical Background

Relays can switch AC and DC, transistors can only switch DC.
Relays can switch high voltages, transistors cannot.
Relays are a better choice for switching large currents (> 5A).
Relays can switch many contacts at once.

2.32 Disadvantages of relay

For Relays are bulkier than transistors for switching small currents.
Relays cannot switch rapidly (except reed relays), transistors can switch many times per

second.
Relays use more power due to the current flowing through their coil.
Relays require more current than many ICs can provide, so a low power transistor
may be needed to switch the current the relay's coil.

Fig 2.9 Relay Configuration

PLC & SCADA Wireless Control System

12 Theoretical Background

Fig 2.10 Relay Operation

2.4 Microphone
In order to speak to larger groups of people, there was a desire to increase the volume of the
spoken word. The earliest known device to achieve this dates to 600 BC with the invention of
masks with specially designed mouth openings that acoustically augmented the voice in
amphitheatres. In 1665, the English physicist Robert Hooke was the first to experiment with a
medium other than air with the invention of the "lovers' telephone" made of stretched wire with a
cup attached at each end.
German inventor Johann Philipp Reis designed an early sound transmitter that used a metallic
strip attached to a vibrating membrane that would produce intermittent current. Better results
were achieved with the 'liquid transmitter' design in Scottish-American Alexander Graham Bell's
telephone of 1876 the diaphragm was attached to a conductive rod in an acid solution. These
systems, however, gave a very poor sound quality.

2.5 Diode

The most basic property of a junction diode is that it conducts an electric current in one
direction and blocks it in the other. This behavior arises from the electrical characteristics
of a junction, called a p-n junction. Fabricated within a semiconductor crystal. The most
commonly used semiconductor material is silicon. The junction diode is useful in a wide
variety of applications including the rectification of ac signals (producing dc from ac), the
detection of radio signals, the conversion of solar power to electricity, and in the
generation and detection of light. It also finds use in a variety of electronic circuits as a
switch, as a voltage reference or even as a tunable capacitor. The p-n junction is also the
basic building block of a host of other electronic devices, of which the most well-known
is the junction transistor.

In our project we have used a diode as a rectifier basically it is a full wave rectifier used
to convert ac in to dc in the power supply portion of the project.

PLC & SCADA Wireless Control System

13 Theoretical Background

Fig 2.11 Diode symbol

2.6 Light Emitting Diode


Basically, LEDs are just tiny light bulbs that fit easily into an electrical circuit. But unlike
ordinary incandescent bulbs, they don't have a filament that will burn out, and they don't get
especially hot. They are illuminated solely by the movement of electrons in a semiconductor
material, and they last just as long as a standard transistor.
A light-emitting-diode (LED) is a semiconductor diode that emits light when an electric current
is applied in the forward direction of the device, as in the simple LED circuit.

Fig 2.12 LED Picture Diagram


PLC & SCADA Wireless Control System

14 Theoretical Background

The effect is a form of electroluminescence where incoherent and narrow-spectrum light is


emitted from the p-n junction in a solid state material.

Fig 2.13 LED schematic symbol

2.7 Bridge Rectifier


Bridge rectifier is an electronic component which converts an input AC current into a DC current
as an output. Electronic devices and particularly portable electronic devices typically make the
use of alternating current to direct current adapters either as a direct source of power to charge
on-board batteries.
A bridge rectifier makes

use of four diodes in a

bridge arrangement to

achieve

rectification. It is called

because

the

entire AC wave (both

positive and negative

sections). 1.4V is used

up in the bridge rectifier

because each diode uses

0.7V when conducting

and there are always

two diodes conducting,

as shown in the diagram

below. Bridge rectifiers

are

it

uses

full-wave

rated

full-wave
rectifier

by

the

maximum current they can pass and the maximum reverse voltage they can withstand (this must
be at least three times the supply RMS voltage so the rectifier can withstand the peak voltages).
This is a widely used configuration, both with individual diodes wired as shown and with single
component bridges where the diode bridge is wired internally.

PLC & SCADA Wireless Control System

15 Theoretical Background

Fig 2.14 Bridge Rectifier


The input to the circuit is applied to the diagonally opposite corners of the network, and the
output is taken from the remaining two corners. Let us assume the transformer is working
properly and there is a positive potential at point A and a negative potential at point B.
The positive potential at point A will forward bias D3 and reverse bias D4. The negative potential
at point B will forward bias D1 and reverse bias D2. At this time D3 and D1 are forward biased
and will allow current flow to pass through them; D4 and D2 are reverse biased and will block
current flow. The path for current flow is from point B through D1, up through R L, through D3,
through the secondary of the transformer back to point B. This path is indicated by the solid
arrows. Waveforms (1) and (2) can be observed across D1 and D3.
One-half cycle later the polarity across the secondary of the transformer reverses, forward
biasing D2 and D4 and reverse biasing D1 and D3. Current flow will now be from point A
through D4, up through RL, through D2, through the secondary of T1, and back to point A. This
path is indicated by the broken arrows. Waveforms (3) and (4) can be observed across D2 and
D4. You should have noted that the current flow through R L is always in the same direction. In
flowing through RL this current develops a voltage corresponding to that shown in waveform (5).
Since current flows through the load (RL) during both half cycles of the applied voltage, this
bridge rectifier is a full-wave rectifier.

PLC & SCADA Wireless Control System

16 Theoretical Background

One advantage of a bridge rectifier over a conventional full-wave rectifier is that with a given
transformer the bridge rectifier produces a voltage output that is nearly twice that of the
conventional full-wave circuit.

2.7.1 Current Flow in the Bridge Rectifier


For both positive and negative swings of the transformer, there is a forward path through the
diode bridge. Both conduction paths cause current to flow in the same direction through the load
resistor, accomplishing full-wave rectification. While one set of diodes is forward biased, the
other set is reverse biased and effectively eliminated from the circuit.

2.7.2 Applications
The primary application of rectifiers is to derive DC power from an AC supply. Virtually all
electronics require a DC supply but mains power is AC so rectifiers find uses inside the power
supplies of virtually all electronic equipment.

2.8 Transformer
A transformer is a device that transfers electrical energy from one circuit to another through
inductively coupled electrical conductors. A changing current in the first circuit (the primary)
creates a changing magnetic field. This changing magnetic field induces a changing voltage in
the second circuit (the secondary). This effect is called mutual induction.
Transformers are passive electrical devices that transform alternating or intermittent electric
energy in one circuit into energy of a similar type in another circuit, commonly with altered
values of voltage and current. It typically contains two or more electrical circuits comprising
primary and secondary windings, each made of a multi-turn coil of electrical conductors with
one or more magnetic cores coupling the coils by transferring a magnetic flux there between.
Increasingly, modern day appliances are constructed using low voltage transformers for many
purposes including as lighting transformers or to supply power to electronic components.

2.8.1 How does a transformer work?

PLC & SCADA Wireless Control System

17 Theoretical Background

A transformer is based on a very simple fact about electricity: when a fluctuating electric current
flows through a wire, it generates a magnetic field (an invisible pattern of magnetism) or
"magnetic flux" all around it. The strength of the magnetism (which has the rather technical
name of magnetic flux density) is directly related to the size of the electric current. So the bigger
the current, the stronger the magnetic field. Now there's another interesting fact about electricity
too. When a magnetic field fluctuates around a piece of wire, it generates an electric current in
the wire. So if we put a second coil of wire next to the first one, and send a fluctuating electric
current into the first coil, we will create an electric current in the second wire. This is called
electromagnetic induction because the current in the first coil causes (or "induces") a current in
the second coil. The current in the first coil is usually called the primary current and the current
in the second wire is (surprise, surprise) the secondary current. What we've done here is pass an
electric current through empty space from one coil of wire to another. This phenomenon is called
electromagnetic induction. We can make electrical energy pass more efficiently from one coil to
the other by wrapping them around a soft iron bar (sometimes called a core):

Fig 2.15 Transformer


To make a coil of wire, we simply curl the wire round into loops or ("turns" as physicists like to
call them). If the second coil has the same number of turns as the first coil, the electric current in
the second coil will be virtually the same size as the one in the first coil. But (and here's the
clever part) if we have more or fewer turns in the second coil, we can make the secondary
current and voltage bigger or smaller than the primary current and voltage.

PLC & SCADA Wireless Control System

18 Theoretical Background

One important thing to note is that this trick works only if the electric current is fluctuating in
some way. In other words, you have to use a type of constantly reversing electricity called
alternating current (AC) with a transformer. Transformers do not work with direct current (DC),
where the current constantly flows in the same direction.

2.8.2 Step-down transformers


If the first coil has more turns that the second coil, the secondary voltage is smaller than the
primary voltage:

Fig 2.16 Step Down Transformer


This is called a step-down transformer. If the second coil has half as many turns as the first coil,
the secondary voltage will be half the size of the primary voltage; if the second coil has one tenth
as many turns; it has one tenth the voltage. In general:
Secondary voltage Primary voltage = Number of turns in secondary Number of turns in
primary
The current is transformed the opposite wayincreased in sizein a step-down transformer:
Secondary current Primary current = Number of turns in primary Number of turns in
secondary
So a step-down transformer with 100 coils in the primary and 10 coils in the secondary will
reduce the voltage by a factor of 10 but multiply the current by a factor of 10 at the same time.
The power in an electric current is equal to the current times the voltage (watts = volts x amps is
one way to remember this), so you can see the power in the secondary coil is theoretically the
PLC & SCADA Wireless Control System

19 Theoretical Background

same as the power in the primary coil. (In reality, there is some loss of power between the
primary and the secondary because some of the "magnetic flux" leaks out of the core; some
energy is lost because the core heats up, and so on.)
Ideal power equation
Pin = IPVP = Pout = ISVS
Ideal transformer equation

2.9

7812 Voltage Regulator

7812 is a famous IC which is being widely used in 12V voltage regulator circuits. Truly speaking
it is a complete standalone voltage regulator. We only need to use two capacitors, one on the
input and second one on the output of 7812 in order to achieve clean voltage output and even
these capacitors are optional to use. To achieve 12V 1A current, 7812 should be mounted on a
good heat sink plate. Thanks to the transistor like shape of 7812 which makes it easy to mount on
a heat sink plate. 7812 has built in over heat and short circuit protection which makes it a good
choice for making power supplies.

Fig: 2.17 7812 circuit diagram


PLC & SCADA Wireless Control System

20 Theoretical Background

In electronics markets, 7812 is sold under various names such as 7812a, 7812act, 7812t and
lm7812. All of them are almost identical with a little to no differences at all. 7812 input voltage
range is 14V to 35V. Exceeding the voltage range may damage the IC. Given bellow is 7812
pin diagram to make the pinout connections clear in case you want to do some experiments.

Fig: 2.18 7812 pin diagram


If you hold upside down (pins up) and the IC number is facing you then the left pin will be the
voltage regulator output, the center pin will be ground and the right pin will be the voltage
input pin. Under my experience, the maximum safe current you can get from one 7812 IC is
1A. If you need more power then there are a few ways to do so.
More than one 7812 can be used in parallel in order to achieve more than 1A current but output
voltage of each 7812 can slightly vary resulting in unbalanced load on all of them. This can
result in load balancing issues and can damage the IC carrying most current. However there is a
way to overcome this problem. I have given bellow a schematic diagram in which two 7812
ICs are attached together and both of them are carrying almost equal load. At least the current
difference is not too much to damage any IC.

PLC & SCADA Wireless Control System

21 Theoretical Background

Fig: 2.19 7812 in parallel circuit diagram


Please note that in this circuit diagram, I have used resistors for load balancing purpose so the
output of this voltage regulator circuit may slightly inaccurate. Both resistors should be
minimum 15 Watt or above. If you dont find such resistors in your area then you can make
them using 32 gauge or thinner copper wire. This parallel 7812 circuit will provide 12V and
approximately 2A current. You can increase number of 7812 but each additional 7812 will
require

resistor

on

its

output.

Following is the link to a simple but complete power supply circuit diagram developed using
7812.

2.10 Arduino Uno


The Arduino Uno is a microcontroller board based on the ATmega328. It has 14 digital
input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz ceramic
resonator, a USB connection, a power jack, an ICSP header, and a reset button. It contains
everything needed to support the microcontroller; simply connect it to a computer with a USB
cable or power it with an AC-to-DC adapter or battery to get started.

PLC & SCADA Wireless Control System

22 Theoretical Background

The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial driver
chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a
USB-to-serial converter.
Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to ground, making it easier
to put into DFU mode Revision 3 of the board has the following new features:
1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins
placed near to the RESET pin, the IOREF that allow the shields to adapt to the voltage provided
from the board. In future, shields will be compatible with both the board that uses the AVR,
which operates with 5V and with the Arduino Due that operates with 3.3V. The second one is a
not connected pin that is reserved for future purposes.
Stronger RESET circuit.
At mega 16U2 replace the 8U2.
"Uno" means one in Italian and is named to mark the upcoming release of Arduino 1.0. The Uno
and version 1.0 will be the reference versions of Arduino, moving forward. The Uno is the latest
in a series of USB Arduino boards, and the reference model for the Arduino platform;

PLC & SCADA Wireless Control System

23 Theoretical Background

Fig 2.20 Arduino Uno R3 Front

Fig: 2.21 Arduino Uno R3 Back

2.10.1 Synopsis
Table 2.1 Summary of ATmega328
Microcontroller

ATmega328

Operating Voltage

5V

Input Voltage (recommended)

7-12V

Input Voltage (limits)

6-20V

Digital I/O Pins

14 (of which 6 provide PWM output)

Analog Input Pins

DC Current per I/O Pin

40 mA

DC Current for 3.3V Pin

50 mA

Flash Memory

32 KB (ATmega328) of which 0.5 KB used by boot loader

SRAM

2 KB (ATmega328)
PLC & SCADA Wireless Control System

24 Theoretical Background

EEPROM

1 KB (ATmega328)

Clock Speed

16 MHz

2.10.2 Schematic & Reference Design


The Arduino reference design can use an Atmega8, 168, or 328, Current models use
an ATmega328, but an Atmega8 is shown in the schematic for reference. The pin configuration is
identical on all three processors.

2.10.3 Power
The Arduino Uno can be powered via the USB connection or with an external power supply. The
power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery.
The adapter can be connected by plugging a 2.1mm center-positive plug into the board's power
jack. Leads from a battery can be inserted in the GND and Vin pin headers of the POWER
connector.
The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V,
however, the 5V pin may supply less than five volts and the board may be unstable. If using
more than 12V, the voltage regulator may overheat and damage the board. The recommended
range is 7 to 12 volts.
The power pins are as follows:
VIN. The input voltage to the Arduino board when it's using an external power source (as
opposed to 5 volts from the USB connection or other regulated power source). You can supply
voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.
5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied
with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of
the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can
damage your board. We don't advise it.
PLC & SCADA Wireless Control System

25 Theoretical Background

3V3. A 3.3 volt supply generated by the on-board regulator. Maximum current draw is 50 mA.
GND. Ground pins.
IOREF. This pin on the Arduino board provides the voltage reference with which the
microcontroller operates. A properly configured shield can read the IOREF pin voltage and select
the appropriate power source or enable voltage translators on the outputs for working with the
5V or 3.3V.

2.10.4 Memory
The ATmega328 has 32 KB (with 0.5 KB used for the boot loader). It also has 2 KB of SRAM
and 1 KB of EEPROM (which can be read and written with the EEPROM library).

2.10.5 Input and Output


Each of the 14 digital pins on the Uno can be used as an input or output,
using pinMode(), digitalWrite(), anddigitalRead() functions. They operate at 5 volts. Each pin
can provide or receive a maximum of 40 mA and has an internal pull-up resistor (disconnected
by default) of 20-50k Ohms. In addition, some pins have specialized functions:
Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins
are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.
External Interrupts: 2 and 3. These pins can be configured to trigger an interrupt on a low value,
a rising or falling edge, or a change in value. See the attachInterrupt() function for details.
PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite() function.
SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using
the SPI library.
LED: 13. There is a built-in LED connected to digital pin 13. When the pin is HIGH value, the
LED is on, when the pin is LOW, it's off.
The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10 bits of resolution
(i.e. 1024 different values). By default they measure from ground to 5 volts, though is it possible
PLC & SCADA Wireless Control System

26 Theoretical Background

to change the upper end of their range using the AREF pin and the analog Reference() function.
Additionally, some pins have specialized functionality:
TWI: A4 or SDA pin and A5 or SCL pin. Support TWI communication using the Wire library.
There are a couple of other pins on the board:
AREF. Reference voltage for the analog inputs. Used with analogReference().
Reset. Bring this line LOW to reset the microcontroller. Typically used to add a reset button to
shields which block the one on the board.
See also the mapping between Arduino pins and ATmega328 ports. The mapping for the
Atmega8, 168, and 328 is identical.

2.10.6 Communication
The Arduino Uno has a number of facilities for communicating with a computer, another
Arduino, or other microcontrollers. The ATmega328 provides UART TTL (5V) serial
communication, which is available on digital pins 0 (RX) and 1 (TX). An ATmega16U2 on the
board channels this serial communication over USB and appears as a virtual com port to
software on the computer. The '16U2 firmware uses the standard USB COM drivers, and no
external driver is needed. However, on Windows, an .inf file is required. The Arduino software
includes a serial monitor which allows simple textual data to be sent to and from the Arduino
board. The RX and TX LEDs on the board will flash when data is being transmitted via the USBto-serial chip and USB connection to the computer (but not for serial communication on pins 0
and 1).
A Software Serial library allows for serial communication on any of the Uno's digital pins.
The ATmega328 also supports I2C (TWI) and SPI communication. The Arduino software
includes a Wire library to simplify use of the I2C bus; see the documentation for details. For SPI
communication, use the SPI library.

2.10.7 Programming

PLC & SCADA Wireless Control System

27 Theoretical Background

The Arduino Uno can be programmed with the Arduino software (download). Select "Arduino
Uno from the Tools > Board menu (according to the microcontroller on your board). For details,
see the reference and tutorials.
The ATmega328 on the Arduino Uno comes pre burned with a boot loader that allows you to
upload new code to it without the use of an external hardware programmer. It communicates
using the original STK500 protocol (reference, C header files).
You can also bypass the boot loader and program the microcontroller through the ICSP (InCircuit Serial Programming) header using Arduino ISP or similar; see these instructions for
details.
The ATmega16U2 (or 8U2 in the rev1 and rev2 boards) firmware source code is available.
The ATmega16U2/8U2 is loaded with a DFU boot loader, which can be activated by:
On Rev1 boards: connecting the solder jumper on the back of the board (near the map of Italy)
and then resetting the 8U2.
On Rev2 or later boards: there is a resistor that pulling the 8U2/16U2 HWB line to ground,
making it easier to put into DFU mode.
You can then use Atmel's FLIP software (Windows) or the DFU programmer (Mac OS X and
Linux) to load a new firmware. Or you can use the ISP header with an external programmer
(overwriting the DFU boot loader). See this user-contributed tutorial for more information.

2.10.8 Automatic (Software) Reset


Rather than requiring a physical press of the reset button before an upload, the Arduino Uno is
designed in a way that allows it to be reset by software running on a connected computer. One of
the hardware flow control lines (DTR) of theATmega8U2/16U2 is connected to the reset line of
the ATmega328 via a 100 Nano farad capacitor. When this line is asserted (taken low), the reset
line drops long enough to reset the chip. The Arduino software uses this capability to allow you
to upload code by simply pressing the upload button in the Arduino environment. This means
that the boot loader can have a shorter timeout, as the lowering of DTR can be well-coordinated
with the start of the upload.
PLC & SCADA Wireless Control System

28 Theoretical Background

This setup has other implications. When the Uno is connected to either a computer running Mac
OS X or Linux, it resets each time a connection is made to it from software (via USB). For the
following half-second or so, the boot loader is running on the Uno. While it is programmed to
ignore malformed data (i.e. anything besides an upload of new code), it will intercept the first
few bytes of data sent to the board after a connection is opened. If a sketch running on the board
receives one-time configuration or other data when it first starts, make sure that the software with
which it communicates waits a second after opening the connection and before sending this data.
The Uno contains a trace that can be cut to disable the auto-reset. The pads on either side of the
trace can be soldered together to re-enable it. It's labeled "RESET-EN". You may also be able to
disable the auto-reset by connecting a 110 ohm resistor from 5V to the reset line; see this forum
thread for details.

2.10.9 USB Overcurrent Protection


The Arduino Uno has a resettable poly fuse that protects your computer's USB ports from shorts
and overcurrent. Although most computers provide their own internal protection, the fuse
provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse
will automatically break the connection until the short or overload is removed.

2.10.10 Physical Characteristics


The maximum length and width of the Uno PCB are 2.7 and 2.1 inches respectively, with the
USB connector and power jack extending beyond the former dimension. Four screw holes allow
the board to be attached to a surface or case. Note that the distance between digital pins 7 and 8
is 160 mil (0.16"), not an even multiple of the 100 mil spacing of the other pins.

PLC & SCADA Wireless Control System

29 Theoretical Background

Fig: 2.22 Pin Configuration of ATmega 328

2.11 FATEK PLC:


The FATEK FBS Series PLC is a new generation of micro PLC equipped with excellent
functions comparable to medium or large PLC, with up to five communication ports. The
maximum I/O numbers are 256 points for Digital Input (DI) and Digital Output (DO), 64 words
for Numeric Input (NI) and Numeric Output (NO). The Main Units of FBS are available in three
types: MA (Economy Type), MC (High-Performance Type), and MN (High-Speed NC Type).
With the combination of I/O point ranges from 10 to 60, a total of 17 models are available.
Fourteen DI/DO and 12 NI/NO models are available for Expansion Units/Modules. With
interface options in RS232, RS485, USB and Ethernet, the communication peripherals are
available with 14 boards and modules. The various models are described in the following:

2.11.1 Appearance of Main Unit


All the Main Units of FBS-PLC have the same physical structure. The only difference is the case
width. There are four different case sizes, which are 60mm, 90mm, 130mm, and 175mm. The
figure below will use the Main Unit case of the FBS-24MC as an example for illustration:

PLC & SCADA Wireless Control System

30 Theoretical Background

Fig 2.23 FATEK PLC Structure

PLC & SCADA Wireless Control System

31 Theoretical Background

Fig 2.24 FATEK PLC with CB-22 Board

2.11.2 FATEK PLC Specifications


1) 35mm-width DIN RAIL
2) DIN RAIL tab
3) Hole for screw fixation (4.52)
4) Terminals of 24VDC power input and digital input (Pitch 7.62mm)
5) Terminals of main power input and digital output (Pitch 7.62mm)
6) Standard cover plate (without communication board)
7) Cover plate of built-in communication port (Port 0)
8) Indicators for transmit (TX) and receive (RX) status of built-in communication port (Port0).
9) Indicator for Digital Input (Xn).
10) Indicator for Digital Output (Yn).
11) Indicator for system status (POW, RUN, ERR).

PLC & SCADA Wireless Control System

32 Theoretical Background

12) I/O output expansion header cover [units of 20 points or beyond only], with esthetic purpose
and capable of securing expansion cable.
13) FBS-CB22 Communication Board (CB).
14) FBS-CB22 CB cover plate (each CB has its own specific cover plate)

PLC & SCADA Wireless Control System

33 Industrial Scope
C HAPTER 3
METHODOLOGY

3.1 Introduction
In our project we have used Arduino IDE for Atmega328 programming, and Eagle for PCB
designing. Before we explain our project code lets first discus some basic principles of the
Arduino IDE.

.2 Arduino Software IDE


The Arduino integrated development environment (IDE) is a cross-platform application written
in Java, and is derived from the IDE for the Processing programming language and
the Wiring projects. It is designed to introduce programming to artists and other newcomers
unfamiliar with software development. It includes a code editor with features such as syntax
highlighting, brace matching, and automatic indentation, and is also capable of compiling and
uploading programs to the board with a single click. A program or code written for Arduino is
called a "sketch".
Arduino programs are written in C or C++. The Arduino IDE comes with a software
library called "Wiring" from the original Wiring project, which makes many common
input/output operations much easier. Users only need define two functions to make a
runnable cyclic executive program:

setup(): a function run once at the start of a program that can initialize settings

loop(): a function called repeatedly until the board powers off

A typical first program for a microcontroller simply blinks an LED on and off. In the Arduino
environment, the user might write a program like this:
#define LED_PIN 13
void setup () {
pinMode (LED_PIN, OUTPUT); // Enable pin 13 for digital output
}

PLC & SCADA Wireless Control System

34 Industrial Scope
void loop () {
digitalWrite (LED_PIN, HIGH); // Turn on the LED
delay (1000); // Wait one second (1000 milliseconds)
digitalWrite (LED_PIN, LOW); // Turn off the LED
delay (1000); // Wait one second
}

It is a feature of most Arduino boards that they have an LED and load resistor connected
between pin 13 and ground; a convenient feature for many simple tests. The previous code would
not be seen by a standard C++ compiler as a valid program, so when the user clicks the "Upload
to I/O board" button in the IDE, a copy of the code is written to a temporary file with an extra
include header at the top and a very simple main() function at the bottom, to make it a valid C++
program.
The Arduino IDE uses the GNU tool chain and AVR Libc to compile programs, and uses avrdude
to upload programs to the board.
As the Arduino platform uses Atmel microcontrollers, Atmel's development environment, AVR
Studio or the newer Atmel Studio, may also be used to develop software for the Arduino.

.3 Development
Arduino is open source hardware: the Arduino hardware reference designs are distributed under
a Creative Commons Attribution Share-Alike 2.5 license and are available on the Arduino Web
site. Layout and production files for some versions of the Arduino hardware are also available.
The source code for the IDE is available and released under the GNU General Public License,
version 2.
Although the hardware and software designs are freely available under copy left licenses, the
developers have requested that the name "Arduino" be exclusive to the official product and not
be used for derivative works without permission. The official policy document on the use of the
Arduino name emphasizes that the project is open to incorporating work by others into the
official product. Several Arduino-compatible products commercially released have avoided the
"Arduino" name by using "-duino" name variants.

3.31.1

Arduino Development Environment


PLC & SCADA Wireless Control System

35 Industrial Scope

The Arduino development environment contains a text editor for writing code, a message area, a
text console, a toolbar with buttons for common functions, and a series of menus. It connects to
the Arduino hardware to upload programs and communicate with them.

3.31.2 Writing Sketches


Software written using Arduino are called sketches. These sketches are written in the text editor.
Sketches are saved with the file extension .ino. It has features for cutting/pasting and for
searching/replacing text. The message area gives feedback while saving and exporting and also
displays errors. The console displays text output by the Arduino environment including complete
error messages and other information. The bottom right-hand corner of the window displays the
current board and serial port. The toolbar buttons allow you to verify and upload programs,
create, open, and save sketches, and open the serial monitor.
NB: Versions of the IDE prior to 1.0 saved sketches with the extension .pde. It is possible to
open these files with version 1.0, you will be prompted to save the sketch with the .ino extension
on save.
Verify
Checks your code for errors.
Upload
Compiles your code and uploads it to the Arduino I/O board.
See uploading below for details.
Note: If you are using an external programmer, you can hold down the "shift"
key on your computer when using this icon. The text will change to "Upload
using Programmer"
New
Creates a new sketch.
Open
Presents a menu of all the sketches in your sketchbook. Clicking one will open
it within the current window.
Note: due to a bug in Java, this menu doesn't scroll; if you need to open a
sketch late in the list, use the File | Sketchbook menu instead.

PLC & SCADA Wireless Control System

36 Industrial Scope

Save
Saves your sketch.
Serial

Monitor

Opens the serial monitor.


Additional commands are found within the five menus: File, Edit, Sketch, Tools, and Help. The
menus are context sensitive which means only those items relevant to the work currently being
carried out are available.
Edit
Copy for Forum
Copies the code of your sketch to the clipboard in a form suitable for posting to the forum,
complete with syntax coloring.
Copy as HTML
Copies the code of your sketch to the clipboard as HTML, suitable for embedding in web pages.
Sketch
Verify/Compile
Checks your sketch for errors.
Show Sketch Folder
Opens the current sketch folder.
Add File...
Adds a source file to the sketch (it will be copied from its current location). The new file appears
in a new tab in the sketch window. Files can be removed from the sketch using the tab menu.
Import Library
Adds a library to your sketch by inserting #include statements at the start of your code. For more
details, see libraries below. Additionally, with version 1.0.5 and later of the IDE, you can import
a library from a .zip file.
Tools
Auto Format

PLC & SCADA Wireless Control System

37 Industrial Scope

This formats your code nicely: i.e. indents it so that opening and closing curly braces line up,
and that the statements inside curly braces are indented more.
Archive Sketch
Archives a copy of the current sketch in .zip format. The archive is placed in the same directory
as the sketch.
Board
Select the board that you're using. See below for descriptions of the various boards.
Serial Port
This menu contains all the serial devices (real or virtual) on your machine. It should
automatically refresh every time you open the top-level tools menu.
Programmer
For selecting a hardware programmer when programming a board or chip and not using the
onboard USB-serial connection. Normally you won't need this, but if you're burning a boot
loader to a new microcontroller, you will use this.
Burn-Boot loader
the items in this menu allow you to burn a boot loader onto the microcontroller on an Arduino
board. This is not required for normal use of an Arduino board but is useful if you purchase a
new ATmega microcontroller (which normally come without a boot loader). Ensure that you've
selected the correct board from the Boards menu before burning the boot loader.

3.31.3

Sketch Book

The Arduino environment uses the concept of a sketchbook: a standard place to store your
programs (or sketches). The sketches in your sketchbook can be opened from the File >
Sketchbook menu or from the Open button on the toolbar. The first time you run the Arduino
software, it will automatically create a directory for your sketchbook. You can view or change
the location of the sketchbook location from with the Preferences dialog.
'''Beginning with version 1.0, files are saved with an .ino file extension. Previous versions use the
.pde extension. You may still open .pde named files in version 1.0 and later, the software will
automatically rename the extension to .ino.

3.3.3.1 Tabs, Multiple Files, and Compilation

PLC & SCADA Wireless Control System

38 Industrial Scope

Allows you to manage sketches with more than one file (each of which appears in its own tab).
These can be normal Arduino code files (no extension), C files (.c extension), C++ files (.cpp), or
header files (.h).

3.3.3.2 Uploading
Before uploading your sketch, you need to select the correct items from the Tools >
Board and Tools > Serial Port menus. The boards are described below. On the Mac, the serial
port is probably something like /dev/tty.usbmodem241 (for a Uno or Mega2560 or Leonardo)
or /dev/tty.usbserial-1B1 (for

Duemilanove

or

earlier

USB

board),

or

/dev

/tty.

USA19QW1b1P1.1 (for a serial board connected with a Keyspan USB-to-Serial adapter).


On Windows, it's probably COM1 or COM2 (for a serial board) or COM4, COM5, COM7, or
higher (for a USB board) - to find out, you look for USB serial device in the ports section of the
Windows Device Manager. On Linux, it should be /dev/ttyUSB0/dev/ttyUSB1 or similar.
Once you've selected the correct serial port and board, press the upload button in the toolbar or
select the Upload item from the File menu. Current Arduino boards will reset automatically and
begin the upload. With older boards (pre-Diecimila) that lack auto-reset, you'll need to press the
reset button on the board just before starting the upload. On most boards, you'll see the RX and
TX LEDs blink as the sketch is uploaded. The Arduino environment will display a message when
the upload is complete, or show an error.
When you upload a sketch, you're using the Arduino boot loader, a small program that has been
loaded on to the microcontroller on your board. It allows you to upload code without using any
additional hardware. The boot loader is active for a few seconds when the board resets; then it
starts whichever sketch was most recently uploaded to the microcontroller. The boot loader will
blink the on-board (pin 13) LED when it starts (i.e. when the board resets).

3.3.3.3 Libraries
Libraries provide extra functionality for use in sketches, e.g. working with hardware or
manipulating data. To use a library in a sketch, select it from the Sketch > Import Library menu.
This will insert one or more #include statements at the top of the sketch and compile the library
PLC & SCADA Wireless Control System

39 Industrial Scope

with your sketch. Because libraries are uploaded to the board with your sketch, they increase the
amount of space it takes up. If a sketch no longer needs a library, simply delete its #include
statements from the top of your code.
There is a list of libraries in the reference. Some libraries are included with the Arduino software.
Others can be downloaded from a variety of sources. Starting with version 1.0.5 of the IDE, you
do can import a library from a zip file and use it in an open sketch. See these instructions for
installing a third-party library.

3.3.3.4 Third-Party Hardware


Support for third-party hardware can be added to the hardware directory of your sketchbook
directory. Platforms installed there may include board definitions (which appear in the board
menu), core libraries, boot loaders, and programmer definitions. To install, create
the hardware directory, then unzip the third-party platform into its own sub-directory. (Don't use
"arduino" as the sub-directory name or you'll override the built-in Arduino platform.) To
uninstall, simply delete its directory.

3.3.3.5 Serial Monitor


Displays serial data being sent from the Arduino board (USB or serial board). To send data to the
board, enter text and click on the "send" button or press enter. Choose the baud rate from the
drop-down that matches the rate passed toSerial.begin in your sketch. Note that on Mac or Linux,
the Arduino board will reset (rerun your sketch from the beginning) when you connect with the
serial monitor. You can also talk to the board from Processing, Flash, MaxMSP, etc

.4 Boards
The board selection has two effects: it sets the parameters (e.g. CPU speed and baud rate) used
when compiling and uploading sketches; and sets and the file and fuse settings used by the burn
bootloader command. Some of the board definitions differ only in the latter, so even if you've
been uploading successfully with a particular selection you'll want to check it before burning the
boot loader.
Arduino Uno
PLC & SCADA Wireless Control System

40 Industrial Scope

An ATmega328 running at 16 MHz with auto-reset, using the optiboot boot loader (115200 baud,
0.5 KB).
Arduino Duemilanove w/ ATmega328
An ATmega328 running at 16 MHz with auto-reset.
Arduino Diecimila or Duemilanove w/ ATmega168
An ATmega168 running at 16 MHz with auto-reset. Compilation and upload is equivalent to
Arduino NG or older w/ ATmega168, but the boot loader burned has a faster timeout (and blinks
the pin 13 LED only once on reset).
Arduino Nano w/ ATmega328
An ATmega328 running at 16 MHz with auto-reset. Has eight analog inputs.
Arduino Nano w/ ATmega168
An ATmega168 running at 16 MHz with auto-reset. Compilation and upload is equivalent to
Arduino NG or older w/ ATmega168, but the bootloader burned has a faster timeout (and blinks
the pin 13 LED only once on reset). Has eight analog inputs.
Arduino Mega 2560 or Mega ADK
An ATmega2560 running at 16 MHz with auto-reset, using a stk500v2 bootloader.
Arduino Mega (ATmega1280)
An ATmega1280 running at 16 MHz with auto-reset.
Arduino Leonardo
An ATmega32u4 running at 16 MHz with auto-reset.
Arduino Mini w/ ATmega328
An ATmega328 running at 16 MHz with auto-reset, using the optiboot bootloader (115200 baud,
0.5 KB). Has eight analog inputs.
Arduino Mini w/ ATmega168

PLC & SCADA Wireless Control System

41 Industrial Scope

Equivalent to Arduino NG
16 MHz without auto-reset).

or

older

w/ ATmega168 (i.e.

an ATmega168 running

at

Arduino Ethernet
Equivalent to Arduino UNO with an Ethernet shield.
Arduino Fio
An ATmega328 running at 8 MHz with auto-reset. Equivalent to Arduino Pro or Pro Mini (3.3V,
8 MHz) w/ ATmega328.
Arduino BT w/ ATmega328
ATmega328 running at 16 MHz The bootloader burned (4 KB) includes codes to initialize the
on-board Bluetooth module.
Arduino BT w/ ATmega168
ATmega168 running at 16 MHz the bootloader burned includes codes to initialize the on-board
Bluetooth module.
Lily Pad Arduino w/ ATmega328
An ATmega328 running at 8 MHz (3.3V) with auto-reset. Equivalent to Arduino Pro or Pro Mini
(3.3V, 8 MHz) w/ ATmega328.
Lily Pad Arduino w/ ATmega168
An ATmega168 running at 8 MHz Compilation and upload is equivalent to the Arduino Pro or
Pro Mini (8 MHz) w/ ATmega168. The bootloader burned, however, has a slower timeout (and
blinks the pin 13 LED three times on reset) because the original versions of the Lily Pad didn't
support auto-reset. They also didn't include an external clock, so the burn bootloader command
configures the fuses of ATmega168 for an internal 8 MHz clock.
If you have a recent version of the Lily Pad, (w/ a 6-pin programming header), you'll want to
select Arduino Pro or Pro Mini (8MHz) w/ ATmega168 before burning the bootloader.
Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
An ATmega328 running at 16 MHz with auto-reset. Equivalent to Arduino Duemilanove or Nano
w/ ATmega328.

PLC & SCADA Wireless Control System

42 Industrial Scope

Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega168


An ATmega168 running at 16 MHz with auto-reset. Equivalent to Arduino Diecimila,
Duemilanove, or Nano w/ ATmega168.
Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328
An ATmega328 running at 8 MHz (3.3V) with auto-reset. Equivalent to Lily Pad Arduino
w/ ATmega328.
Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega168
An ATmega168 running at 8 MHz (3.3V) with auto-reset.
Arduino NG or older w/ ATmega168
An ATmega168 running at 16 MHz without auto-reset. Compilation and upload is equivalent to
Arduino Diecimila or Duemilanove w/ ATmega168, but the boot loader burned has a slower
timeout (and blinks the pin 13 LED three times on reset).
Arduino NG or older w/ ATmega8
An ATmega8 running at 16 MHz without auto-reset.

3.4 Hardware Methodology


Our project hardware is divided into two portions.
1) Transmitter
2) Receiver
1. Transmitter:
The transmitter side consists of the Controller and ZigBee. The controller and ZigBee are
connected through jumper wires.

PLC & SCADA Wireless Control System

43 Industrial Scope

Fig 3.1 Transmitter circuit diagram:

Fig 3.1 Transmitter Real Scenario:

PLC & SCADA Wireless Control System

44 Industrial Scope

Fig 3.2 Receiver Circuit diagram

Receiver Real Picture:

PLC & SCADA Wireless Control System

45 Industrial Scope

3.5 PLC CONNECTIONS:

Fig 3.3 PLC Connections

PLC & SCADA Wireless Control System

C HAPTER 4
VOICE

.1 Microsoft Speech API v5.1 (SAPI 5.1)


This article looks at adding support for speech capabilities to Microsoft Windows applications
written in Delphi, using the Microsoft Speech API version 5.1 (SAPI 5.1).
SAPI 5.1 exposes most of the important interfaces, types and constants through a registered type
library (SAPI 5.0 did not do this, making it difficult to use in Delphi without someone writing
the equivalent of the JEDI import unit for SAPI 5). This means that you can access SAPI 5.1
functionality through late bound or early bound Automation. We will focus our attention on early
bound Automation, which requires you to import the type library.
Choose Project | Import Type Library... and locate the type library described as Microsoft Speech
Object Library (Version 5.1) in the list. Now ensure the Generate Component Wrapper checkbox
is checked so the type library import unit will include component wrapper classes for each
exposed Automation object. These components will go on the ActiveX page of the Component
Palette by default, but you may wish to specify a more appropriate page, such as SAPI 5.1.
Now press Install... so the type library will be imported and the generated components will be
installed onto the Component Palette (pressing Create Unit would also generate the type library
import unit, but would require us to install it manually).
The generated import unit is called SpeechLib_TLB.pas and will be installed in a package. You
can either select the default package offered (the Borland User Components package by default),
choose to open a different package or even create a new one. When the package is compiled and
installed you will get a whopping set of 19 new components on the SAPI 5.1 page of the
Component Palette.
Each component is named after the primary interface it implements. So for example,
the TSpVoice component

implements

the SpVoice interface.

You

can

find

abundant

documentation on all these interfaces in the SAPI 5.1 SDK documentation.


PLC & SCADA Wireless Control System

Readymade SAPI 5.1 packages containing Automation components for Delphi 5, 6 and 7 can be
found in appropriately named subdirectories under SAPI 5.1 in the accompanying files.
If you are using Delphi 6 you will encounter a problem that is still present even with Update
Pack 2 installed. The type library importer has a bug where the parameters to Automation events
are incorrectly dispatched (they are sent in reverse order) meaning that all the Automation events
operate incorrectly (if at all). You can avoid this by importing the type library in Delphi 5 or 7
and using the generated type library import unit in Delphi 6. A Delphi 6 compatible package is
supplied with this article's files (it uses a Delphi 5 generated type library import unit).
The Delphi 7 type library importer has been improved to produce more accurate Pascal
representations of items in the type library than Delphi 5 did (and than Delphi 6 tried to). As a
result of this, the event handlers will often have different parameter lists in the Delphi 7 imported
type library. This means that the sample programs won't compile with Delphi 7 with the true
Delphi 7 SAPI type library import unit.
If you wish, you can write late bound Automation that calls CreateOleObject to instantiate the
Automation objects. In the case of the SpVoice interface, you would execute:
var
SpVoice: Variant;
...
SpVoice := CreateOleObject('SAPI.SpVoice')

4.2 Speech Synthesis


At its simplest level, all you need to do to get your program to speak is to use
a TSpVoice Automation object and call the Speak method. A trivial application that does this can
be found in the TextToSpeechSimple.dpr project in the files associated with this article. The
code looks like this:
procedure TfrmTextToSpeech.Button1Click(Sender: TObject);
PLC & SCADA Wireless Control System

begin
SpVoice1.Speak(memText.Text, SVSFDefault)
end;
And there you have it: a speaking application. The call to Speak takes a number of parameters
that we should examine:

The first is the text to speak, passed as a PChar. Because of the second parameter, this
call will be synchronous and so will not return until the text has been spoken.

The second parameter represents some flags that indicate how to use the first
parameter (you can combine multiple flags with the or operator). For example:
o SVSFDefault means the Speak method will be synchronous
o SVSFlagAsync makes the Speak method asynchronous and so it returns
immediately (you can use events to find out when speech terminates, or call
the WaitUntilDone method, or call SpeakCompleteEvent to receive a Win32
event

handle,

which

can

be

passed

to WaitForSingleObject).

Note that the Speak method returns a stream number. When queuing several
asynchronous voice streams, the stream number allows you to identify them;
each voice event passes the stream number to which it relates as a parameter.
o SVSFPurgeBeforeSpeak means any text being spoken and any text queued to
speak will be immediately cancelled.
o SVSFNLPSpeakPunc means punctuation marks are read out by their names,
rather than being used as punctuation (so ? is read out as question mark)
o SVSFIsFilename means the first parameter is a file name containing text to
speak.

PLC & SCADA Wireless Control System

o SVSFIsXML means the text includes XML tags to alter attributes of the
spoken text. For example this text controls the pitch, rate, volume, emphasis
and pronunciation of the spoken text:
o <EMPH>Hello</EMPH>
o <PRON SYM="d eh l f y">Delphi</PRON> developers!
o <VOLUME LEVEL="70">
o I can speak <PITCH MIDDLE="+10">high</PITCH> and <PITCH
MIDDLE="-10">low</PITCH>.
o I can speak <RATE SPEED="+10">very quickly</RATE> and <RATE
SPEED="-10">very slowly</RATE>.
o I can speak <VOLUME LEVEL="40">quietly</VOLUME> and <VOLUME
LEVEL="100">loudly</VOLUME>.
</VOLUME>
When the program executes it lets you type in some text in a memo and a button renders it into
the spoken word.

Fig 4.1 Speech Test 1


That's the simple example out of the way, but what can we achieve if we dig a little deeper and
get our hands a little dirtier? The next project, which holds the answers to these questions, can be
found as TextToSpeech.dpr in this article's files. You can see it running in the screenshot below;
PLC & SCADA Wireless Control System

notice that as the text is spoken, the current sentence is italicized and the current word is
displayed selected and also the phonemes spoken are written to a memo.

Fig 4.2 Speech Test 2


The following sections describe the important parts of the code from this project.

4.3 Enumerating Voices


The first thing the program does is to add a list of all the available voices to the combo box and
set the rate and volume track bar positions. The latter part of this is trivial as the voice rate and
volume are always within predetermined ranges (the volume is in the range 0 to 100 and the rate
is in the range -10 to 10).

PLC & SCADA Wireless Control System

procedure TfrmTextToSpeech.FormCreate(Sender: TObject);


var
I: Integer;
SOToken: ISpeechObjectToken;
SOTokens: ISpeechObjectTokens;
begin
SendMessage(lstProgress.Handle, LB_SETHORIZONTALEXTENT, Width, 0);
//Ensure all events fire
SpVoice.EventInterests := SVEAllEvents;
Log('About to enumerate voices');
SOTokens := SpVoice.GetVoices('', '');
for I := 0 to SOTokens.Count - 1 do
begin
//For each voice, store the descriptor in the TStrings list
SOToken := SOTokens.Item(I);
cbVoices.Items.AddObject(SOToken.GetDescription(0), TObject(SOToken));
//Increment descriptor reference count to ensure it's not destroyed
SOToken._AddRef;
end;
if cbVoices.Items.Count > 0 then
begin
PLC & SCADA Wireless Control System

cbVoices.ItemIndex := 0; //Select 1st voice


cbVoices.OnChange(cbVoices); //& ensure OnChange triggers
end;
Log('Enumerated voices');
Log('About to check attributes');
tbRate.Position := SpVoice.Rate;
lblRate.Caption := IntToStr(tbRate.Position);
tbVolume.Position := SpVoice.Volume;
lblVolume.Caption := IntToStr(tbVolume.Position);
Log('Checked attributes');
end;
The SpVoice object's GetVoices method returns a collection object that allows access to each
voice as an ISpeechObjectToken. In this code, both parameters are passed as empty strings, but
the first can be used to specify required parameters of the returned voices and the second for
optional parameters. So a call toGetVoices('Gender = male', '') would return only male voices.
In order to keep track of the voices, these ISpeechObjectToken interfaces are added, along with a
description, to the combo boxs Items (the description in the Strings array and the interfaces in
the Objects array).
Storing an interface reference in an object reference is possible as long as we remember exactly
what we stored, and we don't make the mistake of accessing it as an object reference. Also, since
the interface reference is stored using an inappropriate type, it is important to manually
increment its reference count to stop it being destroyed when the RTL code decrements the
reference count at the end of the method.

PLC & SCADA Wireless Control System

The On Destroy event handler tidies up these descriptor objects by decrementing their reference
counts, thereby allowing them to be destroyed.
procedure TfrmTextToSpeech.FormDestroy(Sender: TObject);
var
I: Integer;
begin
//Release all the voice descriptors
for I := 0 to cbVoices.Items.Count - 1 do
ISpeechObjectToken(Pointer(cbVoices.Items.Objects[I]))._Release;
end;
When the user selects a different voice from the combobox, the OnChange event handler selects
the new voice and displays the voice attributes (including the path in the Windows registry where
the voice attributes are stored).
procedure TfrmTextToSpeech.cbVoicesChange(Sender: TObject);
var
SOToken: ISpeechObjectToken;
begin
with lstEngineInfo.Items do
begin
Clear;
SOToken := ISpeechObjectToken(Pointer(

PLC & SCADA Wireless Control System

cbVoices.Items.Objects[cbVoices.ItemIndex]));
SpVoice.Voice := SOToken;
Add(Format('Name: %s', [SOToken.GetAttribute('Name')]));
Add(Format('Vendor: %s', [SOToken.GetAttribute('Vendor')]));
Add(Format('Age: %s', [SOToken.GetAttribute('Age')]));
Add(Format('Gender: %s', [SOToken.GetAttribute('Gender')]));
Add(Format('Language: %s', [SOToken.GetAttribute('Language')]));
Add(Format('Reg key: %s', [SOToken.Id]));
end
end;

4.4 Making Your Computer Talk


There are different calls to start speech and to continue paused speech, so a helper flag is
employed to record whether pause has been pressed. This allows the play button to start a fresh
speech stream as well as continue a paused speech stream. The text to speak is taken from a
richedit control and is spoken asynchronously thanks to the SVSFlagsAsync flag being used.
procedure TfrmTextToSpeech.btnPlayClick(Sender: TObject);
begin
if not BeenPaused then
SpVoice.Speak(reText.Text, SVSFlagsAsync)
else
begin

PLC & SCADA Wireless Control System

SpVoice.Resume;
BeenPaused := False
end
end;
procedure TfrmTextToSpeech.btnPauseClick(Sender: TObject);
begin
SpVoice.Pause;
BeenPaused := True
end;
procedure TfrmTextToSpeech.btnStopClick(Sender: TObject);
begin
SpVoice.Skip('Sentence', MaxInt)
end;
There

is

another speech

demo in

the

same

directory

in

the

project

TextToSpeechReadWordDoc.dpr. As the name suggests, this sample reads out loud from a Word
document. It uses Automation to control Microsoft Word (as well as the SAPI voice object).
type
TfrmVTxtAutoLateBound = class(TForm)
...
private
MSWord: Variant;
PLC & SCADA Wireless Control System

end;
...
procedure TfrmTextToSpeechReadWordDoc.FormCreate(Sender: TObject);
begin
MSWord := CreateOleObject('Word.Application');
end;

procedure TfrmTextToSpeechReadWordDoc.btnReadDocClick(Sender: TObject);


const
// Constants for enum WdUnits
wdCharacter = $00000001;
wdParagraph = $00000004;
// Constants for enum WdMovementType
wdExtend = $00000001;
var
Moved: Integer;
Txt: String;
begin
(Sender as TButton).Enabled := False;
Stopped := False;
if dlgOpenDoc.Execute then
PLC & SCADA Wireless Control System

begin
MSWord.Documents.Open(FileName := dlgOpenDoc.FileName);
Moved := 2;
while (Moved > 1) and not Stopped do
begin
//Select next paragraph
Moved := MSWord.Selection.EndOf(Unit:=wdParagraph, Extend:=wdExtend);
if Moved > 1 then
begin
Txt := Trim(MSWord.Selection.Text);
if Length(Txt) > 0 then
SpVoice.Speak(Txt, SVSFlagsAsync);
Application.ProcessMessages;
//Move to start of next paragraph
MSWord.Selection.MoveRight(Unit := wdCharacter);
end
end;
end;
MSWord.ActiveDocument.Close;
TButton(Sender).Enabled := True;
end;
PLC & SCADA Wireless Control System

procedure TfrmTextToSpeechReadWordDoc.btnStopClick(Sender: TObject);


begin
SpVoice.Skip('Sentence', Maxint);
Stopped := True;
end;

procedure TfrmTextToSpeechReadWordDoc.FormDestroy(Sender: TObject);


begin
btnStop.Click;
MSWord.Quit;
MSWord := Unassigned;
end;

4.5 Voice Events


The SpVoice object has a variety of events that fire during speech. Each block of speech starts
with an OnStartStream event and ends with OnEndStream.OnStartStream identifies the speech
stream, and all the other events pass the stream number to which they pertain. As each sentence
is started an OnSentenceevent fires and there is also an OnWord event that triggers at the start of
each spoken word.
Additionally (among others) an OnAudioLevel event allows a progress bar to be used as a VU
meter for the spoken text. However it is important to note that for some events to fire you must
set the EventInterests property accordingly; to receive the OnAudioLevel event you should
set EventInterests toSVEAudioLevel or SVEAllEvents.
PLC & SCADA Wireless Control System

const
Phonemes: array[1..49] of String = (
'-', '!', '&', ',', '.', '?', '_',
'1', '2', 'aa', 'ae', 'ah', 'ao', 'aw',
'ax', 'ay', 'b', 'ch', 'd', 'dh', 'eh',
'er', 'ey', 'f', 'g', 'h', 'ih', 'iy',
'jh', 'k', 'l', 'm', 'n', 'ng', 'ow',
'oy', 'p', 'r', 's', 'sh', 't', 'th',
'uh', 'uw', 'v', 'w', 'y', 'z', 'zh'
);
procedure TfrmTextToSpeech.SpVoicePhoneme(Sender: TObject;
StreamNumber: Integer; StreamPosition: OleVariant; Duration: Integer;
NextPhoneId: Smallint; Feature: TOleEnum; CurrentPhoneId: Smallint);
begin
if CurrentPhoneId <> 7 then //Display phonemes, except silence
memEnginePhonemes.Text :=
memEnginePhonemes.Text + Phonemes[CurrentPhoneId] +'-'
end;

4.6 Animating Speech


An OnViseme event is triggered for each recognised viseme (a portion of speech requiring the
mouth to move into a visibly different position); there are 22 different visemes generated by
PLC & SCADA Wireless Control System

English speech and these are based on the Disney 13 visemes (cartoons have less granularity and
Disney animators discovered many years ago that only 13 cartoon mouth shapes are required to
represent all English phonemes).
If you have some artistic flair and can draw a mouth in each position represented by the visemes
you could use this event to provide a simple animated representation of speech.
The SAPI 5.1 SDK comes with a C++ example called TTSApp, which displays an animated
cartoon microphone whose mouth is drawn to represent each viseme. The microphone is made
up from a number of separate images that can all be loaded into an image list. The
additional demo program TextToSpeechAnimated.dpr makes use of these images to show how
the effect can be achieved.
const
Visemes: array[0..21] of Byte = (
0, // SP_VISEME_0 = 0,

// Silence

11, // SP_VISEME_1,

// AE, AX, AH

11, // SP_VISEME_2,

// AA

11, // SP_VISEME_3,

// AO

10, // SP_VISEME_4,

// EY, EH, UH

11, // SP_VISEME_5,

// ER

9, // SP_VISEME_6,

// y, IY, IH, IX

2, // SP_VISEME_7,

// w, UW

13, // SP_VISEME_8,

// OW

9, // SP_VISEME_9,

// AW

12, // SP_VISEME_10,

// OY
PLC & SCADA Wireless Control System

11, // SP_VISEME_11,

// AY

9, // SP_VISEME_12,

// h

3, // SP_VISEME_13,

// r

6, // SP_VISEME_14,

// l

7, // SP_VISEME_15,

// s, z

8, // SP_VISEME_16,

// SH, CH, JH, ZH

5, // SP_VISEME_17,

// TH, DH

4, // SP_VISEME_18,

// f, v

7, // SP_VISEME_19,

// d, t, n

9, // SP_VISEME_20,

// k, g, NG

1 // SP_VISEME_21,

// p, b, m

);

procedure TfrmTextToSpeech.SpVoiceViseme(Sender: TObject;


StreamNumber: Integer; StreamPosition: OleVariant; Duration: Integer;
NextVisemeId, Feature, CurrentVisemeId: TOleEnum);
const
EyesNarrow = 14;
EyesClosed = 15;
begin
imgsMic.Draw(pbMic.Canvas, 0, 0, Visemes[CurrentVisemeId]);
PLC & SCADA Wireless Control System

if Visemes[CurrentVisemeId] mod 6 = 2 then


imgsMic.Draw(pbMic.Canvas, 0, 0, EyesNarrow)
else
if Visemes[CurrentVisemeId] mod 6 = 5 then
imgsMic.Draw(pbMic.Canvas, 0, 0, EyesClosed);
end;

procedure TfrmTextToSpeech.pbMicPaint(Sender: TObject);


begin
imgsMic.Draw(pbMic.Canvas, 0, 0, 0);
end;
The OnViseme event gets the image list to draw on a paint box component and the image to draw
is identified from a simple lookup table. There are 22 different visemes, but only 13 images (as
in the Disney approach). Occasionally the code also draws narrowed or closed eyes, but
whenever the silence viseme is received (at the start and end of each sentence) the default
microphone (the first image in the image list) is drawn.

PLC & SCADA Wireless Control System

Fig 4.3 Speech Test 3


You can take this idea further if you need, by using images of a person's face saying each of the
22 visemes (for real people it seems to work best if you use 22 images, rather than 13). This way
you can animate a real person's face in sync with the spoken text quite trivially.

PLC & SCADA Wireless Control System

Fig 4.4 Speech Test 4

4.7 Keeping Track Of Spoken Text


We can use OnWord and OnSentence to highlight the currently spoken work or sentence, as the
events provide the character offset and length of the pertinent characters in the text. So when a
sentence is started, the OnSentence event tells you which character in the text is the start of the
sentence, and also how long the sentence is.
procedure TfrmTextToSpeech.SetTextHilite(FirstChar, Len: Integer);
begin
reText.SelStart := FirstChar; //highlight word
reText.SelLength := Len;
PLC & SCADA Wireless Control System

end;

procedure

TfrmTextToSpeech.SetTextStyle(FirstChar,

Len:

Integer;

Styles:

TFontStyles);
begin
with reText do
begin
Lines.BeginUpdate;
try
SelStart := FirstChar; //highlight word
SelLength := Len;
SelAttributes.Style := Styles; //apply requested style
SelLength := 0; //unhighlight word
finally
Lines.EndUpdate
end
end
end;

procedure TfrmTextToSpeech.SpVoiceSentence(Sender: TObject;


StreamNumber: Integer; StreamPosition: OleVariant; CharacterPosition,

PLC & SCADA Wireless Control System

Length: Integer);
begin
Log('OnSentence: stream %d, position: %s, char. pos. %d, length %d',
[StreamNumber, String(StreamPosition), CharacterPosition, Length]);
SetTextStyle(OldSentencePos, OldSentenceLen, []);
if Length > 0 then
begin
SetTextStyle(CharacterPosition, Length, [fsItalic]);
OldSentencePos := CharacterPosition;
OldSentenceLen := Length;
end;
if not StreamJustStarted then
memEnginePhonemes.Text := memEnginePhonemes.Text + #13#10;
StreamJustStarted := False;
end;

procedure TfrmTextToSpeech.SpVoiceWord(Sender: TObject;


StreamNumber: Integer; StreamPosition: OleVariant; CharacterPosition,
Length: Integer);
begin
Log('OnWord: stream %d, position: %s, char. pos. %d, length %d',
PLC & SCADA Wireless Control System

[StreamNumber, String(StreamPosition), CharacterPosition, Length]);


SetTextHilite(CharacterPosition, Length);
end;
Each sentence that gets spoken is italicised through the SetTextStyle helper routine (which
records the position details so the sentence can be set back to non-italic when the next sentence
starts). Similarly, each spoken word is highlighted using the SetTextHilite helper routine.
The comment in the OnSentence event handler points out that the last OnSentence event for
some text has the character position set to the last character and the length set to the negative
equivalent. This gives an opportunity to reset all the text formatting back to the default styles.
However it is only true if the text ends with a full stop; if not you can use
the OnEndStream event for tidying up.

4.8 Speaking Dialogs


As an example of using speech synthesis you can make all your VCL dialogs talk to you using
this small piece of code.
uses
ComObj;

var
Voice: Variant;

procedure TForm1.FormCreate(Sender: TObject);


begin

PLC & SCADA Wireless Control System

Screen.OnActiveFormChange := ScreenFormChange;
end;

procedure TForm1.ReadVCLDialog(Form: TCustomForm);


var
I: Integer;
ButtonCaptions, LabelCaption, DialogText: string;
const
SVSFlagsAsync = 1;
begin
try
if VarType(Voice) <> varDispatch then
Voice := CreateOleObject('SAPI.SpVoice');
for I := 0 to Form.ComponentCount - 1 do
if Form.Components[I] is TLabel then
LabelCaption := TLabel(Form.Components[I]).Caption
else
if Form.Components[I] is TButton then
ButtonCaptions := Format('%s%s, ',
[ButtonCaptions, TButton(Form.Components[I]).Caption]);
ButtonCaptions := StringReplace(ButtonCaptions,'&','', [rfReplaceAll]);
PLC & SCADA Wireless Control System

DialogText := Format('%s.%s%s.%s%s',
[Form.Caption, sLineBreak, LabelCaption, sLineBreak, ButtonCaptions]);
Memo1.Text := DialogText;
Voice.Speak(DialogText, SVSFlagsAsync)
except
//pretend everything is okay
end
end;

procedure TForm1.ScreenFormChange(Sender: TObject);


begin
if Assigned(Screen.ActiveForm) and
(Screen.ActiveForm.ClassName = 'TMessageForm') then
ReadVCLDialog(Screen.ActiveForm)
end;
The form's OnCreate event handler sets up an OnActiveFormChange event handler for the screen
object. This is triggered each time a new form is displayed, which includes VCL dialogs. Any
call to ShowMessage, MessageDlg or related routines causes a TMessageForm to be displayed
so the code checks for this. If the form type is found, a textual version of what's on the dialog is
built up and then spoken through the SAPI Automation component.
A statement such as:

PLC & SCADA Wireless Control System

MessageDlg('Save changes?', mtConfirmation, mbYesNoCancel, 0)


causes the ReadVCLDialog routine to build up and say this text:
Confirm.
Save changes?.
Yes, No, Cancel,
Notice the full stops at the end of each line to briefly pause the speech engine at that point before
moving on.

4.9 Speech Recognition


Continuous dictation is easy to set up as no specific grammar is required, but Command and
Control recognition will need a grammar to educate the recogniser as to the permissible
commands.
When you need SR you can either use a shared recogniser (TSpSharedRecognizer) or an inprocess recogniser (TSpInprocRecognizer). The in-process recogniser is more efficient (it resides
in your process address space) but means that no other SR applications can receive input from
the microphone until it is closed down. On the other hand the shared recogniser can be used by
multiple applications, and each one can access the microphone. It is more common to use the
shared recogniser in typical SAPI applications.
The recogniser uses the notion of a recognition context to identify when it will be active (not to
be confused with the use of context in a context-free grammar or CFG). A context is represented
by the SpInprocRecoContext or SpSharedRecoContext interfaces. An application may use one
context for each form that will use SR, or several contexts for different application modes
(Office XP has a dictation mode for adding text to a document and a control mode for executing
menu commands).

PLC & SCADA Wireless Control System

Recognition contexts enable you to start and stop recognition, set up the grammar and receive
important recognition notifications.

4.9.1 Grammars
Part of the process of speech recognition involves deciding what words have actually been
spoken. Recognisers use a grammar to decide what has been said, where possible. SAPI 5.x
represents grammars in XML.
In the case of dictation, a grammar can be used to indicate some words that are likely to be
spoken. It is not feasible to try and represent the entire spoken English language as a grammar so
the recogniser uses its own rules and context analysis, with any help from a grammar you might
supply.
With Command and Control, the words that are understood are limited to the supported
commands defined in the grammar. The grammar defines various rules that dictate what will be
said and this makes the recogniser's job much easier. Rather than trying to understand anything
spoken, it only needs to recognise speech that follows the supplied rules. A simple grammar that
recognises three colours might look like this:
<GRAMMAR LANGID="809">

<!-- "Constant" definitions -->


<DEFINE>
<ID NAME="RID_start" VAL="1"/>
</DEFINE>

PLC & SCADA Wireless Control System

<!-- Rule definitions -->


<RULE NAME="start" ID="RID_start" TOPLEVEL="ACTIVE">
<L>
<P>red</P>
<P>blue</P>
<P>green</P>
</L>
</RULE>
</GRAMMAR>
The GRAMMAR root node defines the language as British English ($809, American English is
$409). Note that the colour rule is a top level rule and has been marked to be active by default,
meaning it will be active whenever speech recognition is enabled for this context.
Grammars support lists to make implementing many similar commands easy and also support
optional sections. For example this grammar will recognise any of the following:

colour red

colour red please

colour blue

colour blue please

colour green

colour green please

PLC & SCADA Wireless Control System

<GRAMMAR LANGID="809">
<DEFINE>
<ID NAME="RID_start" VAL="1"/>
</DEFINE>

<RULE NAME="start" ID="RID_start" TOPLEVEL="ACTIVE">


<P>colour</P>
<RULEREF NAME="colour" />
<O>please</O>
</RULE>

<RULE NAME="colour">
<L>
<P>red</P>
<P>blue</P>
<P>green</P>
</L>
</RULE>
</GRAMMAR>
You can find more details about the supported grammar syntax in the SAPI documentation

PLC & SCADA Wireless Control System

4.10 Continuous Dictation Recognition


Thankfully this is quite straightforward to use. We need to set up a recognition context object for
the shared recogniser so drop a TSpSharedRecContextcomponent on the form.
The recogniser will implicitly be set up if we do not create one specifically. This means you do
not need to drop a TSpSharedRecognizer or aTSpInprocRecognizer on the form unless you need
to use them directly.
The code below shows how you create a simple grammar that will satisfy the SR engine for
continuous dictation. The grammar is represented by anISpeechRecoGrammar interface and is
used to start the dictation session. The code comes from the ContinuousDictation.dpr sample
project.
SRGrammar: ISpeechRecoGrammar;
...
procedure TfrmContinuousDictation.FormCreate(Sender: TObject);
begin
//OnAudioLevel event is not fired by default - this changes that
SpSharedRecoContext.EventInterests := SREAllEvents;
SRGrammar := SpSharedRecoContext.CreateGrammar(0);
SRGrammar.DictationSetState(SGDSActive)
end;

4.11 Grammar Notifications


As the SR engine does its work it calls notification methods when certain things happen, such as
a phrase having been finished and recognised. These notifications are available as standard

PLC & SCADA Wireless Control System

Delphi events in the Delphi Automation object component wrappers. This greatly simplifies the
job of responding to the notifications.
The main event is OnRecognition, which is called when the SR engine has decided what has
been spoken. Whilst working it out, it will likely call theOnHypothesis event several times.
Finished phrases are added to a memo on the form and whilst a phrase is being worked out the
hypotheses are added to a list box so you can see how the SR engine made its decision. Each
time a new phrase is started, the hypothesis list is cleared.
You can see the list of hypotheses building up in this screenshot of the program running.

PLC & SCADA Wireless Control System

Fig 4.5 Dictation Test


Both OnRecognition and OnHypothesis are
an ISpeechRecoResult results

object.

In

passed
Delphi

a Result parameter;
7

this

is

declared

this

is

using

the

correct ISpeechRecoResult interface type, but in earlier versions this was just declared as
an OleVariant (which contained the ISpeechRecoResult interface).
This code can be used in Delphi 6 and earlier to access the text that was recognised:
procedure TfrmContinuousDictation.SpSharedRecoContextHypothesis(
Sender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
var Result: OleVariant);
begin
lstHypotheses.Items.Add(Result.PhraseInfo.GetText);
lstHypotheses.ItemIndex := lstHypotheses.Items.Count - 1
end;

procedure TfrmContinuousDictation.SpSharedRecoContextRecognition(
Sender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
RecognitionType: TOleEnum; var Result: OleVariant);
begin
memText.SelText := Result.PhraseInfo.GetText + #32
end;
This code uses late bound Automation on the results object (so no Code Completion or Code
Parameters), but you could use early bound Automation with:
PLC & SCADA Wireless Control System

procedure TfrmContinuousDictation.SpSharedRecoContextHypothesis(
Sender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
var Result: OleVariant);
var
SRResult: ISpeechRecoResult;
begin
SRResult := IDispatch(Result) as ISpeechRecoResult;
lstHypotheses.Items.Add(SRResult.PhraseInfo.GetText(0, -1, True));
lstHypotheses.ItemIndex := lstHypotheses.Items.Count - 1
end;

procedure TfrmContinuousDictation.SpSharedRecoContextRecognition(
Sender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
RecognitionType: TOleEnum; var Result: OleVariant);
var
SRResult: ISpeechRecoResult;
begin
SRResult := IDispatch(Result) as ISpeechRecoResult;
memText.SelText := SRResult.PhraseInfo.GetText(0, -1, True) + #32
end;
The code here does not check if a valid IDispatch reference is in the Variant but probably should.
PLC & SCADA Wireless Control System

In Delphi 7 the code should look like this:


procedure TfrmContinuousDictation.SpSharedRecoContextHypothesis(
ASender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
const Result: ISpeechRecoResult);
begin
lstHypotheses.Items.Add(Result.PhraseInfo.GetText(0, -1, True));
lstHypotheses.ItemIndex := lstHypotheses.Items.Count - 1
end;

procedure TfrmContinuousDictation.SpSharedRecoContextRecognition(
ASender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
RecognitionType: TOleEnum; const Result: ISpeechRecoResult);
begin
memText.SelText := Result.PhraseInfo.GetText(0, -1, True) + #32
end;

4.12 Engine Dialogs


The buttons on the form allow various engine dialogs to be invoked (if supported). This support
is all attained through a couple of methods of the recogniser object.
const
SPDUI_EngineProperties = 'EngineProperties';

PLC & SCADA Wireless Control System

SPDUI_AddRemoveWord = 'AddRemoveWord';
SPDUI_UserTraining = 'UserTraining';
SPDUI_MicTraining = 'MicTraining';
SPDUI_RecoProfileProperties = 'RecoProfileProperties';
SPDUI_AudioProperties = 'AudioProperties';
SPDUI_AudioVolume = 'AudioVolume';

procedure TfrmContinuousDictation.btnEnginePropsClick(Sender: TObject);


begin
InvokeUI(SPDUI_EngineProperties, 'Engine Properties')
end;

procedure TfrmContinuousDictation.btnUserSettingsClick(Sender: TObject);


begin
InvokeUI(SPDUI_RecoProfileProperties, 'User Settings')
end;

procedure TfrmContinuousDictation.btnLexiconClick(Sender: TObject);


begin
InvokeUI(SPDUI_AddRemoveWord, 'Add/Remove Word')
end;
PLC & SCADA Wireless Control System

procedure TfrmContinuousDictation.btnTrainGeneralClick(Sender: TObject);


begin
InvokeUI(SPDUI_UserTraining, 'Speaker Training')
end;

procedure TfrmContinuousDictation.btnTrainMicClick(Sender: TObject);


begin
InvokeUI(SPDUI_MicTraining, 'Microphone Setup')
end;

procedure TfrmContinuousDictation.btnAudioPropsClick(Sender: TObject);


begin
InvokeUI(SPDUI_AudioProperties, 'Audio Properties')
end;

procedure TfrmContinuousDictation.btnAudioVolClick(Sender: TObject);


begin
InvokeUI(SPDUI_AudioVolume, 'Audio Volume')
end;

PLC & SCADA Wireless Control System

procedure

TfrmContinuousDictation.InvokeUI(const

TypeOfUI,

Caption:

WideString);
var
U: OleVariant;
begin
U := Unassigned;
if SpSharedRecoContext.Recognizer.IsUISupported(TypeOfUI, U) then
SpSharedRecoContext.Recognizer.DisplayUI(Handle, Caption, TypeOfUI, U)
end;

4.13 Command and Control Recognition


For C and C recognition we will need a grammar to give the SR engine rules by which to
recognise

the

commands.

This

grammar

is

used

by

sample

project

called

CommandAndControl.dpr in the files that accompany this article.


<GRAMMAR LANGID="809">

<!-- "Constant" definitions -->

<DEFINE>
<ID NAME="RID_start" VAL="1"/>
<ID NAME="PID_chosencolour" VAL="2"/>
<ID NAME="PID_colourvalue" VAL="3"/>

PLC & SCADA Wireless Control System

</DEFINE>

<!-- Rule definitions -->

<RULE NAME="start" ID="RID_start" TOPLEVEL="ACTIVE">


<O>colour</O>
<RULEREF

NAME="colour"

PROPNAME="chosencolour"

PROPID="PID_chosencolour" />
<O>please</O>
</RULE>

<RULE NAME="colour">
<L PROPNAME="colourvalue" PROPID="PID_colourvalue">
<P VAL="1">red</P>
<P VAL="2">blue</P>
<P VAL="3">green</P>
</L>
</RULE>
</GRAMMAR>
After defining some constants the rules are laid out next. The top level rule (start, which is just
an arbitrarily chosen name) is defined as the optional word colour, a value from another rule
(also called colour) and the optional word please. The value from the colour rule can be
PLC & SCADA Wireless Control System

identified programmatically (rather than by scanning the recognised text) thanks to it being
defined as a property (chosencolour).
The colour rule defines one of three colours that can be spoken, each of which has a value
defined for it. Again, this value will be accessible thanks to the list being defined as a property
(colourvalue).
This grammar is stored in an XML file and loaded in the OnCreate event handler.
procedure TfrmCommandAndControl.FormCreate(Sender: TObject);
begin
//OnAudioLevel event is not fired by default - this changes that
SpSharedRecoContext.EventInterests := SREAllEvents;
SRGrammar := SpSharedRecoContext.CreateGrammar(0);
SRGrammar.CmdLoadFromFile('C and C Grammar.xml', SLODynamic);
SRGrammar.CmdSetRuleIdState(0, SGDSActive)
end;
Notice that two different ISpeechRecoGrammar methods are used to instigate command and
control

recognition. CmdLoadFromFile loads

grammar

from

an

XML

file

and CmdSetRuleIdState activates all top level rules when the first parameter is zero (you can
activate individual rules by passing their rule ID).
The OnRecognition event handler does the work of locating the chosencolour property and then
finding the nested colourvalue property. Its value is used to change the form colour at the user's
request, for example with phrases such as:

red please

PLC & SCADA Wireless Control System

colour green

colour blue please

red

procedure TfrmCommandAndControl.SpSharedRecoContextRecognition(
ASender: TObject; StreamNumber: Integer; StreamPosition: OleVariant;
RecognitionType: TOleEnum; const Result: ISpeechRecoResult);
begin
with Result.PhraseInfo do
begin
Log('OnRecognition: %s', [GetText(0, -1, True)]);
case GetPropValue(Result, ['chosencolour', 'colourvalue']) of
1: Color := clRed;
2: Color := clBlue;
3: Color := clGreen;
end
end
end;
This code uses a helper routine, GetPropValue whose task is to locate the appropriate property in
the result object, by following the property path specified in the string array parameter. The code
for GetPropValue and its own helper routine, GetProp, looks like this:

PLC & SCADA Wireless Control System

function GetProp(Props: ISpeechPhraseProperties;


const Name: String): ISpeechPhraseProperty; overload;
var
I: Integer;
Prop: ISpeechPhraseProperty;
begin
Result := nil;
for I := 0 to Props.Count - 1 do
begin
Prop := Props.Item(I);
if CompareText(Prop.Name, Name) = 0 then
begin
Result := Prop;
Break
end
end
end;

function GetPropValue(SRResult: ISpeechRecoResult;


const Path: array of String): OleVariant;
var
PLC & SCADA Wireless Control System

Prop: ISpeechPhraseProperty;
PathLoop: Integer;
begin
for PathLoop := Low(Path) to High(Path) do
begin
if PathLoop = Low(Path) then //top level property
Prop := GetProp(SRResult.PhraseInfo.Properties, Path[PathLoop])
else //nested property
Prop := GetProp(Prop.Children, Path[PathLoop]);
if not Assigned(Prop) then
begin
Result := Unassigned;
Exit;
end
end;
Result := Prop.Value
end;

PLC & SCADA Wireless Control System

C HAPTER 5
PROGRAMMING & CODING

.1 Transmitter Coding
#include <VirtualWire.h>
#include <String.h>
const int led_pin = 11;
const int transmit_pin = 12;
const int transmit_en_pin = 3;
int ldr = A0;
String str;
char cstr[27];
void setup()
{
// Initialise the IO and ISR
vw_set_tx_pin(transmit_pin);
Serial.begin(9600);
vw_setup(2000);

// Bits per sec

pinMode(led_pin, OUTPUT)
pinMode(ldr, INPUT);}
byte count = 1;

PLC & SCADA Wireless Control System

void loop()
{
if(Serial.available()>0)
{
char message = Serial.read();
str = String(message);
str.toCharArray(cstr,27);
//char msg[7] = {'h','e','l','l','o',' ','#'};
//char msg1[27] = "fahad i love you ";
// msg[6] = count;
digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
vw_send((uint8_t *)cstr, 1); // change this number according to the sensor values
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(led_pin, LOW);
count = count + 1;}
}

5.2 Receiver Coding


#include <VirtualWire.h>
const int receive_pin = 11;

int load1 = 2;
PLC & SCADA Wireless Control System

int load2 = 3;
int load3 = 4;
int load4 = 5;
int load5 = 6;
int load6 = 7;
void setup()
{
delay(1000);
Serial.begin(9600);

// Debugging only

Serial.println("setup");
// Initialise the IO and ISR
vw_set_rx_pin(receive_pin);
vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(2000);
vw_rx_start();

// Bits per sec


// Start the receiver PLL running

pinMode(load1, OUTPUT);
pinMode(load2, OUTPUT);
pinMode(load3, OUTPUT);
pinMode(load4, OUTPUT)
pinMode(load5, OUTPUT);
pinMode(load6 , OUTPUT);

PLC & SCADA Wireless Control System

}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
for (i = 0; i < buflen; i++)
{
char c = (buf[i]);
Serial.print(c);
if( c == 'a')
digitalWrite(load1, HIGH);
if( c == 'b')
digitalWrite(load1, LOW);
if( c == 'c')
digitalWrite(load2, HIGH);
if( c == 'd')
digitalWrite(load2, LOW)
if( c == 'e')

PLC & SCADA Wireless Control System

digitalWrite(load3, HIGH);
if( c == 'f')
digitalWrite(load3, LOW);
if( c == 'g')
digitalWrite(load4, HIGH);
if( c == 'h')
digitalWrite(load4, LOW);
if( c == 'i')
digitalWrite(load5, HIGH);
if( c == 'j')
digitalWrite(load5, LOW);
if( c == 'k')
digitalWrite(load6, HIGH);
if( c == 'l')
digitalWrite(load6, LOW);}}
}

PLC & SCADA Wireless Control System

C HAPTER 6
INDUSTRIAL SCOPE

1. High grade management system is adopted and computer comprehensive management


system is established.
2. PLC & SCADA is used for its large reduction in quantity of mediate-relay and hardwiring, the rehability and flexibility of the system are greatly enhanced.
3. This system is suitable not only for the requirement of Silo control, but also for the other
industrial requirements of process operations of rice mill, flour mill , feed mill, oil
refiner, foodstuff factory etc.
4. It has played an important role in speeding up harbour transportation.
5. It contributes to the comprehensive functions of monitoring and controlling, maternal
blockage and equipment stoppage are largely decreased, labor strength is greatly reduced
and the management is also updated to the further high level based on the replacement of
traditional control desk and mimic panel with computer configuration control and
operation interface.
6. This system features: direct digital control, high interference-free ability, absolute
rehability and less dimension.
7. All working operations can be realized by optimizing selection of process route direction
according to technological demands.
8. The smart operations for auto alarm, sequent and emergent stop are created.
9. The application of this system reduces the labor strength, avoids inharmonious operation
links and delays resolution for removal of equipment failure, decreases mistakes or
errors, and provides the technological environment for upgrade of equipment utilization
ratio, labor productivity and capability of gram handling.

PLC & SCADA Wireless Control System

93

APPENDICES

PLC & SCADA Wireless Control System

94 Appendix A
Appendix A

A)

ZigBee Layers

Figure A.1 The seven layers of ZigBee model

The 5 layers can be divided into three groups, Customer, IEEE and ZigBee Alliance.

A-i) Physical layer


The physical layer of the IEEE802.15.4 standard is the closest layer to the hardware, which
control and communicate with the radio transceiver directly. It handles all tasks involving the
access to the ZigBee hardware, including initialization of the hardware, channel selection, link
quality estimation, energy detection measurement and clear channel assessment to assist the
channel selection. Supports three frequency bands, 2.45GHz band which using16 channels,

PLC & SCADA Wireless Control System

95 Appendix A

915MHz band which using 10 channels and 868MHz band using 1 channel. All three using
Direct Spread Spectrum Sequencing (DSSS) access mode.
PHY Packet Fields

Preamble (32 bits) synchronization


Start of Packet Delimiter (8 bits)
PHY Header (8 bits) PSDU length
PSDU (0 to 1016 bits) Data field

A-ii) MAC Layer


This layer provides interface between physical layer and network layer. This provides two
services; MAC data services and MAC management service interfacing to the MAC sub Layer
Management Entity (MLME) Service Access Point called (MLME-SAP). The MAC data service
enables the transmission and reception of MAC protocol Data Units (MPDUs) across the PHY
data service. MAC layer is responsible for generating beacons and synchronizing devices to the
beacon signal in a beacon enabled services. It is also performing association and dissociation
function. It defines four frame structures, are Beacon frame, Data frame, Acknowledge frame,
MAC command frame. Basically there are two types of topology; star and peer to peer. Peer to
peer topology can take different shapes depends on its restrictions. Peer to peer is known as
mesh, if there is no restriction. Another form is tree topology. Interoperability is one of the
advantages of ZigBee protocol stack. ZigBee has wide range of applications, so different
manufacturer provides ZigBee devices. ZigBee devices can interact with each other regardless of
manufacturer (even I if the message is encrypted).

A-iii) Network Layer


Network layer interfaces between application layer and MAC Layer. This Layer is responsible
for network formation and routing. Routing is the process of selection of path to relay the
messages to the destination node. This forms the network involving joining and leaving of nodes,
maintaining routing tables (coordinator/router), actual routing and address allocation. ZigBee
coordinator or router will perform the route discovery. This layer Provides network wide security

PLC & SCADA Wireless Control System

96 Appendix A

and allows low power devices to maximize their battery life. From the basic topologies, there are
three network topologies are considered in IEEE802.15.4 are star, tree Network and mesh.

A-iv) Application Layer


The application Layer is the highest protocol layer and it hosts the application objects. ZigBee
specification separates the APL layer into three different sub-layers: the Application Support Sub
layer, the ZigBee Device Objects, and Application Framework having manufacturer defined
Application Objects.
The application objects (APO):
Control and manages the protocol layers in ZigBee device. It is a piece of software which
controls the hardware. Each application objects assigned unique end point number that other
APOs can use an extension to the network device address to interact with it. There can be up to
240 application objects in a single ZigBee device. A ZigBee application must conform to an
existing application profile which is accepted ZigBee Alliance. An application profile defines
message formats and protocols for interactions between application objects. The application
profile framework allows different vendors to independently build and sell ZigBee devices that
can interoperate with each other in a given application profile.
ZigBee Device Object:
The key definition of ZigBee is the ZigBee device object, which addresses three main
operations; service discovery, security and binding. The role of discovery is to find nodes and ask
about MAC address of coordinator/router by using unicast messages. The discovery is also
facilitating the procedure for locating some services through their profile identifiers. So profile
plays an important role. The security services in this ZigBee device object have the role to
authenticate and derive the necessary keys for data encryption. The network manager is
implemented in the coordinator and its role is to select an existing PAN to interconnect. It also
supports the creation of new PANs. The role of binding manager is to binding nodes to recourses
and applications also binding devices to channels.
Application support sub layer:

PLC & SCADA Wireless Control System

97 Appendix A

The Application Support (APS) sub layer provides an interface between the NWK and the APL
layers through a general set of services provided by APS data and management entities. The APS
sub layer processes outgoing/incoming frames in order to securely transmit/receive the frames
and establish/manage the cryptographic keys. The upper layers issue primitives to APS sub layer
to use its services. APS Layer Security includes the following services: Establish Key, Transport
Key, Update Device, Remove Device, Request Key, Switch Key, Entity Authentication, and
Permissions Configuration Table.
Security service provider:
ZigBee provides security mechanism for network layer and application support layers, each of
which is responsible for securing their frames. Security services include methods for key
establishment, key transport, frame protection and device management.

A-v) Data Link layer


The Data Layer is mainly the method in which information from the network is broken down
into frames and transmitted over the physical layer. This layer is also responsible for some Error
detection and correction and some addressing so different devices can tell each other apart in
larger systems.

PLC & SCADA Wireless Control System

98 Bibliography

BIBLIOGRAPHY
[1]. Kevin Collins, PLC programming for industrial automation;AuthorsChance Ltd
Haselmere/GB-Feb 2007
[2] Ashutosh Singh, Debajit Tapadar, Sitanshu Sekhar Mondal, soumyaroop sengupta,
Automation of bolt galvanization plant using PLCInternational Conference on Process
Automation ,Control and Computing-PACC,2011
[3] Haider Ali & Ahmed Ali, Riaz Ul Hassnain Syed & Ajmal Khan & Ihsanullah Khan,
SCADA implementation of industrial temperature automation IJCSNS International Journal
of Computer Science and Network Security, VOL.11 No.8, August 2011
[4] Marek Laciak, Peter Fazekas, Jan Kacur, Monitoring and control of temperatures in electric
furnace in promotic system, 2011 12th International Carpathian Control Conference (ICCC).
[5] US patent NO:4227965 dtd Oct,14,1980 Production of Hard board
[6] US patent NO:3880975 dtd Apr 29,1975 Continous Hardboard Production
[7] J. W. Webb and R. A. Reis, Programmable Logic Controllers: Principles and Applications.
Engelwood Cliffs, NJ: Prentice-Hall, 1999.
[8] 020-745 Data Pack D Data Sheet RS Allen-Bradley MicroLogix 1000
[9] Rinaldi, et al., Identifying, Understanding, and Analyzing Critical Infrastructure
Interdependencies, IEEE Control Systems Magazine, 2001,
http://www.ce.cmu.edu/~hsm/im2004/readings/CII-Rinaldi.pdf.
[10] GAO-04-354, Critical Infrastructure Protection: Challenges and Efforts to Secure Control
Systems, U.S. GAO, 2004, http://www.gao.gov/new.items/d04354.pdf.
[11] Weiss, Joseph, Current Status of Cyber Security of Control Systems, Presentation to
Georgia Tech Protective Relay Conference, May 8, 2003.
[12] Keeney, Michelle et al., Insider Threat Study: Computer System Sabotage in Critical
Infrastructure Sectors, United States Secret Service and Carnegie Mellon Software Institute,
2005, http://www.cert.org/archive/pdf/insidercross051105.pdf.
[13] Federal Information Security Management Act of 2002, Section 301: Information Security,
http://csrc.nist.gov/policies/FISMA-final.pdf.

PLC & SCADA Wireless Control System

99 Bibliography

[14] Federal Information Security Management Act Implementation Project,


http://csrc.nist.gov/sec-cert/.
[15] Federal Information Processing Standards Publication: FIPS 199, Standards for Security
Categorization of Federal Information Systems, NIST, 2004,
http://csrc.nist.gov/publications/fips/fips199/FIPS-PUB-199-final.pdf.
[16] Federal Information Processing Standards Publication: FIPS 200, Minimum Security
Requirements for Federal Information Systems, NIST, 2005,
http://csrc.nist.gov/publications/drafts/FIPS-200-ipd-07-13-2005.pdf.
[17] Swanson, Marianne, et al., NIST SP 800-18, Guide for Developing Security Plans for Federal
Information Systems, Revision 1, 2006, http://csrc.nist.gov/publications/nistpubs/800-18Rev1/sp800-18-Rev1-final.pdf.
[18] Swanson, Marianne, NIST SP 800-26, Security Self-Assessment Guide for Information Technology
Systems, 2001, http://csrc.nist.gov/publications/nistpubs/800-26/sp800-26.pdf.
[19] Stoneburner, Gary, et al., NIST SP 800-30, Risk Management for Information Technology Systems,
2002, http://csrc.nist.gov/publications/nistpubs/800-30/sp800-30.pdf.
[20] Ross, Ron, et al., NIST SP 800-37, Guide for the Security Certification and Accreditation of Federal
Information Systems, 2004, http://csrc.nist.gov/publications/nistpubs/800-37/SP800-37-final.pdf.
[21] Ross, Ron, et al., NIST SP 800-53, Recommended Security Controls for Federal Information
Systems, 2005, http://csrc.nist.gov/publications/nistpubs/800-53/SP800-53.pdf.
[22] Ross, Ron, et al., NIST SP 800-53A, Guide for Assessing the Security Controls in Federal
Information Systems, http://csrc.nist.gov/publications/nistpubs/800-53/SP800-53.pdf.
[23] Barker, William, NIST SP 800-59, Guideline for Identifying an Information System as a National
Security System, 2003, http://csrc.nist.gov/publications/nistpubs/800-59/SP800-59.pdf.
[24] Barker, William, NIST SP 800-60 Version 2.0, Guide for Mapping Types of Information and
Information systems to Security Categories, 2004, http://csrc.nist.gov/publications/nistpubs/80060/SP800-60V1-final.pdf.
[25] Souppaya, Murugiah, et al., NIST SP 800-70, Security Configuration Checklists Program for IT
Products Guidance for Checklists Users and Developers, 2005,
http://csrc.nist.gov/checklists/docs/SP_800-70_20050526.pdf.
[26] Bowen, Pauline, et al., NIST SP 800-100, Information Security Handbook: A Guide for Managers,
2006, http://csrc.nist.gov/publications/drafts.html#sp800-100.
[27] TR99.00.02: Integrating Electronic Security into the Manufacturing and Control Systems
Environment, ISA, 2004.
[28] NIST Security Configurations Checklists Program for IT Products, http://checklists.nist.gov/
PLC & SCADA Wireless Control System

100 Bibliography

PLC & SCADA Wireless Control System

You might also like