Real Time Control Engineering
Real Time Control Engineering
Tian Seng Ng
Real Time
Control
Engineering
Systems and Automation
Studies in Systems, Decision and Control
Volume 65
Series editor
Janusz Kacprzyk, Polish Academy of Sciences, Warsaw, Poland
e-mail: [email protected]
About this Series
The series “Studies in Systems, Decision and Control” (SSDC) covers both new
developments and advances, as well as the state of the art, in the various areas of
broadly perceived systems, decision making and control- quickly, up to date and
with a high quality. The intent is to cover the theory, applications, and perspectives
on the state of the art and future developments relevant to systems, decision
making, control, complex processes and related areas, as embedded in the fields of
engineering, computer science, physics, economics, social and life sciences, as well
as the paradigms and methodologies behind them. The series contains monographs,
textbooks, lecture notes and edited volumes in systems, decision making and
control spanning the areas of Cyber-Physical Systems, Autonomous Systems,
Sensor Networks, Control Systems, Energy Systems, Automotive Systems, Bio-
logical Systems, Vehicular Networking and Connected Vehicles, Aerospace Sys-
tems, Automation, Manufacturing, Smart Grids, Nonlinear Systems, Power
Systems, Robotics, Social Systems, Economic Systems and other. Of particular
value to both the contributors and the readership are the short publication timeframe
and the world-wide distribution and exposure which enable both a wide and rapid
dissemination of research output.
123
Tian Seng Ng
School of Mechanical and Aerospace
Engineering
Nanyang Technological University (NTU)
Singapore
Singapore
Control technology has been in existence for the last 60 years. Throughout the
decades, many developments have evolved in control and automation engineering.
Especially, nowadays, when computers have become more popular, technology in
control has progress to combine with computer technology for faster and more
precise method of computations. Software control can take the place of hardwired
control system economically. Hence, new control methods for real-time systems are
progressively discovered and taught in institutions. Most engineering applications
involve control function. Broadly speaking, there are many types of control tech-
nology in engineering domain. We have the electrical and electronics control
design, microcontroller and embedded system programmings and control, as well as
the mechatronics control system. The low-level assembly programming language
performs basic control techniques as well as controlling the stepper motor. Besides,
we can find control applications in big and complex industrial system. Power
system analysis can predict, monitor and therefore, control the load flow network
system. PLC system enhances the design of the elevator control system. We study
process control engineering to apply the theory to the water control system. More
advanced control technology such as the neural network machine learning tech-
nology finds its application in the chemical control plant. Furthermore, computer
vision technique is being used widely in the manufacturing factories or the
industries. As can be seen, the usefulness of real-time control engineering is applied
to countless industrial applications.
The book introduces many different types of control with relevances to real life
control systems design. Illustrative diagrams, circuits programming examples and
algorithms show the details of the system function design. Readers will find various
real-time control automation engineering practices and applications for the modern
industries as well as the educational sectors.
vii
Acknowledgement
Thanks to the project supervisor, Dr. Fazlur Rahman, for his guidance on the topic:
control of process plant using the neural network. Gratefully thanks to Prof. Fok Sai
Cheong for his contribution to the control of electro-pneumatic mechanisms. Also,
appreciation goes to the technical staff Mr. Lim Chai Lye for assisting in the
servo motor control system modification. Besides, the author is also thankful to
Mr. Ang Kwee Leng, the engineer for giving his unassuming support on the
electrical system.
It was sad that the associate professor, Dr. Lim Tau Meng, had left us. His past
contribution to the mechatronics section is highly appreciated. The author would
also like to thank Prof. Yap Kian Tiong for his teachings and advises on micro-
controller system and Mr. Norbel Navarro for some of the microcontroller pro-
grammings. Not forgetting the support team assisting Prof. Yap on the
microcontroller section. They are Mdm Yap-Lee Koon Fong, Mrs. Pamela Loh,
Mrs. Grace Ho, Mrs. Josephine Loh, Mr. Seow Tzer Fook and Mr. Ng Jui Hock
helping in the engineering laboratory.
Appreciation is due to my family members and friends for their overall support
and patience. Without these people, the writing of the book would not have been a
success. Finally, I would like to thank NTU, School of Mechanical Engineering,
Division of Mechatronics and Design, for giving me the opportunity to make this
work a reality.
ix
Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Highlights of the Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Organisation of the Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Embedded Intruder System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1 Requirements and Assumptions . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Hardware Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Software Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 System Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3 Mechatronics . . . . . . . . . . . . . . . . . . ....... . . . . . . . . . . . . . . . 27
3.1 Liquid Level Control . . . . . . . . ....... . . . . . . . . . . . . . . . 27
3.2 Oscillating Planar. . . . . . . . . . . ....... . . . . . . . . . . . . . . . 29
3.3 Conveyor Inspection Using Shift Registers . . . . . . . . . . . . . . . 34
3.4 Modern Speed Control . . . . . . . ....... . . . . . . . . . . . . . . . 35
4 Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.1 Basic I/O Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.2 LCD and Keypad. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.3 Waveform Timings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.4 Pressure Sensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.5 Temperature Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.6 Stepper Motor Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.7 Serial Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5 Electronics Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.1 Servo Motor Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.2 Square Wave Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.3 PID Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.4 Control of an Electro-pneumatic Mechanism . . . . . . . . . . . . . . 87
xi
xii Contents
6 Electrical System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.1 Elevator Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.2 Programmable Logic Controller . . . . . . . . . . . . . . . . . . . . . . . 91
6.3 Ladder Diagram Control Structures . . . . . . . . . . . . . . . . . . . . 91
6.3.1 Part 1:- Indicating Lights . . . . . . . . . . . . . . . . . . . . . 93
6.3.2 Part 2:- Lift Door Open/Close . . . . . . . . . . . . . . . . . . 94
6.3.3 Part 3:- Lift Up/Down . . . . . . . . . . . . . . . . . . . . . . . 96
6.4 Safety Control Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7 Power Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.1 Power System Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.2 Newton Raphson Formulation . . . . . . . . . . . . . . . . . . . . . . . . 101
7.3 Load Flow Analysis Using Newton Raphson. . . . . . . . . . . . . . 104
8 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.1 Water Tank Control System . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.1.1 First-Order Derivation. . . . . . . . . . . . . . . . . . . . . . . . 115
8.2 Single Tank Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
9 Machine Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
9.1 Neural Network in Process Control . . . . . . . . . . . . . . . . . . . . 121
9.2 The Artificial Neurons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
9.3 Techniques Involved in the Controllers . . . . . . . . . . . . . . . . . . 123
9.4 NN Learning Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
9.5 Selection of the Learning Algorithms . . . . . . . . . . . . . . . . . . . 126
9.6 The Network Topology. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
9.7 MLP Backpropagation Network for Process Control. . . . . . . . . 130
9.8 Chemical Plant NN Feedback Control System . . . . . . . . . . . . . 133
9.8.1 Process Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
9.8.2 Process Verification . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.8.3 Process Improvement . . . . . . . . . . . . . . . . . . . . . . . . 137
9.9 Remote Operated Neural Network Control Plant . . . . . . . . . . . 138
9.9.1 Field Instrumentations. . . . . . . . . . . . . . . . . . . . . . . . 138
9.9.2 Scaling and Conversions . . . . . . . . . . . . . . . . . . . . . . 139
9.9.3 Control Valves . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.9.4 Wireless Transmissions . . . . . . . . . . . . . . . . . . . . . . . 140
9.10 Valves and Chemical Plant Tunings . . . . . . . . . . . . . . . . . . . . 142
9.10.1 Desired Chemical Mixture, Samples and NN Data . . . . 142
9.10.2 Chemical and Valves Calibration . . . . . . . . . . . . . . . . 142
9.10.3 Trial Test in Actual Plant . . . . . . . . . . . . . . . . . . . . . 143
9.11 Computerized Neural Network Control System . . . . . . . . . . . . 144
9.11.1 NN Real Time Control Plant . . . . . . . . . . . . . . . . . . . 144
9.11.2 Neural Network Control Valves . . . . . . . . . . . . . . . . . 145
9.11.3 Intelligent Advisor . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Contents xiii
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
List of Figures
xv
xvi List of Figures
xix
List of Flow Charts
xxi
List of Programs
xxiii
Chapter 1
Introduction
1.1 Objectives
The book introduces many different kinds of control systems and design. They
comprise of hardware and software for the real-time engineering control systems.
• Security alarm system is commonly being practiced in almost every organisa-
tions. It provides intruder detection during after office hours. We introduced the
study of the microprocessor controlled alarm system.
• Electronic circuits were built to accommodate each of the different design
structure. We construct various kinds of the mechatronics systems. Some are
• Chapter 7 illustrates the power flow techniques for network system analysis.
Programming examples in Pascal describes a clear view of how to monitor the
load flow system.
• Chapter 8 study the control characteristics of the water tank control system.
Experimental set characterises the single tank control system.
• Chapter 9 extends the plant process control by using neural networks. The topic
includes the use of the machine learning technique to control the liquid flow of a
chemical process plant by controlling the valves.
• Chapter 10 illustrates the use of computer vision. The developed algorithm
skeletonized the main outlines of the picture for control and application
purposes.
Chapter 2
Embedded Intruder System
A microprocessor is a powerful device used to control the input and output oper-
ations of an external device. It serves as a data storage element as well. There are
various stages of upgrade and development of the 8086 (16-bit) microprocessor
unit. Its applications are used widely in the commercialized and industrialised areas.
For example, it is used to perform arithmetic and logical operations inside of a
computer system. It enables high speed and large memory storage in computer
application, especially in the latest development of the computer system. Besides,
CISCO securities also incorporate microprocessor in their security systems.
A standard microprocessor can be programmed and interfaced to the external
devices to control and operate a remote control system or collect and perform data
operations. An intruder alarm system safeguards an organisation’s asset and
security. To implement the automation, security system, we need to look at the
drawing of the building floor plan and layout. Both the hardware and software
combine for the intruder system to work.
The chapter comprises of the detailed design of the microprocessor hardware as
well as software algorithms of a security system in the computer room. The scripts
described the system analysis, specifications, selection and design of the security
system. It also includes hardware interface design and software flow charts and
programs. The valuable experience gained and knowledge applied were briefly
described in the following few pages.
Hardware Requirements:
• 8086 CPU or its upgraded version
• Microprocessor clock signal of 5 MHz
• 8 KB EEPROM
• 4 KB RAM
• Switches: 5 numbers excluding the reset switch
– switch 1, 2, 3 for front, side and back door sensors
– switch 4 to turn on autotime switch
– switch 5 for external interrupt to alarm
• 7 segment LEDs (8 nos)
– 6 LEDs to display time in hrs, mins and secs
– 2 LEDs to display 30 s countdown.
System Analysis:
• At power up system reset and display blank until sw4 is activated.
• Upon pressing the switch, the system starts up and corresponding time of the
day is displayed.
• Security system starts from 19:00:00 pm to 07:00:00 am.
• System constantly checked the current time with the limit time.
• If matched, it checks the memory location (60020H) for data.
• After activation, only 30 s are allowed to enter the correct code.
• The system will trigger the alarm if 30 s expire without the correct code entered.
• The system will not trigger an alarm if the correct code is being entered within
the time.
• Data will be stored in the memory address (60020H) if someone had entered
between the time.
• Otherwise, no data in the location.
Stated Assumptions:
Software:
• Clock generator had no wait state.
• Delay of counting sequence omitted in the program.
• Six secret codes to enter including alphabetical letters within 30 s.
• Assumed program time is aligned to the real-time clock.
2.1 Requirements and Assumptions 7
Hardware:
• No buffer used for the output device as it is being connected to less than ten
output.
• The time colons is by other physical means without using 7-segments.
• External hardware interrupt service provided via interrupt type 60H.
• A reset button (normally closed) is physically connected to the microprocessor
via the supply line.
• 4 KB RAM excluding interrupt address.
• Interrupt vector uses another 1 KB RAM.
• 500 byte RAM piece exist.
The internal architecture of the CPU consisted of the bus interface unit and the
execution unit. They performed the fetch, decode and execution operations. The
microprocessor CPU registers enhanced speed processing of data. They are mainly
the general purpose registers; pointers and index registers; segment registers and
flag registers. The 8086 is used to operate in the minimum mode for single CPU
environment in the system. 5 MHz clock operation is designed using 8254A chip
and interfaced into the microprocessor. The crystal of the 8254A clock generator is
three times the microprocessor input clock. Alternatively, you can use 8284A clock
generator to generate a direct 5 MHz timer for the 8086/8088 microprocessor [20].
The selection of the memory or input/output operation enables 1 MB of memory
addresses and 64 KB of i/o addresses. The address lines share with the 16 bits data
lines. We use latches for latching the address lines in addition to another four
address lines. Making a total of 20 address lines. Therefore, it saves the spaces of
the microprocessor. Multiplexers are used in the address line so data will not go to
the wrong location when we change the address. At the other end, it is demulti-
plexed. The decoding circuits are used to enable one selection of the addresses at a
time. The memory used in the design is 24 KB or 8 KB EEPROM and 2 * 2 KB or
4 KB SRAM. We select static RAM for faster operation due to its non-volatile
characteristics. Moreover, we take also the advantages of eliminating the refreshing
circuit. The switches connect to the buffer 74LS244 for boosting the signal to the
microprocessor. Where latches, 74LS374 are being connected to the seven segment
LEDs. The purpose is for stabilizing the output ports. We described the selected
design with diagrams (see Figs. 2.1, 2.2 and 2.3).
8 2 Embedded Intruder System
VCC
74LS10
In the RAM decoding circuit of Fig. 2.4, the read ðRDÞ and the write ðWRÞ
operations enable the selections of the data read, and data write operations
respectively. We used logic gates to perform the functions of the combinational
logics for the addresses. Thus, RAM addresses from 60000H to 60FFFH in the
memory map are selectable.
In the EPROM decoding circuit, 2 nos of 74LS08 are required for the 7 2
input AND gates to be joined up for the eight inputs. A0 address forms the nec-
essary selection for the odd or even bank selection (see Fig. 2.5).
Next, we have an alternative solution to the RAM/ROM decoding circuit. The
stated assumption in the scenario is that the 1.5 KB and 0.5 KB RAM exists.
The circuit in the top left corner in Fig. 2.6 is derived from the following table.
The decoding map represents the 3 rows of memory addresses (see Table 2.1).
Following up is the input decoding device interfacing. The addresses for the
input devices range from 0060H to 007EH. The dip switches selections serve as the
data as well as the address lines input to the microprocessor unit. The addresses A0
to A4 are selectable by the dip switch input. The relevant dip switch selects the
active low for each of the matching input address. For example, each of the dip
switches represents each sensor. When any of the five sensors activates, a logic, ‘0’
will select the corresponding address input. So data for the selected address is input.
NOR gate helps to decode the address lines A9 to A12. Three of the dip switches
are replaceable by door sensors. The input keypad circuit can be designed from
address 0071H to 0076H (0000 0000 0111 0xxx) also. Alternatively, we can use
8279 chip for interfacing the keypad to the microprocessor (see Fig. 2.7).
2.2 Hardware Design
The output device as shown in Fig. 2.8 is interfaced to the 8 nos. of 7 segment
LED display. The seven segment LEDs are for hours, minutes, seconds and the 30 s
countdown as stated in the design assumption. We used the BCD to 7 segment
driver (74LS47) to light the LEDs. Thus, only the first 4-bit data is enough to
display the ten different numbers. The 74LS138 decoder is used to decode the
selectable output for display. The decoded output addresses are from 0050H to
0057H. The interrupt type 60H is input into the microprocessor once there is an
interrupt request for calling the interrupt subroutine. We can use input port A4 of
Fig. 2.7 to call the interrupt request as in Fig. 2.9. The microprocessor will
acknowledge the interrupt request to accept the interrupt type.
We include a flow chart, (see Flowchart 2.1) of the program which consists of the
following functions:
(a) The auto time will start only when switch 4 activates.
(b) The program consistently scans for the time between 19:00:00 and 07:00:00
interval.
(c) Next, if it is within the time interval, a subroutine will check for the external
interrupts. In another word, we scan switch 1 (front door), switch 2 (back
door) or switch 3 (side door) for anyone entering the room. If switches are not
activated, it will loop back and forth the main program and the subroutine until
the time is not within the time interval.
2.3 Software Design
Fig. 2.7 Input device interface. Note Dip sw5 activates the input port number 006FH and so on
15
16
74LS47
0050H
0051H
0052H
A4
A6 0053H
0054H
0055H
0056H
A3 0057H
A5
A7
A15
0050H 0057H
0 0101
(d) If any one of the switches is activated, it does two things. First, it activates the
30 s countdown. At the same time, it will also check for the correct code
sequence entered. The program will check for one input code each time one
second passes, by going through the delay procedure. It will compare with the
correct code sequence of the six secret codes. Therefore, the program allows
the intruder to key in a total of 30 code words before it sounds the alarm.
Normally, to get the correct security password take 6 s to key in. But if the
user key in wrongly, he may take more than 6 s to do it. If the system detects
the correct code within 30 s, it will drop off the alarm.
The range between the first and the last wrong code entered is 54–74
instructions (only consumes 59.2 ls) within the program. If a second passes
and no code input, it will take the empty code and compare with the correct
code. Since it does not match, the outcome is that it will loop to re-match the
code again. Thereby, it lost one second. Similarly, if any of the subsequence
code does not match it will also losses a second.
A 16-bit loop will consist of approximately 65,600 maximum instructions.
Calculations for each second delay takes about 65,540 instructions per
loop. The program consumes a total of 0.052 s per loop (the calculated values
is: 4 machine cycles 200 ns per instruction, for 65,600 instructions).
Therefore, the program scans 19 loops for an entered code within a second. So
overall, the program may check between 28 and 30 times each time a code is
entered, to test for the correct secret code sequence within the 30 s.
18 2 Embedded Intruder System
(e) If any of the door sensors is activated and left opened while the code sequence
enter is correct, the program will continue to run auto time restarting the 30 s
countdown, to scan for new input codes to be entered. If it senses no input
entered, it will still sound the alarm if 30 s is up. So, all the doors should be
shut immediately after entering, between 19.00 pm and 07.00 am. Another
scenario is, if any of the doors are open and close after entering the correct
codes, the person will still have to re-enter the codes again.
(f) All the codes entered within the 30 s will be saved.
(g) If 30 s expired before we enter the correct code sequence, the subroutine
triggers an external interrupt to an alarm.
(h) All the above scenarios will activate the alarm accordingly unless the power
switch is turned off, or the switch 4 is not on. The alarm is turn off using the
reset button. The power switch, the reset button and switch 4 is highly secured.
Mechatronics systems are widely utilized in the automation, industries. The prac-
tices involve the controls of electronics for mechanical systems. In this chapter, we
present the liquid level control system, the oscillating planar mechanical system, the
conveyor inspection using shift registers and the modern speed control unit.
The latching circuit for filling the water into a tank or beaker is as shown in
Fig. 3.2. We can conduct a simple experiment by using a solenoid valve to open
and close an opening for controlling the flow of water into a beaker. The operation
is simply a latched circuit for water flowing to a beaker. The apparatus requires a
water carrying container hooked onto a standing rod structure and a beaker. The bar
structure only has a square base and an upright standing bar or rod. The square base
holds the weight of the water container. We placed a beaker underneath the water
carrying container, on the base frame structure. A solenoid is attached below to the
container to open or close the valve. The solenoid valve is at normally closed when
not energise, to stop the water from flowing out of the container. A small pipe fixed
downward from the container leads the water to fill up the beaker.
The sensors required are a proximity sensor, a latch button and a spring button.
The latch button ‘S2’ is latched for the operation of the system. The operation starts
by pressing the ‘LS1’ spring button. The output of the ‘OR’ gate is activated.
The LED is lighted up by the logic ‘1’ from the ‘OR’ gate output. The signal also
enters the buffer to energise the solenoid valve. Thus, the valve will open and water
start to flow out from the container into the beaker. The output of the ‘OR’ gate also
goes into the Pin 1 of the ‘AND’ gate. So the circuit is latched as the ‘AND’ gate
outputs a logic ‘1’ signal. In the circuit, the 1 kΩ resistors are being used as the
pull-down resistors. We connect the 1.8 kΩ resistors to the transistor base. The
470 Ω resistor serves as the pull-up resistor for the proximity sensor.
We placed the proximity switch at a certain level of the beaker. So that when the
water level reaches the level, the proximity switch will be activated to stop the
water flow. The ‘TIP-121’ transistor will be de-activated and a logic ‘0’ will go to
the pin 2 of the ‘AND’ gate. Thus, the output of the ‘AND’ gate will be zero. The
output LED will not lit up, and the solenoid valve will be de-energised. So the
opening of the valve will close back to stop the water from flowing out of the pipe.
If the latched button is de-latched during the water filling operation, it will stop the
water filling process. To continue the operation, we had to reset the latch switch to
the connected position. Then we pressed the ‘LS1’ spring button to continue the
water filling process (Fig. 3.1).
An illustration of a simple program written in the PBasic language is as shown
in the program P3.1. We make use of the Basic Stamp microcontroller to perform
similar function. The microcontroller connects to three input ports 5, 6 and 7 for
sensings. Input port 7 connects to the proximity sensor. While we connect the
input ports 5 and 6 to LS2 and S2 (latched) switches respectively. If both buttons
are turned on, it will activate the solenoid to open the valve to fill the beaker or
water tank. The proximity sensor (to IN7) fixed at a certain level of the tank must
also be cleared to begin the water flowing process. The output port 10 is con-
nected to activate the solenoid valve via a buffer and a TIP-121 transistor.
Similarly, a 1.8 kΩ resistor is connected to drive the base of the transistor. The
proximity sensor is activated when the water level reaches its height. Thereby
3.1 Liquid Level Control 29
--------------------------------------------
Program 3.1: Liquid Level Control
--------------------------------------------
'{$STAMP BS2}
DIRS=%0000000010000000
again IF IN7=1 AND IN5=1 THEN do
you:OUT10=0 ‘ water stop
GOTO again
do: IF IN6=0 OR IN7=0 THEN you
OUT10=1 ‘ water flow
GOTO do
causing IN7 to input a zero, resulting output port 10 to output a logic low to the
transistor. It will deactivate the solenoid, and close the valve to stop the water
from flowing out. By making use of the program, we can replace the hardware
circuits (Fig. 3.3).
In this section, we combined the field of electronics with mechanical to build and
control an oscillating planar. The operation begins with the preset switch pressed
when powered up. The first D-latch on top presets with a logic ‘0’ and the second
D-latch below clears with a logic ‘0’. So the oscillating planar starts to turn to the
right. As the planar rotates, the slotted optical switch will be blocked and activates
again. It triggers clock input to the D-latches. As a result, a logic ‘0’ now output
from the top D-latch. The logic ‘1’ now appear at the output of the lower D-latch. It
reverses the turning direction of the oscillating planar. It will again activate both the
optical switches fixed on both sides of the planar’s edge. A second trigger to the
D-latches will stop the planar. Now both the outputs of the D-latches are zero.
Therefore, we can see that the function of the preset switch is to reset the position of
the oscillating planar to its starting position. The circuit is operated by a start switch
to hold a logic ‘1’ to pin 2 of the ‘AND’ gate. We begin the oscillating function by
pressing the preset switch. It triggers a logic high and a logic low from the output of
30
3 Mechatronics
330R
the D-latches to turn the planar. As the slotted optical switches senses, a clock
trigger to the D-latches will output a logic ‘0’ to the ‘C’ input of the motor. At the
same time logic ‘1’ enters the ‘D’ input of the same motor simultaneously. It
changes the direction of the moving planar. The oscillating planar reverses direction
again when the optical switches activate a second time. The operation continues
until the ‘start’ holding switch stops. So we can see that we use the same button for
the start and the stop operation (Fig. 3.4 and Table 3.1).
The 4 diodes used for the DC motor are 1 A high speed diodes (Figs. 3.5, 3.6).
IN4001
gnd
3.2 Oscillating Planar
74LS74A
0.5R / 1w
----------------------------------------
Program 3.2: Oscillating Planar
----------------------------------------
The circuit implements shift registers to control a diverter solenoid. Four negative
edge-triggered J-K flip flops as well as a slotted optoisolator, are the main electronics
components for the circuit. The far end of the conveyor is where we located the
diverter. We mount small pieces of block indicator at a fixed distance along the
conveyor system. The block indicator will energize the slotted switch at distance
intervals as the conveyor rolls. The start of the conveyor and the diverter end is three
block indicators away. There is indicator block at the starting point of the conveyor
system where we placed the material. We used a reject switch or a proximity sensor
to detect material put on the conveyor system. A proximity sensor is mounted at the
beginning of the conveyor system where we placed the material. The output of the
first J-K flip-flop will light up if something is on the conveyor system. As the
conveyor rolls, the J-K flip-flops will be activated when the indicator block covers
the slotted optoisolator. It will lit up the second LED at the output of the second J-K
3.3 Conveyor Inspection Using Shift Registers 35
flip-flop if a material is present. When the material travels to the end of the diverter,
the output of the fourth J-K flip-flop will be energised. At the same time, the diverter
solenoid will be energized to divert the material placed on the conveyor system. The
LEDs indicate which zone the material has arrived in the midst of travelling in the
conveying system. If we put two materials subsequently in each different indicator
block, two LEDs will light up each time the indicator blocks energize the slotted
optical sensor. When nothing is on the conveyor, the far end diverter will not be
activated as the last J-K flip-flop outputs a zero (Figs. 3.7, 3.8).
25ms
It causes a positive spike to the trigger input of the timer. The rate of discharge
depends on Cdiff and Rdiff (Figs. 3.9, 3.10).
The RC differentiator circuit time constant is 0.15 ms as we used a 1.5 kΩ and
the 0.1 uF passive components. We determined the period by using resistors and
capacitor of 18 kΩ and 1 uF respectively. By the connection of the 0.01 uF
capacitor to the control input, the 555 timer oscillates at 50 % duty cycle, with a
period of 25 ms. The calculation for the timing of the first timer circuit is as follow.
T ¼ 2 0:7 18 k 1u
ð3:1Þ
¼ 25:2 ms:
We connected the resistor and capacitor from the second timer as 10 kΩ and 2.2 uF
respectively.
As can be seen, it forms the variable time peak of 22 ms. Therefore, the maximum
duty cycle of the second timer is reachable at (22 ms/25 ms) 88 % efficiency. The
40 v permanent magnet motor is controllable with a maximum duty cycle of 88 %.
The motor’s duty cycle is variable from 10 to 88 % by varying the control source to
the second one-shot timer from 1.8 to 10 V. We control the mechanical shaft power
of the permanent magnet motor by the control source. A +40 V DC source powered
the permanent magnet motor. Low pass filter can be installed to the motor when
needed.
Chapter 4
Microcontroller
Load and run program 4.1. Note that port A connector is internally being connected
to 10 kΩ pull-up resistors. Observe how to read in a 8 bits information via Port A.
Note that the address of Port A is $1000. DDRA address at $1001. The register
controls whether the bit 0–7 use as input (Low) or output (High) pins. Index
addressing with register X. CLI (clear interrupt mask) to enable interrupts by setting
I bit to zero. By doing so, we enable the software debugger. Check the value at
address $0050 using the debugger. It should give you the value indicated by the dip
switches. All files associate with the file extension .a11 in the assembly format
(Fig. 4.1).
---------------------------------------
Program 4.1: Read Dip Switch
---------------------------------------
porta equ 0
ddra equ 1
org $8000 ; Micro-P starting address
cli ; enable the debugger
ldx #$1000
ldaa #$00
staa ddra, x ;set poara as input
again ldaa porta, x ;load dip switch status
staa $0050 ;store dip switch status
bra again
----------------------------------------------
Program 4.2: Write to Output LEDs
----------------------------------------------
Note that port B (Fig. 4.2) of the output circuit is connected internally to
ULN2803A Darlington transistors. You can load and run the program 4.2 to
observe the following points. How to output a 8 bits output via Port B. The address
of Port B is $1060. That is it is Port B of the basic microprocessor, not the Port B of
the 68HC11 microcontroller. We observe the branching and looping techniques.
----------------------------------------------
Program 4.3: Push Button & Buzzer
----------------------------------------------
portd equ 8
ddrd equ 9
with register X. We used branching and looping. The high current Darlington
transistor arrays are for driving the buzzer load.
In basic, both programs 4.4 and 4.5 are the same. They read in the PE2 port for
the A/D conversion from the potentiometer connected to it (see Fig. 4.4). Program
4.6 can read in any selected port to be read (PE0 to PE3). In the case, PE2 is being
read at the address $1033 in the program. In program 4.7, we measure at pin6 of
portA the sampling period.
---------------------------------------
Program 4.4: A/D Converter 1
---------------------------------------
org $0100
adctl equ $30 ; option registerr
addr equ $33 ; store conversion result
begin: ldx #$1000 ; reads in analog 0 – 5v into PE2 channel
bset $39, x $80
bclr $39, x $40
off: ldab #$02
stab adctl, x ; select channel PE2 clr scan
check: ldaa adctl, x ; and mult bits of adctl
brclr adctl, x $80 check ; read status until conversion ends
ldaa addr, x ; If CCF=1 read results in ADR3 register
staa $ec00
bra off ; halt here
org $fffe
fdb begin
---------------------------------------
Program 4.5: A/D Converter 2
---------------------------------------
org $0100
begin: ldx #$1000 ; reads in analog 0 – 5v into PE2 channel
bset $39, x $80
bclr $39, x $40
off: ldab #$02
stab $1030 ; select channel PE2 clr scan
check: ldaa $1030 ; and mult bits of adctl
bpl check ; read status until conversion ends
ldaa $1033 ; If CCF=1 read results in ADR3 register
staa $ec00
bra off ; halt here
org $fffe
fdb off
44 4 Microcontroller
---------------------------------------
Program 4.6: A/D Converter 3
---------------------------------------
org $0100
adctl equ $30 ; option registerr
addr equ $33 ; store conversion result
begin: ldx #$1000 ; reads in analog 0 – 5v into PE2 channel
bset $39, x $80 ; bit in ADPU option reg to
bclr $39, x $40 ; power up and use E clk
off: ldab #$30 ; use PE0-PE3 mult continuous scan=1
stab adctl, x ; select channel PE2 clr scan
again: ldaa adctl, x ; and mult bits of adctl
brclr adctl, x $80 again ; read status until conversion ends
ldaa addr, x ; channel PE2 at $1033
staa $ec00
bra again ; get next continuous scan
org $fffe
fdb begin
---------------------------------------
Program 4.7: A/D Converter 4
---------------------------------------
org $0100
adctl equ $30 ; This program measures
addr equ $33 ; the sampling period by
begin: ldx #$1000 ; sending 1 out pin A6
ldaa #$40 ; pin 6
bset $39, x $80 ; bit in ADPU option reg to
bclr $39, x $40 ; power up and use E clk
off: ldab #$30 ; use PE0-PE3 mult continuous scan=1
stab adctl, x ; select channel PE0 – PE3 clr scan
again: ldaa adctl, x ; and mult bits of adctl
brclr adctl, x $80 again ; read status until conversion ends
staa $1000 ; pulse A6
eora #$40 ; reverse pulse A6
undone:bra again ; get next continuous scan
org $fffe
fdb begin
Next, the LCD program 4.8 teaches how to program in assembly language the
following extension .a11 assembly file. How to display a character of 8 bits word on
LCD, via port M, 4 bits nibble at a time. You can replace “Welcome to the Lab”
with own text. You also learn how to move the cursor to the start of each line. The
flow chart illustrates the flow of steps involved in the program. The LCD used is a
16 × 2 characters module (Flowchart 4.1).
4.2 LCD and Keypad 45
----------------------------------
Program 4.8: LCD Display
----------------------------------
; ****************Subroutine************************
; lcdnib, lcdnibw – send code to LCD through PORTM
; lcdtempo – delay
; lcdputc – arrange command code to be sent
; lcdinit – set up LCD
; lcdput – arrange character code to be sent
sect data
lcdbuf: rmb 32 ; reserve 32 bytes of ram as buffer for storing
; characters to be displayed
sect text
lcdnib: ; send code to LCD through PORTM (pm0 – pm3)
andb #$4F
orab #$30
stab PORTM
tba
oraa #$80
staa PORTM ; 1 to 500ns
stab PORTM
rts
lcdnibw:
bsr lcdnib
ldd #20 ; delay 40us (20 x 2us)
bsr lcdtempo
rts
lcdtempo:
subd #1 ; 1unit in reg D x 2us (12MHz)
bne lcdtempo
rts
lcdputc: ; arrange command code – send 4 bits at one time
; to LCD screen, higher nibble goes first
pshb ; retain the content of ACCB
lsrb ; shift out lower nibble
lsrb
lsrb
lsrb
bsr lcdnib; send higher nibble
pulb ; restore ACCB
bsr lcdnibw ; send lower nibble
rts
lcdinit: ; set up the LCD for 4 lines interface, 2 line mode,
; 5x7 dot format, increment, display shift off.
Ldab #$3F
stab PORTM
ldd #8000
bsr lcdtempo ; 15ms
ldab #3
48 4 Microcontroller
lsrb
lsrb
lsrb
lsrb
orab #$40
bsr lcdnib ; send higher nibble
ldab 0, x
orab #$40
bsr lcdnibw ; send lower nibble
inx
cpx #lcdbuf+12
bne lcdp1
rts
The next program for the keypad and LCD demonstrates how to read in char-
acters from Port D & G of connector D, 4 bits at a time. You will learn how to
change the content of the conversion table and check the LCD character map. The
keypad used is a 16 keys keypad. We use a keypad encoder as shown in Fig. 4.5,
for the keypad connections (Flowchart 4.2).
50
4 Microcontroller
-------------------------------------
Program 4.9: Keypad & LCD
-------------------------------------
diagram with the other to find out the complexities of the other keypad and LCD
circuit diagram. You may also note the simplicity of using the high levels language
instead of the assembly language (Fig. 4.6).
--------------------------------------------------------
Program 4.10: Keypad & LCD In C Program
--------------------------------------------------------
#include “hc11.h”
#define PORTM *(unsigned char *)(_IO_BASE + 0x62)
#define PORTN *(unsigned char *)(_IO_BASE + 0x63)
#include <stdio.h>
#include <math.h>
void lcdinit(void);
char keyget(void);
double e;
void main(void)
{ int i;
lcdinit( );
for (i=2;;)
{ e = sqrt(i);
if (i>=0)
print(“ sqrt(%d)=%f”, i, e);
i= keyget( ) – ‘0’; } }
/**************************Lcd*****************************
//PORTM bit7=LCD EN = 0 by default
//PORTM bit4=DAC CS = 1 by default
#define LCDCOLS 16
#define LCDLINES 2
#define LCDBUFSZ (LCDCOLS*LCDLINES)
char lcdbuf[LCDBUFSZ];
lcdnib(3); /* lcd = 3 */
lcdwait(1); /* 4.1ms */
lcdnib(3); /* lcd = 3 */
lcdwait(0); /* 0.1 ms */
lcdnibw(3); /* lcd = 3 x 40us */
lcdnibw(2); /* lcd = 2 x 40us */
lcdputc(0x28 | (LCDLINES-1)); /*LCDLINES:info for the sim11*/
lcdputc(0x08); /* display off */
lcdputc(0x01); /* clear display */
lcdwait(1);
lcdputc(0x06);
lcdputc(0x0E); /* display on, cursor */
for (s=lcdbuf; s<lcdbuf + LCDBUFSZ; s++)
*s = ‘ ‘;
putchar(‘ ‘); }
int putchar(char c) /*library function*/
{ char *s;
for (s=lcdbuf; s<lcdbuf + LCDBUFSZ – 1; s++)
*s = s[1];
*s = c;
lcdputc(0x80);
for (s = lcdbuf; s<lcdbuf + LCDBUFSZ; s++)
{ if (s==lcdbuf + (LCDBUFSZ/2))
lcdputc(0x80 + 0x28);
lcdnib( (*s >>4) | 0x40);
lcdnibw(*s | 0x40); }
return c; }
/**************Keyboard*************************/
char keyget(void)
{ static char old_key;
char x = 0;
#if 0 // keypad 3 x4
PORTM = 0x37; /* K=0 J=1 H=1 G=1 */
if ((PORTN&0x08)==0) x = ‘1’;
if ((PORTN&0x04)==0) x = ‘2’;
if ((PORTN&0x02)==0) x = ‘3’;
PORTM = 0x3B; /* K=1 J=0 H=1 G=1 */
if ((PORTN&0x08)==0) x = ‘4’;
if ((PORTN&0x04)==0) x = ‘5’;
if ((PORTN&0x02)==0) x = ‘6’;
PORTM = 0x3D; /* K=1 J=1 H=0 G=1 */
if ((PORTN&0x08)==0) x = ‘7’;
if ((PORTN&0x04)==0) x = ‘8’;
if ((PORTN&0x02)==0) x = ‘9’;
PORTM = 0x3E; /* K=1 J=1 H=1 G=0 */
58 4 Microcontroller
if ((PORTN&0x08)==0) x = ‘*’;
if ((PORTN&0x04)==0) x = ‘0’;
if ((PORTN&0x02)==0) x = ‘#’;
#else // keypad 4 x 4
PORTM = 0x37; /* K=0 J=1 H=1 G=1 */
if ((PORTN&0x08)==0) x = ‘C’;
if ((PORTN&0x04)==0) x = ‘B’;
if ((PORTN&0x02)==0) x = ‘0’;
if ((PORTN&0x01)==0) x = ‘A’;
PORTM = 0x3B; /* K=1 J=0 H=1 G=1 */
if ((PORTN&0x08)==0) x = ‘D’;
if ((PORTN&0x04)==0) x = ‘9’;
if ((PORTN&0x02)==0) x = ‘8’;
if ((PORTN&0x01)==0) x = ‘7’;
PORTM = 0x3D; /* K=1 J=1 H=0 G=1 */
if ((PORTN&0x08)==0) x = ‘E’;
if ((PORTN&0x04)==0) x = ‘6’;
if ((PORTN&0x02)==0) x = ‘5’;
if ((PORTN&0x01)==0) x = ‘4’;
PORTM = 0x3E; /* K=1 J=1 H=1 G=0 */
if ((PORTN&0x08)==0) x = ‘F’;
if ((PORTN&0x04)==0) x = ‘3’;
if ((PORTN&0x02)==0) x = ‘2’;
if ((PORTN&0x01)==0) x = ‘1’;
#endif
if (x == old_key)
return 0;
old_key = x; return x; }
-------------------------------------------
Program 4.11: Square Wave Timer
-------------------------------------------
regbas equ $1000 ; bas address
porta equ $0 ; port A
tcnt equ $0e ; timer counter
toc3 equ $1a ; timer output compare 3
tmsk1 equ $22 ; timer interrupt mask 1
tflg1 equ $23 ; timer interrupt flag 1
tctl1 equ $20 ; timer control 1
; outputsquare wave signal at bit5 of porta
org $8000 ; program starts at $8000
cli
main: ldx #regbas
ldaa #%00100000
staa tmsk1, x ; OC3I interrupt enable
staa tflg1, x ; send a one to clear the OC3F flag
ldaa #%00010000
staa tctl1, x ; OM3:OL3=0:1;toggle TOC3 output after a successful compare
ldd tcnt, x ; load current content of timer counter
addd #2000 ; added by 2000 counts (333nsec per count, total up 0.67msec)
std toc3, x ; store the result in compare register TOC3
undone: bra undone ; do something useful here
;***********interrupt subroutine*******************************
rtoc: bset tflg1, x $20 ; send a “one” to clear the OC3F flag
ldd #4000 ; set high or low period for 400x333 = 1.332msec
addd tcnt, x ; store the value in compare register
std toc3, x ; interrupr generated when next tcnt = toc3
rti
;**************define interrupt vector address********************
org $ffe4
fdb rtoc
-------------------------------------------------------------------
Program 4.12: PWM Signal of 400Hz at 2.5ms Period
-------------------------------------------------------------------
regbas equ $1000 ; bas address
porta equ $0 ; port A
tcnt equ $0e ; timer counter
toc3 equ $1a ; timer output compare 3
tmsk1 equ $22 ; timer interrupt mask 1
tflg1 equ $23 ; timer interrupt flag 1
tctl1 equ $20 ; timer control 1
hi_time equ 3000 ; high period 3000 cnts (333ns per count)
org $8000 ; program starts at $8000
cli
main: bsr initoc3 ; set up timer output compare 3, TOC3
undone: nop
bra undone
;*******************subroutine**********************
Initoc3: ldx #regbase
ldaa #$20
staa porta, x ; set PA5 high first
staa tmsk1, x ; OC3I interrupt enable
staa tflg1, x ; send a “one” to clear OC3F interrupt flag
staa tctl1, x ; OM3: OL3 = 1:0; set PA5 low upon interrupt
ldd tcnt, x ; load current content of timer counter
addd #50 ; added by 50 counts, initial setup before interrupt occurs
std toc3, x ; store the result in compare register TOC3
rts
;***********interrupt subroutine*******************************
rtoc3: ldx #$1000
ldaa porta, x ; check porta PA5 high or low
bita #$20
beq low
high: ldd tcnt, x
4.3 Waveform Timings 61
The next program can perform three functions with the external connections.
Refer to the circuit diagram for the program. The optical or slotted switch (con-
nected to PA0) is used as an input device to start the motor. After starting the motor,
the microcontroller can ignore the input signal from the slotted switch. Note 1: It is
important to note that to establish the correct initial status of the slotted switch the
power supply to the optical switch and motor must be turned on before turning on
the microcontroller. Note 2: After you have loaded the program, sometimes
pressing ‘Go’ does not work as expected. If this happens, press the Reset switch
instead of ‘Go’.
The external rotary potentiometer connects to the A/D converter (PE2) port E.
We use the potentiometer to control the motor speed. Depending on the converted 8
bit reading at PE2, three distinct speed levels are set accordingly.
Note: Under the label ‘low’ in the interrupt subroutine, the value
(#7500-hi_time) should be added to Accumulator D. You may refer to the diagram
in Fig. 4.7 for the PWM control of DC motor. The A/D pulse width varying circuit
is the same as Fig. 4.4 A/D converter. Port E is only a 8 bit read in port for A/D
converter. The third function is the inclusion of the XIRQ interrupt subroutine to
stop the motor. We connect a push button to the X connector’s XIRQ pin of the
microcontroller unit.
62 4 Microcontroller
start motor
stop motor
------------------------------------------------------------------------
Program 4.13: PWM Motor Control With A Potentiometer
------------------------------------------------------------------------------------
Smart sensors can adjust their interface outputs to the receiving appliances. But
there are factors exist that produce errors in the measuring sensors. Factors to
consider are scaling (static range) and offset voltages, drift due to temperature after
prolonged operations in a non-cooled space, noise margins and finally, bandwidth
for dynamics, frequency-related measurements. Therefore, signal conditioning
circuits are often necessary for better interpretation and presentation of the
incoming signal from the sensors into the microcontroller.
The setup in the figure measures the air pressure in the host line using the
SCX01DNC pressure transducer. Verify the resistors are correct to give the desired
output equations. We can vary the input pressure and plot the digital values
66
converted by the 68HC11 A/D converter. The oscilloscope can be used to find the
time delay from the instance of pressure change to the time of complete digital
conversion by the processor, that is, the duty cycle of the system. Most A/D
converters lose their accuracy when the voltages come close to the rail values. We
can improve it by changing the resolution to the A/D converter. The circuit for the
pressure detector requires a gain to amplify the signal large enough to view or use
for other activities. The amplifiers simply do the job. Any of the A/D converter
programs (P4.4–P4.7) can be used to measure the converted signal values
(Fig. 4.8).
Why is the standard 741 Op Amp not good enough? It gives an offset of 6 mV
and drift of 15 mV/°C. The BJT is also susceptible to noise from RF rectification.
So, let say we want to amplify the signal to a magnitude of 100, for a temperature
sensing of 100 mV/°C. We will have an offset of 6 °C and a drift of ±7 °C! We
must use a more precise CMOS-based amplifier. The circuit for the temperature
measurement is as shown in the diagram. AD590 is the temperature sensor. The
resistors are chosen to give a slope of 5. Trim pots are necessary to ensure this as
well as to remove offset voltage at 0 °C. Use a hot blower to increase the
measured temperature. We measure the Vo into the portE of the microcontroller.
Vo = (50 mV/°C) * T, where T represents the temperature measured. We can
make use of any of the A/D converter program 4.4–4.7 to detect the signal into
the microcontroller unit. We can then compare and verify the voltage signal with
a thermometer (Fig. 4.9).
We can program the 68HC11 microcontroller unit to drive a stepper motor. The
stepper motor we use needs a 5 V input power supply. Power MOSFETs for
example, the BUZ12 n-channel transistors are used to switch on the stepper
motor. The terminals of Port A of the MCU connects to output to the gates of
each transistor. The stepper motor has four coils to be activated in a sequential
68
manner to rotate the motor. IN4001 diodes are used as free-wheeling diodes to
protect the motor coils when the transistors are de-activated. It helps to relieve
the stored charges in the coils when the transistors are turned off. So the motor
coils are protected from burnings. Three methods used can activate and energise
the motor. They are the full phase, full step and half step modes. The three
programs written in assembly language for the 68HC11 microcontroller illus-
trates the different techniques used to energise the four motor coils for rotating
the motor. Only the correct sequence of turning on the phase of the coils will
activate the motor to turn in a continuous direction. The 68HC12 family has
slightly different configurations in the registers. We can just change the data
direction register, and the data port register addresses in the program, to perform
the same function (Fig. 4.10).
------------------------------------------
Program 4.14: Two Phase Mode
------------------------------------------
;now give short delay before reversing (share the use of the delay subroutine)
ldy #25
shdel1 jsr delay
dey
bne shdel1
;now rotate shaft ccw by 1 rev (200 steps)
;again use the Y index reg as a counter
ldy #50
revccw jsr ccw
dey
bne revccw
4.6 Stepper Motor Control 71
;now give another short delay before reversing again(share the use of the delay
;subroutine)
ldy #25
shdel2 jsr delay
dey
bne shdel2
jmp again
;subroutine to step through 1 cycle of full-step mode in
;clockwise direction
cw ldaa #$c0 ;step1 of cycle(coilsA+B=on)
staa $1000
jsr delay
ldaa #$60 ;step2 of cycle(coilsB+C=on)
staa $1000
jsr delay
ldaa #$30 ;step3 of cycle(coilsC+D=on)
staa $1000
jsr delay
ldaa #$90 ;step4 of cycle(coilsD+A=on)
staa $1000
jsr delay
rts
;subroutine to step through 1 cycle of full-step mode in
;counter clockwise direction
ccw ldaa #$30 ;step3 of cycle(coilsC+D=on)
staa $1000
jsr delay
ldaa #$60 ;step2 of cycle(coilsB+C=on)
staa $1000
jsr delay
ldaa #$c0 ;step1 of cycle(coilsA+B=on)
staa $1000
jsr delay
ldaa #$90 ;step4 of cycle(coilsD+A=on)
staa $1000
jsr delay
rts
;delay routine works close to pull-in speed of motor
delay ldx #500 ;
del1 dex
bne del1
rts
72 4 Microcontroller
------------------------------------
Program 4.15: Full Step Mode
------------------------------------
ldy #25
sdel2 jsr delay
dey
bne sdel2
jmp again
;subroutine to step through 1 cycle of full-step mode in
;clockwise direction
cw ldaa #$80 ;step1 of cycle(coilA=on)
staa $1000
jsr delay
----------------------------------------
Program 4.16: Half Step Mode
----------------------------------------
ldy #100
hdel2 jsr delay
dey
bne hdel2
jmp again
;subroutine to step through 1 cycle of half-step mode in
;clockwise direction
cw ldaa #$80 ;step1 of cycle(coilA=on)
staa $1000
jsr delay
ldaa #$c0 ;step2 of cycle(coilA+B=on)
staa $1000
jsr delay
ldaa #$40 ;step3 of cycle(coilB=on)
staa $1000
jsr delay
ldaa #$60 ;step4 of cycle(coilB+C=on)
staa $1000
jsr delay
ldaa #$20 ;step5 of cycle(coilC=on)
staa $1000
jsr delay
ldaa #$30 ;step6 of cycle(coilC+D=on)
staa $1000
jsr delay
ldaa #$10 ;step7 of cycle(coilD=on)
staa $1000
jsr delay
ldaa #$90 ;step8 of cycle(coilD+A=on)
staa $1000
jsr delay
rts
;subroutine to step through 1 cycle of full-step mode in
;counter clockwise direction
ccw ldaa #$10 ;step7 of cycle(coilD=on)
staa $1000
jsr delay
ldaa #$30 ;step6 of cycle(coilC+D=on)
staa $1000
jsr delay
ldaa #$20 ;step5 of cycle(coilC=on)
staa $1000
jsr delay
ldaa #$60 ;step4 of cycle(coilB+C=on)
staa $1000
jsr delay
ldaa #$40 ;step3 of cycle(coilB=on)
76 4 Microcontroller
staa $1000
jsr delay
ldaa #$c0 ;step2 of cycle(coilA+B=on)
staa $1000
jsr delay
ldaa #$80 ;step1 of cycle(coilA=on)
staa $1000
jsr delay
ldaa #$90 ;step8 of cycle(coilD+A=on)
staa $1000
jsr delay
rts
;delay routine works close to pull-in speed of motor note that pull-in speed of
;half step mode is approx twice that of full-step mode but note that angular
;velocity of pull-in speed for both modes is approx the same.
delay ldx #250 ;
del1 dex
bne del1
rts
We can use a computer to communicate with the microprocessor via RS232 connect
to COM1 of the microprocessor unit. A simple experiment starts by opening the
hyper terminal for the interface. We load a program into the microprocessor after
configuring the serial port of the computer. The serial communication may be set as
follow: 8 data bits; 1 stop bit; no parity bit; no flow control; 9600 baud rate. We
write the program in the high levels language. The function is to send a character
from the PC to the microprocessor. The microprocessor will in turn reply, with a
character. The character is to be input from the PC to the microprocessor through
the hyper terminal. It will receive and return a ‘character+1’. Example, you send an
‘A’ to the microprocessor, the hyper terminal will receive a ‘B’. If you send a ‘1’,
you receive a ‘2’.
4.7 Serial Communications 77
---------------------------------------------------
P4.17 PC Communication With MicroP
---------------------------------------------------
#include “startup.bas”
byte recu_pc
initrs232in()
Do ‘loop here
If recu_pc<>0 Then ‘character from PC
Putcharrs232(recu_pc+1) ‘send back to PC from MicroP
Recu_pc=0
End If
Loop
Function putcharrs232(x) ‘send a character back to PC
Do
loop until SCSR.7=1
SCDR=x
End Function
Function initrs232in() ‘rs232 initialisation
ASM ldx #rs232in ‘activate interrupt rs232
ASM stx $00FE
End Function
‘Character send to microprocessor
ASM rs232in: staa recu_pc
ASM rti
Chapter 5
Electronics Control
Laboratory experiment for the servo motor is set up to demonstrate and study the
characteristics of the implemented PID controller system. The motor’s controller
output is affected by the backslash. We eliminate the backslash by using the
backslashing gear for the dc motor. The gearbox of the motor can be of any
selection ratio for use. The joystick is used to jack in the input voltage reference
signal to the motor plant. The selectable switches are to select the relevant P, PI, PD
and PID controllers for analyses. We connect the controller output to the motor.
The BNC connector for the servo motor locates at the right-hand side of the
controller box. We can change each of the proportional, integrator and differentiator
parameters by the parameters’ values selection switches. The meters gives the
readout of the analog voltage readings. The actual readout connects to the oscil-
loscope through another BNC connector located at the bottom right of the control
box. From here, we study the transient and steady state characteristics of the motor
plant. Instead of manual input from the joystick, we can adjust the black knob to
input the ranges of frequencies to the servo motor. A square wave signal oscillator
is developed to eliminate the input signal required from the function generator.
Hence, we save space from the occupied function generator (Figs. 5.1 and 5.2).
As shown in the error detecting circuit, the voltage follower serves the purpose
of stabilizing the feedback signal from the motor plant. Following the differentiator
circuit to produce the error signal between the voltage signal feedback and the
desired input voltage signal from the square wave generator. This error signal then
feeds back into the PID controller circuit. We observe a gain of 1 in the differen-
tiator circuit. Figure 5.3 illustrates the full control circuit for the motor plant.
A square wave oscillator provides the input of the controller circuit with a desired
frequency of oscillation to study the motor. The circuit according to Fig. 5.4 is the
design.
Oscillatory Circuit
Desired criterior 0.2 Hz, 1 V output:
Using 12 V d.c. power supply
Choose C = 3.3 μF; R = 0.68 MΩ; R1 = R2 = 1 MΩ; R3 = 1 kΩ; R4 = 28 kΩ
5.2 Square Wave Generator
TL ¼ 0:693 R2 C ð5:2Þ
5v to15v
2
Figure 5.7 shows the full implementation of the analogue PID controller. The
settings are as follow: CDi = 0.1 μF; CIf = 0.22 μF; C4 = 10 nF
Differentiator Circuit
Gain ratio = - RC*s = -Td*s
Integrator Circuit
Gain ratio = - 1/(RC*s) = - 1/(Ti*s)
Proportional Circuit
Gain ratio = - R2/R1= - kp
fi1 ¼ 0:2 Hz; fi2 ¼ 4 Hz; fd1 ¼ 90 Hz; fd2 ¼ 800 Hz; fs ¼ 1 kHz
Proportional d.c gain is, Ki ¼ ðRIf R4Þ=ðRIi R2Þ ¼ 21:33 Suitable resistor
for differentiator corner frequencies are:
16k
4.7k
To motor plant
RKf R4 SðsÞ RIf R4 SðsÞ s CDi RDf R4 SðsÞ
GðsÞ :¼ þ þ
RKi R3 RIi ð1 þ s RIf CIf Þ R2 1 þ s CDi RDi R1
ð5:7Þ
The analogue voltage control circuit measures the differences between the desired
set voltage and the feedback voltage to operate the solenoid valve of a system. The
electronics circuit diagram is as shown in Fig. 5.9. The function of the first
amplifier in the circuit is to calibrate the errors of the transducer signal feedback.
We define this as the zeroing of the voltage feedback to a reference point. Next, we
can set the desired voltage at the terminal of the differential amplifier. The voltage
signal will be fed into the voltage comparator together with the feedback voltage.
A supply voltage of 5 V offsets the differences of the set voltage and the feedback
voltage in the next amplifier circuit. Finally, the output of the analogue control
circuit is fed forward to the solenoid valve of the rodless cylinder to initiate the
linear motion. The electronic circuit of the analogue voltage controller consists of
three types of amplifier circuits as shown above. We can ground the inverting
amplifier using a 1 kΩ, R3 resistor (Fig. 5.10).
R2
For differential amplifier; Vo ¼ ðV2V1Þ ð5:8Þ
R1
R2
For inverting amplifier; Vo ¼ V1 ð5:9Þ
R1
R3 R3
For summing amplifier; Vo ¼ V1 þ V2 ð5:10Þ
R1 R2
The analogue signal control circuit output voltages for each of the stages are
derived as follow. For simplicity, we use 1 kΩ value for all the resistors. So the
amplification is straight forward.
R3 R3
First Stage: V1 ¼ Vtrim þ Vin ð5:11Þ
R1 R2
R6
Second Stage: V2 ¼ V1 ð5:12Þ
R4
R8
Third Stage: V3 ¼ ¼ ðVsetV2Þ ð5:13Þ
R7
R11 R11
Fourth Stage: V4 ¼ Voffset þ V3 ð5:14Þ
R9 R10
R14
Final Stage: Vout ¼ V4 ð5:15Þ
R12
The voltage input to the displacement output of the rodless cylinder mechanism
system is as shown in the plot. The static sensitivity is calculated approximately as
5.625 V/m. There is an offset in the initial system as shown in the graph. That arises
the need for the 20 kΩ potentiometer. The zeroing adjustment of the transducer
potentiometer is to eliminate the error of the feedback voltage, from the displace-
ment transducer when starting. The 20 kΩ referencing potentiometer calibrates the
misalignment of the signal feedback, due to some physical, mechanical error or
degradation of the components which inherits in the system. We can adjust the
potentiometer or trimmer to counteract on the positive or negative transducer signal
feedback. The system is trimmed to 5 kΩ as shown in the circuit. The position of
the adjusted voltage of the trimmer can eliminate the error of the transducer
feedback voltage (as referenced to the static sensitivity graph). For example, when
the set and offset voltages are all set to zero, there is no distance travel or any
displacement. So the voltage from the transducer should feedback a 0 V signal. But
when referring to the static sensitivity graph, there is an offset of 1 V in the system
for zeros displacement. So we trim the voltage trimmer to a negative 1 V same
signal. It eliminates the transducer signal, so the final output of the analogue control
circuit is zero at the beginning. Therefore, there will be no displacement for the
linear system before we inject a desired set voltage (Fig. 5.11).
Also, the voltage offset is set to 5 V for the system because the rodless cylinder
mechanism is referenced and positioned to this fixed distance at the beginning.
5.4 Control of an Electro-pneumatic Mechanism 89
As shown in the graph, the distance for the 5 V offset will be approximately 89 cm
away from the starting end of the rodless linear mechanism system. Therefore, the
two potentiometers serve as a signal compensation and voltage allowance for the
mechanical system.
Chapter 6
Electrical System
PLC control systems are invested heavily in the market to perform many different
control functions. Brands like Hitachi, Omron, Allen Bradley, etcs, are popular in
their usage, serving the various sectors in the industrial. Due to ease of maintenance
and the flexibility in configuration, the PLC control system is used worldwide.
Elevator control employs PLC.
We used the Hitachi E-Series PLC for a large number of sequential control
applications. The ladder logic diagram is programmed and applied in many
applications. The operation of the elevator control for a four storey building is one
example. The elevator or lift system consists of three PLC program structures. They
are the lift up/down control structure, the lift door open/close control structure and
the lift lighting control structure. Figure 6.1 is the lift system layout for the design.
Table 6.1 shows the standard input and output lift functions for the operational
control of the lift system. There are altogether thirteen push buttons, eight limit
switches and seventeen indicating lights in the elevator system. Besides, we have
four solenoid relays to control the lift up/down and door open/close positions.
The ladder logic control design for the lift system consists of three main parts. They
are
1 2 3 4
L1 L2 L3 L4 LS1
P1 up L5 LS2
P2 down L6
P3 up L7 LS3
P4 down L8 LS7 LS8
P5 up L9 Open Close
P6 down L10 LS4
LS5
LS6
L1 – 50 P1 – 00 LS1 – 100
L2 -- 51 P2 – 01 LS2 – 101 P7 EMG. L11
STOP
L3 – 52 P3 – 02 LS3 – 102
L4 – 53 P4 – 03 LS4 – 103 P8 4 L12
L5 – 54 P5 – 04 LS5 – 104
L6 – 55 P6 – 05 LS6 – 105 P9 3 L13
L7 – 56 P7 – 06 LS7 – 106
2
L8 – 57 P8 – 07 LS8 – 107 P10 L14
L9 – 150 P9 – 10 COM
1
L10 – 151 P10 – 11 P11 L15
L11 –152 P11 – 12
L12 – 153 P12 – 13
L13 – 154 P13 – 14 P12 P13
L14 – 155 OPEN CLOSE
L15 – 156 Up – 60 Close – 62
L16 – 157 Down – 61 Open -- 63 L16 L17
L17 –160 COM COM
COM
Fig. 6.1 Lift references
without worries or concerns of undoing the whole system. The designer can then
combine the three parts as one continuous ladder control diagram for the elevator
system.
As shown in Fig. 6.2 is the ladder diagram structure for the lift indicating lights. We
installed these lights outside the lift for indication to passengers waiting outside the
lift. We connect the internal relays 50–53 of the PLC to the indicating lights outside
the elevator. The light indicators from 53 to 50 are from level 4 to level 1
respectively. LS2 activates the 4th storey limit switch, LS3 represents the 3rd storey
limit switch and so on. We used only four limit switches in the design.
Alternatively, we may want to use two limit switches to signal for the lift
indicator (Fig. 6.3). It depends on the design engineer whether to fix one or two
limit switches for activating the light indicators. Additional limit switches will
ensure a more fully proofed system at the expenses of having more maintenance
and costs. Moreover, additional hardware increases the chances of hardware failure
of the system also.
The solenoid relay 63 of Fig. 6.4 energises the lift door open motor while the coil
62 energise the lift door to close. Lamp indicators are 157 and 160. We use the on
delay timer T02, to delay the lift door closing when it is open. The delay is set to
2 s. When the elevator door is opening, pressing the close button P13 will not
activate the lift door to close. On the other hand, pressing the open button P12 will
bypass the door closing to open the lift door. The contacts 60 and 61 are from the
lift up/down motors. We install the on delay timer T04 to delay the timing for
opening the lift door when the elevator reached the level or when the up/down
motor has de-activated. The timer is set to hold for one second before the elevator
door operates to open. So the lift up/down motor will not be activated first (6 s
delay). Another scenario is to press the buttons outside the lift to be able to open the
lift door. The second rung of the ladder diagram of the buttons P1 to P6 hold the lift
door back from closing when the lift stations at the respective level.
6.3 Ladder Diagram Control Structures 95
The first line in the elevator open/close ladder diagram ensures the elevator is
stationary before it can open its door. While the lift is moving, the coil 60 or 61 will
be activated to open its contact. Hence, logic line one of the ladder diagram is open
circuit. So the lift door will not be opening. Once reached (after delay 1 s), the lift
door opens until it touches the open limit switch LS7. Conversely, the lift door will
close (if there is no interference) until it activates the close limit switch LS8, to
de-energize the close relay motor 62. Then, the program continues to the lift
up/down ladder diagram to decide about the elevator vertical movement.
The lift up and down moving control system is shown in the ladder diagram of
Fig. 6.5. Beside it are the mnemonics or logic codes for the ladder diagram pro-
gram. The up/down control of the elevator is cut off by the limit switches (from LS2
to LS5) in each of the levels when activated.
The lift control is manually input by pressing any of the six buttons outside the
lift or any of the four buttons inside the lift. Altogether, we have ten press button
input for the elevator control system. The lift up/down movement activates when
LS8 limit switch is closed. Furthermore, it depends on the location level of the
elevator to decide whether to move up or down. That depends on the activation of
the limit switches (LS2 to LS5) in each level. The indicating lights inside the lift,
from L11 to L15 (contactor output 152 to 156) only connect to light indicators. We
do not connect them to any contact point (152 to 156). Whereas, the indicating
lights outside the lift, from L5 to L10 (contactor 54 to 57 and 150 to 151), all are
connected to contactor points and relays. For instance, if we pressed button P9
(level 3) inside the lift, the button P2 or P3 will light up. Which button light up
depends on whether the lift is above or below the level 3. Let us say, the lift is in
level 2 or 1, so P3 (light L7) lights up. If the lift is at level 4, L6 will lit instead of
L7 outside the lift. If we press P2 or P3 outside the lift, the P9 button inside the lift
will light up also. Thus, passengers outside or inside the lift know the elevator will
arrive and stop at the levels where there are lighted buttons. The relays (60 and 61)
each connects to their respective motor for activating the lift up and down. The LS8
limit switch ensures the lift is closed before it can move up/down. We install on
delay timer T05 to T08 to control the elevator from overshot when the passengers
had pressed the lift from different levels. These four timers have a delay of 6 s each,
to cater time for the lift to stop at the activated level before it responses to its next
vertical (up/down) movement in the same direction. Whereas the three seconds
timer T09 and the two seconds timer T11, allow enough time to open the lift door
first before it responses to the next passenger level for the lift to move in the
opposite direction. The delay prevents the lift from responding to move in the
opposite direction when it has reached the passenger level. Timers T09 and T11 are
6.3 Ladder Diagram Control Structures 97
set differently to prevent both up/down motors of the lift from energizing simul-
taneously. Together with the ladder diagram controlling the lights and the lift door
opening and closing, the elevator functions as a complete working system.
We can add safety features to the lift control system. For example, we can put two
more limit switches to stop the lift at the highest and the lowest level. Limit switch
LS1 is the safety control to halt the elevator from rising when the LS2 limit switch
at level 4 fails. Similarly, LS6 limit switch is mounted to prevent the lift from
descending further if limit switch LS5 fails. Secondly, we implement a timer delay
or on delay timer T01 to activate the lift to rise. The purpose is to delay energizing
the upward lift motor if both the up and down motors activate at the same time
when the lift door (LS8 limit switch) is at closed position. That is cause by both the
upper and lower level passengers energizing the lift buttons when the lift is held
stationary at the middle level (between both the passengers level). So, the lift will
activate the move down motor 61 first. Furthermore, we can install the emergency
button inside the lift too. Button P7 is the emergency latch button to halt the
elevator at the standstill during the emergency. Another implementation is to move
the elevator to the level 1 or ground level when nobody is using. If any of the
6.4 Safety Control Features 99
buttons from P1 to P6 and from P8 to P11 are not press, the elevator will auto-
matically lower itself to the ground level (level 1). That is the initial stationary
position (level) of the lift to wait for passengers. Fifth, we can add on delay timer
(T03) to delay the lift from moving up once the door is closed. Lastly, we add a
timer delay, T10 to have different timing for energizing the lift down motor
(61) once the lift is closed. The on delay timer, T03 is set to two seconds while T10
is set to 1 s delay. Thus, the timer T01 can be considered redundant for the situ-
ation. These six additional features of the lift system are as shown in Fig. 6.6.
100 6 Electrical System
Table 6.2 Elevator on-delay T01 T02 T03 T04 T05 T10 T09 T11
timer settings T06
T07
T08
1s 2s 2s 1s 6s 1s 3s 2s
We can include them to replace the last eight rungs of Fig. 6.5 to have the complete
safety elevator system (Table 6.2).
The lift timing control is done by the on delay timers from T01 to T11. The
settings for the timings ensure the elevator operates without fail. It guarantees the
smooth transition of the lift to the next level and the efficiency of the lift control
system. With the presence of the timers T10 and T03 in the system design, we can
lengthen T02 to 4 s delay. The extra delay time holds the lift door longer in the
open standstill position. It caters for the concern of the elderly to enter the lift. At
the same time, we can shorten T05 to T08 to 4 s also. In reducing these timing
delays, enable the lift passenger buttons to be more active. By doing so, we
improved the efficiency and user friendliness of the elevator system.
Chapter 7
Power Flow
Numerical methods are used to solve for complex non-linear problems in power
system analysis. One of the most popular techniques is the approximation of the
non-linear algebraic equations to linearise equations. The Newton-Raphson method
is an iterative algorithm, which only makes use of the first few terms of the Taylor
series function f(x). It is used practically in load flow power network. Power
efficiency is crucial for load flow transmission and distribution. Transmission lines
circuit protections and overloads need to be calculated to monitor and control the
network system. So network design and line regulation are optimized for better
efficiency.
By the Newton-Raphson formulation, we have the first-order terms from the Taylor
series expansion shown in Eq. (7.1). Where e stands for the amount of error
computed. x0 is the initial guess for the unknown variable. We set f (x0 + e) to zero
and solve for the error in the system (see Eq. (7.2)).
xn þ 1 ¼ xn þ e n ð7:3Þ
The unknown value for the system is updated as in Eq. (7.3) until the error is zero.
--------------------------------------
Program 7.1: Newton Raphson
---------------------------------------
Program Newton_Raphson;
VAR
X1,X2,F1,F2,X11,X22,T:REAL;
J11,J22,J12,J21,IJ11,IJ22,IJ12,IJ21,DET:REAL;
COUNT:INTEGER;
BEGIN
WRITELN;
WRITELN('Newton Raphson Technique for Simultaneous Equations');
WRITELN(' 3 2 2');
WRITELN('F1= 2X1 + 3X1 X2 - X2 - 2 = 0');
WRITELN(' 2 2 2');
WRITELN('F2= X1X2 + 2X1 - 3X2 + 16 = 0');
WRITELN;
WRITELN('ENTER TWO VALUE OF APPROXIMATION');
WRITELN;
READLN(X1,X2);
WRITELN('X1 = ',X1:4:5,' X2 = ',X2:10:5);
WRITELN;
WRITELN;
WRITELN('COUNT':8,'X1':17,'X2':17);
WRITELN(COUNT:8,X1:17:5,X2:17:5);
X11:=1.0;
X22:=1.0;
7.2 Newton Raphson Formulation 103
T:=0.001;
WHILE (ABS(X11)>T) OR (ABS(X22)>T) DO
BEGIN
F1:=2*EXP(3*LN(X1))+3*SQR(X1)*X2-SQR(X2)-2;
F2:=X1*SQR(X2)+2*SQR(X1)-3*SQR(X2)+16;
J11:=6*SQR(X1)+6*X1*X2;
J12:=3*SQR(X1)-2*X2;
J21:=SQR(X2)+4*X1;
J22:=2*X2*X1-6*X2;
DET:=J11*J22-J21*J12;
IJ11:=J22/DET;
IJ12:=-J12/DET;
IJ21:=-J21/DET;
IJ22:=J11/DET;
X11:=-(IJ11*F1+IJ12*F2);
X22:=-(IJ21*F1+IJ22*F2);
X1:=X1+X11;
X2:=X2+X22;
COUNT:=COUNT+1;
WRITELN(COUNT:8,X1:17:5,X2:17:5);
END;
WRITELN;
WRITELN(' THE ANSWER AFTER ',COUNT-1,' ITERATION IS X1 = ',X1:1:5);
WRITELN(' X2 = ',X2:1:5);
104 7 Power Flow
X
n
Pi calc ¼ jVi Vk Vik j cosðUik þ dk diÞ ð7:4Þ
k¼1
X
n
Qi calc ¼ jVi Vk Vik j sinðUik þ dk diÞ ð7:5Þ
k¼1
Expression (7.4) and (7.5) shows the calculated active and reactive power at bus i.
The differences between the specifications and the calculated power in Eqs. (7.6)
and (7.7) are the changes in the active and reactive power. The Jacobian matrix of
Eq. (7.8) is the partial derivative of Pi and Qi. Equation (7.9) is the system equation.
By substituting the Jacobian matrix into the system, we derive Eq. (7.9).
7.3 Load Flow Analysis Using Newton Raphson 105
Y/2 ¼ j0:1
ð7:16Þ
¼ 0:1 x 90
Y11 ¼ Yt ð7:17Þ
Yt ¼ Y/2 þ Y12
¼ j0:1 þ 21:8 j22:8
ð7:18Þ
¼ 21:8 j22:7
¼ 31:47 x 46:15
(Fig. 7.3).
106 7 Power Flow
Fig. 7.7 a Case 2 output, b case 2 output, c case 2 output, d case 2 output
For case 2, we need to derive the subject of interest which is the ΔQ and Δd. The
below equations’ formulations result in the matrix equation of interest (Eq. 7.26)
required for the computation. The first result is as shown in Fig. 7.6 when the
inductor is not present to ensure we do not exceed the generator (Qg) limitation
requirements.
DP J11 J12 Dd
¼ ð7:19Þ
DQ J21 J22 DV
1 J12
Dd ¼ DP DV ð7:23Þ
J11 J11
DP J12DV
DQ ¼ J21 þ J22DV ð7:24Þ
J11 J11
J21 J21J12
DQ ¼ DP þ J22 DV ð7:25Þ
J11 J11
110 7 Power Flow
" 1 J12
#
Dd DP
¼ J11 J11 ð7:26Þ
DQ J21 J22 J21J12 DV
J11 J11
We insert an inductor (QL) at bus 1 because from Fig. 7.6 we had exceeded the
limitations for the QG(PU) value. Figure 7.7 shows the result is within the limits
after the insertion of the inductor at bus 1. When using the generator limits Qg as the
conversion requirement, the active power at bus 2 is out of the range (see Fig. 7.7a).
When using termination tolerances of ΔV22 and ΔX22, the convergence is slightly
out of the range for load active power load (P2D) at bus bar 2 (see Fig. 7.7b). From
the findings, the convergence requirement is the best when using changes in Pi and
Qi as the terminating tolerances. (The active power load on bus 2 is exactly the same
given value when the iteration stops.) (see Fig. 7.7c, d) Figure 7.8 shows the result of
the voltage at bus 2 when the load is suddenly switched off with the capacitor at bus 2
and the inductor at bus 1, remain connected.
7.3 Load Flow Analysis Using Newton Raphson 111
----------------------------------------------------
Program 7.2:Newton Raphson Load Flow
----------------------------------------------------
Program Newton_Raphson_Load_Flow;
VAR
Y,PHI:ARRAY[1..2,1..2] OF REAL;
READFILE : TEXT;
I,K,COUNT,NUMBER :INTEGER; STRIN:STRING;
CP2,CQ2,P2DC,Q2DC,PL,QL,X22,V22,a,b,c:REAL;
PF,CP1,CQ1,P1DC,Q1DC,P2G,Q2G,PGS,QGS:REAL;
P1DS,Q1DS,P2DS,Q2DS,PGC,QGC,AG,Q2C,Q1I,QGT:REAL;
J11,J22,J12,J21,IJ11,IJ22,IJ12,IJ21:REAL;
J1,J2,J3,J4,T,DET,V1,X1,V2,X2,V2C:REAL;
BEGIN
WRITELN('Newton Raphson Technique for Load Flow');
WRITELN(' 2');
WRITELN('P2DC=31.55*V2*COS(133.72-X2) + 21.8V2 ');
WRITELN(' 2');
WRITELN('Q2DC=-31.55*V2*SIN(133.72-X2) + 22.695V2 ');
ASSIGN(READFILE,'C:DATA1.TXT');
RESET(READFILE);
FOR I:=1 TO 2 DO
FOR K:=1 TO 2 DO
READLN(READFILE,Y[I][K],PHI[I][K]);
CLOSE(READFILE);
FOR I:=1 TO 2 DO
FOR K:=1 TO 2 DO
BEGIN
WRITELN('Y',I,K,' =',Y[I,K]:4:2,' PHASE ANGLE ',I,K,' =',PHI[I,K]:5:2);
PHI[I,K]:=PHI[I,K]*PI/180;
END;
NUMBER:=0;
WHILE NUMBER<3 DO
BEGIN
CP2:=1.0;
CQ2:=1.0;
T:=0.0001;
COUNT:=0;
CP1:=0;
CQ1:=0;P1DS:=0;Q1DS:=0;
PGS:=0;P2G:=0;P2DS:=2.4;P1DC:=0;
QGS:=0;Q2G:=0;Q2DS:=1.8;Q1DC:=0;
V1:=1; X1:=0;
IF NUMBER=2 THEN
BEGIN
112 7 Power Flow
Q1DS:=Q1I;
P2DS:=P2DS-P2DS;
Q2DS:=Q2DS-Q2DS+Q2C;
WRITELN('Load Swtched off with Capacitor(bus 2) and Inductor(bus 1) Connected.');
WRITELN;
END;
WRITELN('Please ENTER V2(more than 1) then angle X2(RAD) for approximation');
WRITELN('Please ENTER X2(RAD) not exceeding 0.707 for convergence (best 0)');
READLN(V2,X2); {*not >0.81 for question 1*}
WRITELN(' V2 = ',V2:4:5,' X2(RAD) = ',X2:4:5);
WRITELN; {*not >0.74 for question 3*}
WRITELN('COUNT':12,'V2':10,'X2(RAD)':20);
WHILE (ABS(CP2)>T) OR (ABS(CQ2)>T) DO
BEGIN
P2DC:=Y[2,2]*SQR(V2)*COS(PHI[2,2])+(Y[2,1]*COS(PHI[2,1]+X1-X2)*V2*V1);
Q2DC:=-Y[2,2]*SQR(V2)*SIN(PHI[2,2])-(Y[2,1]*SIN(PHI[2,1]+X1-X2)*V2*V1);
CP2:=-P2DS-P2DC;
CQ2:=-Q2DS-Q2DC;
J11:=Y[2,1]*V1*V2*SIN(PHI[2,1]+X1-X2);
J12:=Y[2,1]*COS(PHI[2,1]+X1-X2)*V1+Y[2,2]*2*V2*COS(PHI[2,2]);
J21:=Y[2,1]*V1*V2*COS(PHI[2,1]+X1-X2);
J22:=-Y[2,1]*V1*SIN(PHI[2,1]+X1-X2)-Y[2,2]*2*V2*SIN(PHI[2,2]);
DET:=J11*J22-J21*J12;
IJ11:=J22/DET;
IJ12:=-J12/DET;
IJ21:=-J21/DET;
IJ22:=J11/DET;
X22:=(IJ11*CP2+IJ12*CQ2);
V22:=(IJ21*CP2+IJ22*CQ2);
X2:=X2+X22;
V2:=V2+V22;
COUNT:=COUNT+1;
WRITELN(COUNT:8,V2:17:5,X2:17:5);
END;
PGC:=SQR(V1)*Y[1,1]*COS(PHI[1,1])+V1*V2*Y[1,2]*COS(PHI[1,2]+X2-X1);
QGC:=-SQR(V1)*Y[1,1]*SIN(PHI[1,1])-V1*V2*Y[1,2]*SIN(PHI[1,2]+X2-X1);
IF NUMBER=2 THEN
QGC:=QGC-(-Q1I); {Pt=Pg-Pload}
PGS:=PGC+CP1;
QGS:=QGC+CQ1;
X2:=X2*180/PI;
PL:=PGC-P2DS-P1DS;
QL:=QGC-Q2DS-Q1DS;
PF:=PGC/SQRT(SQR(PGC)+SQR(QGC));
AG:=arctan(QGC/PGC)*180/PI;
7.3 Load Flow Analysis Using Newton Raphson 113
WRITELN('AG= ',AG:2:4);
IF AG>0.00 THEN
STRIN:='LAG'
ELSE
STRIN:='LEAD';
WRITELN(' THE ANSWER AFTER ',COUNT,' ITERATION IS : ');
WRITELN('BUS NO VOLT(PU) ANGLE(DEG) PD(PU) QD(PU)
PG(PU) QG(PU)');
WRITELN('------ ------- ---------- ------ ------ ------ ------');
WRITELN('1',V1:13:4,X1:12:4,P1DS:10:4,Q1DS:9:4,PGC:9:4,QGC:9:4);
WRITELN('2',V2:13:4,X2:12:4,-P2DC:10:4,-Q2DC:9:4,'0.0000':9,'0.0000':9);
WRITELN('PLOSSES=',PL:2:4,' PU, ','QLOSSES=',QL:4:4,'
PU,','P.F=',PF:2:4,' ',STRIN:4);
WRITELN('---------------------------------------------------------------------');
NUMBER:=NUMBER+1;
IF NUMBER=1 THEN
BEGIN
WRITELN;
WRITELN('Find Capacitor(bus 2) with V1=V2.');
WRITELN;
WRITELN('Please enter Q2DC then angle X2(RAD) for approximation');
WRITELN('Enter Q2DC value of between 14.33 to -5.7 for convergence');
READLN(Q2DC,X2);
WRITELN(' Q2DC = ',Q2DC:4:5,' X2(RAD) = ',X2:4:5);
WRITELN('COUNT':10,'Q2DC':8,'X2(RAD)':17,'V2C':14,'Pg':14);
CP2:=1.0; Q1I:=1; Q1DS:=Q1I; V22:=1;X22:=1;
CQ2:=1.0;COUNT:=0; QGC:=5.0;PGC:=5.0;V2:=1;
WHILE (ABS(CP2)>T) OR (ABS(CQ2)>T) DO
BEGIN
{*Q2DC:=-Y[2,2]*SQR(V2C)*SIN(PHI[2,2])-(Y[2,1]*SIN(PHI[2,1]+X1-
X2)*V2C*V1)*}
a:=-Y[2,2]*SIN(PHI[2,2]);
b:=-Y[2,1]*SIN(PHI[2,1]+X1-X2)*V1;
c:=-Q2DC;
V2C:=(-b+sqrt(sqr(b)-(4*a*c)))/(2*a);
{ IF V2C>0 THEN
V2C:=V2C
ELSE
V2C:=(-b-sqrt(sqr(b)-(4*a*c)))/(2*a);}
{IF V2C1}
P2DC:=Y[2,2]*SQR(V2C)*COS(PHI[2,2])+(Y[2,1]*COS(PHI[2,1]+X1-
X2)*V2C*V1);
CP2:=-P2DS-P2DC;
{CQ2:=-Q2DS-Q2DC;}
V22:=V2-V2C;
114 7 Power Flow
J11:=Y[2,1]*V1*V2C*SIN(PHI[2,1]+X1-X2);
J12:=Y[2,1]*COS(PHI[2,1]+X1-X2)*V1+Y[2,2]*2*V2C*COS(PHI[2,2]);
J21:=Y[2,1]*V1*V2C*COS(PHI[2,1]+X1-X2);
J22:=-Y[2,1]*V1*SIN(PHI[2,1]+X1-X2)-Y[2,2]*2*V2C*SIN(PHI[2,2]);
J1:=1/J11;
J2:=-J12/J11;
J3:=J21/J11;
J4:=J22-((J21*J12)/J11);
X22:=(J1*CP2+J2*V22);
CQ2:=(J3*CP2+J4*V22);
X2:=X2+X22;
Q2DC:=Q2DC+CQ2; {Q2DC:=-Q2DS-CQ2;}
PGC:=SQR(V1)*Y[1,1]*COS(PHI[1,1])+V1*V2C*Y[1,2]*COS(PHI[1,2]+X2-X1);
QGT:=-SQR(V1)*Y[1,1]*SIN(PHI[1,1])-V1*V2C*Y[1,2]*SIN(PHI[1,2]+X2-X1);
QGC:=QGT-(-Q1DS); {Pt=Pg-Pload)}
COUNT:=COUNT+1;
WRITELN(COUNT:6,Q2DC:15:5,X2:14:5,V2C:14:5,PGC:14:5);
END;
X2:=X2*180/PI;
PL:=PGC-(-P2DC)-P1DS;
QL:=QGC-(-Q2DC)-Q1DS;
PF:=PGC/SQRT(SQR(PGC)+SQR(QGC));
AG:=arctan(QGC/PGC)*180/PI;
WRITELN('AG= ',AG:2:4);
IF AG>0.00 THEN
STRIN:='LAG'
ELSE
STRIN:='LEAD';
Q2C:=-Q2DC-Q2DS;
WRITELN(' THE ANSWER AFTER ',COUNT,' ITERATION IS : ');
WRITELN('BUS NO VOLT(PU) ANGLE(DEG) PD(PU) QD(PU) PG(PU)
QG(PU)');
WRITELN('------ ------- ---------- ------ ------ ------ ------');
WRITELN('1',V1:13:4,X1:12:4,P1DS:10:4,Q1DS:9:4,PGC:9:4,QGC:9:4);
WRITELN('2',V2:13:4,X2:12:4,-P2DC:10:4,-Q2DC:9:4,'0.0000':9,'0.0000':9);
WRITELN('PLOSSES=',PL:2:4,' PU, ','QLOSSES=',QL:4:4,'
PU,','P.F=',PF:2:4,' ',STRIN:4);
WRITELN('---------------------------------------------------------------------');
WRITELN('THE RATING OF THE CAPACITOR IS -Q2DC-Q2DS = ',Q2C:4:4);
WRITELN;
END;
NUMBER:=NUMBER+1;
END;
END.
Chapter 8
Process Control
The experiment we conduct studies the control response of the water level control
process in the system. We control the water level in the tank for the process control
system. Conventional PID control characteristics demonstrate the dynamics of the
system process. In most parts of the experiment, we only make use of one tank. So
we derived a first order equation G(s) for the main process. The apparatus as shown
in the diagram consists of the double tank system. A separation valve (A) locates
between the tanks. We fix the level and flow sensors on each of the tanks. We
supply a voltage input from zero to 10 V to each different tank. The supply voltage
is proportional to the water level and flow rate of each different tank. A plotter
connects to plot the control characteristics of the system (Figs. 8.1, 8.2, 8.3).
The error signal shows the differences between the set-point and the output. We
first study the proportional control system. By adding a PI controller into the
closed-loop system, we can derive the steady-state level output from the block
diagram with a step input.
Q0 ¼ H=R ð8:1Þ
dh
C ¼ Qi Q0 ð8:2Þ
dt
By substitution:
dh H
Qi ¼ C þ ð8:3Þ
dt R
Therefore:
H dh H
Q0 =Qi ¼ = C þ ¼ 1=ðTs þ 1Þ ð8:4Þ
R dt R
The steady-state output level due to a unit step input is (Fig. 8.5):
9
When Kp ¼ 3 : 3=ðTs þ 4Þ ¼ 0:75 Vðplot showing 0:85 V) =
When Kp ¼ 6 : 6=ðTs þ 7Þ ¼ 0:85 V(plot showing 1 V)
;
When Kp ¼ 9 : 9=ðTs þ 10Þ ¼ 0:9 Vðplot showing 1 VÞ
By using PI controller:
TANK A TANK B
Water Level
Calibration Output Level
Output Level
Scales Sensor
Sensor
Output Flow
Output Flow Sensor
Sensor
Valve A
Variable DC
Variable DC
0 to +10v
0 to +10v
control
control
voltage
voltage
The actual response due to a step input is as shown in the plots. The time constant
we plotted in Fig. 8.4 shows 1.75 min (105 s). For the proportional controller
alone, the steady-state error reduces as Kp increases. We manually offset the input,
to have a clear readout for the differences in the steady-state output plotted. The
actual plot might have slight variation from the derivations for the output level. It is
partly due to the pump’s overhead loss or the plotter pen mechanism loose.
Furthermore, small particles present in the liquid might block the pump suction
head. For a small unit input of 1 V, all these might be significant to cause the output
deviation. The disadvantage of using the proportional Kp term alone is that it
introduces an offset in the final value as shown in the Fig. 8.5. So we introduce the
proportional-integral PI term. It is clearly seen by derivation and from the experi-
ment plot also, that the steady-state error is being reduced to zero. The PI controller
is properly selected depending on the required response by choosing the Kp term
first then the Ki term. As shown in the graphs plotted, we found that the system
exhibits second-order characteristics from the PI controller. With a fixed Kp of 5,
the overshoot gets larger as Ki increases. We are unable to fix the Ki first then
adjust the Kp term. Figure 8.7 depicts the reasons behind. Ringing oscillations are
introduced into the system when Kp is small. Moreover, there is always an
overshoot present in the system, which we are unable to eliminate. Thus, Fig. 8.6
shows the correct tuning method to adjust the steady-state final output level without
exhibiting any overshoot. From the PI controller, we can add on an additional
derivative term into the system. The PID controller can be introduced to improve
the system characteristics further. By adding the derivative term, it increases the
overshoot, at the same time reduces oscillations and ringings. Moreover, it also
reduces the time constant at the transient stage. Therefore, it improves the speed of
responses to reach steady-state. So, we learned that the derivative term is used to
compromise the integral term in the PID controller. It enables three selectable
tunings in the PID controller, for a more precise control of the system.
Chapter 9
Machine Learning
A neural network learns your process by observation and adapts its strategy for a
more precise control. Neural networks are self-tuning systems that automatically
take advantages of process upgrades and compensate for system degradation.
Neurocontrol comes into existence to the problem solving of tuning a noisy,
non-linear and complex system. Also, it can reduce the cost of implementing
solutions for the problem. The nonlinear and multivariable capabilities of neural
networks make the technology ideal for direct process control [24] (Fig. 9.1).
The artificial neural network has successfully used in many process control
applications. It allows complexity control and critical monitoring of the process
plant and sensors. In many systems, performance degrades over time due to dete-
rioration of the system components. For compensation, operational parameters are
dynamically tuned to optimize system performance. An ANN can be used to make
decisions about the system operation and adjust the appropriate control to keep the
process operates with optimal efficiency. An advantage of ANN over the traditional
adaptive controllers is that we can continuously update the ANN with new
The neural network comprises of artificial neurons which are group into three main
layers: input, output and hidden layers. Its function is by the rules of mathematical
equations built into a semantic rule-based implementing as a controller to navigate
the system and monitor its progress through its self-iterative learning process.
The information processing performed may be taken as the signals appearing at
the unit’s input. Or the action potentials to the synapses. The effect (PSP) of each
signal can be approximated by multiplying the signal with some number or weight
to indicate the strength of the synapse. The weighted signals are now summed to
produce an overall unit activation. The unit will produce an output response when
the activation exceeds a certain threshold. This functionality captured in the arti-
ficial neuron the Threshold Logic Unit (TLU) (Fig. 9.2).
We suppose there are n inputs with signals X1, X2, etc. The signals have a
boolean output that is ‘0’ or ‘1’. The threshold value is assumed zero. We illustrate
the g value in Fig. 9.3.
9.2 The Artificial Neurons 123
The graph shows the difference between the two g values. The g value is higher
when the slope is steeper. For calculation, the g value is always put to one. The A
value is always negative.
Thus the equation:
1
fðxÞ ¼ ^ ðgðAhÞÞ
1þe
ð9:3Þ
1
¼ ðWhere h ¼ 0 and g ¼ 1Þ
1 þ e^ A
Generally, there are five basic approaches in neuro-control techniques. They are:
(1) Supervised control
(2) Direct inverse control
(3) Neural MRAC-type adaptive control
(4) Reinforcement learning
(5) Unsupervised control.
124 9 Machine Learning
(1) Supervised control: We make use of a training set consisting of X(t), and u*(t)
where u* is the target action vectors. The system records the actions as well as
the sensor inputs so that, we can track the responses. We need to calculate the
deviation error for the weight adaptation.
(2) Direct inverse control: It is according to supervised learning. The states of the
system make up the input of the plant, and the targets are the actuating signals.
It is suitable for robot control.
(4) Reinforcement learning: The output feedback of the plant either aids or
negates the control states depending on the environment reaction. The aiding
signal reinforces those states that contribute to improvement, while the
deducting signal, reduces the states that produce the improper behaviour. It
uses a ‘fuzzy’ approach to the calculated output. The weight changing stops
when the output stabilises in the range of the ‘fuzzy’ categorized output.
(5) Unsupervised control: The output of the subsets are put together at random or
unsupervised, but the members of the same subset are one of its kinds. Thus, it
is suitable for feature mappings based on the similarity of the input patterns.
From all of the above techniques, supervised control is used for neural network
process control system as it enables on-line tuning, changing and process opti-
mization in the system.
(1) Hebb learning: If the two neurons take the same state at the same time (both
inactive or both active), the output of the weight connection between them
increases (Fig. 9.4).
(2) The perceptron learning rule: We calculate the output error from the deviation
between the desired and actual output. Then, it is used to calculate the changes
in weight in the connectism neurons (Fig. 9.5).
9.4 NN Learning Rules 125
decrease
(3) The delta learning rule: It makes use of the same concept as the perceptron
learning, except we divide the deviation errors by the number of the prepro-
cess neurons (Fig. 9.6).
(4) Backpropagation learning rule: It uses the same tactic as the delta learning
rule, but it allows the changing of weights in the additional hidden layers
introduced. The derivative of the activation function is the sensitivity of the
For all the above learning rules, backpropagation is most popular for process
control as it enables a more precise manipulation such that we can change the
weights in the hidden neurons.
hidden layers
h i j
The hidden layer in the system lies between the input and output layer by the
interconnected neurons. There is a direction for the computation of infor-
mation. The number of hidden neurons may be 50 % of the number of input
neurons. It is not always the case to have the same number of input neurons
as the output neurons in the last layer.
(1b) Backpropagation (feedforward net): It allows weights into and output of the
hidden neurons to change during learning. There are sensings of activation
neurons due to weight changes. There are two calculations involved. First, is
to calculate the net output and the error in each neuron in the forward
direction and secondly, to backpropagate the net errors to the preceding
neurons. Besides, backpropagated errors to neurons in predecessor layer are
held at the same time. Thus, the calculated net output formed is slow.
Assuming, neuron i is the preceding of neuron j (Fig. 9.8).
Every unit of the neuron inherits with a non-linear function called the activation
function or the standard sigmoidal function.
1
Equation: fðnetÞ ¼ ^ net
X 1 þ e
where: netj ¼ wij oi ð9:10Þ
i
& fi0 ðnetÞ ¼ oi ð1 oi Þ
We use the data training set to train the system for error reduction. At the same
time, we use the validation set to validate the data. The optimal point, where the
intersection occurs between the validation and training errors, is the point to stop
training. This is the best generalization before the validation error starts to increase
(Fig. 9.9).
128 9 Machine Learning
We calculate the error function by the sum of squared error differences between
the actual and targeted output value.
X
N
E ¼ 0:5 ðt j y j Þ2 ð9:11Þ
j¼1
where / represents the multiplier factor, r is the learning rate, f(net) the activation
function, x defines the input to the neuron. T is the target output and y is the actual
output. We can assume the factor / to be 1.
Dwij ¼ / d j xi ð9:14Þ
Dwih ¼ / di xh ð9:15Þ
X
di ¼ ri fi0 ðnetÞ d j wij ð9:16Þ
j2Ii
where Ii is the set of nodes after the hidden node i. It is known as the fan-out of i.
(1c) Radial Basis Function (feedforward net): The RBF have unique identity such
that they have only one hidden layer with radial basis functions Ψ(x) and
9.5 Selection of the Learning Algorithms 129
produces only linear output. As such, training of the net consists of the
unsupervised part to define the center of the radial basis function and
supervised part to learn the weight. A disadvantage is that we often used it
for the small number of inputs. However, for a large input multi-layer per-
ceptron network, gives a better generalisation.
(2a) Hopfield Net (feedback net): The difference is that weight calculation leads
to only the change of neuron states (pattern learning). The minimal problem
should be modelled so optimizing the objective function minimised the
energy function and that non-fulfillment of a constraint, leads to an energy
increase. Its function is more suitable for pattern recognition. The equation
shows the error function. Where Qi is the neuron input.
X X
Equation: 0:5 þ active neurons þ Qi ð9:17Þ
(2b) Simulated Annealing (feedback net): Another name for it is the Boltzmann
machine. It uses the same principal as Hopfield Net and is a further
enhancement of it to counteract the disadvantages of this system. That is, it
allows the neurons to change state to avoid local minimal of the system. It
consists of visible and hidden neurons interconnected. This system stops at
global minimum. However, the main drawback of the system is that it is slow
and is used for travelling salesman problem.
The neural network data processor consists of the input, hidden and output layers.
The decision for the numbers of input neurons and the layers of the hidden neurons
involved depends on the complexity of the system process. The data training set for
the input neurons rely on how we control the system and the input sensors involved.
The neuron numbers in the hidden layers and the number of hidden layers in the
system plant will affect the system monitoring and accuracy predetermined from the
neural processor. Thus, a careful determination of the number of neurons in the
hidden layers are often chosen. The final part is the target monitoring of the plant. It
consists of the last layer of the output neurons. The numbers of output neurons
depend on how many and what kind of action output we are controlling. It is in term
compared with the desired target value, and the deviation is feedback to the pre-
decessor to re-calculate the output to be maintained at the target requirements.
Therefore, a network topology is derived from a given system to be controlled.
130 9 Machine Learning
The neural network based controller and predictor are computerised systems, which
perform optimization in the continuous chemical processes. It monitors the
chemical products and adjusts the effect to produce the desired chemical reactions
and properties in a plant. Most of the existing chemical plant do not have chemical
sensors that can measure its properties. Human interventions are needed to examine
the samples off-line and consistently adjust the plant operating parameters to suit
the target. The neural based system can replace the human intervention to estimate
the chemical properties of the final product on-line automatically. The SCADA
system connected allows the display of the plant information. Human operators can
then make decisions to take further action to counteract conditions such as
degradation of the hardware sensors and tunings of plant parameters to maintain the
desired target performance. An example is a chemical process in a mixer plant. We
can use the system for forecasting as the output produced is the future value of the
input signal (Figs. 9.10, 9.11, 9.12).
Based on backpropagation calculations the following data set were being tab-
ulated for round one of the backpropagation learning:
out4 = 1 out5 = 1
D5 = [0.525*(1 – 0.525)]*(1 – 1) = 0
D6 = [0.73*(1 – 0.73)]*(0 – 1) = – 0.197
D7 = [0.5*(1 – 0.5)]*(1 – 1) = 0
D4 = 0.639*(1 – 0.639)*[0.1*0 + 1*( – 0.197) + (0*0) = – 0.045
The Table 9.1 weights tabulation is in accordance to Fig. 9.11. That is, it
depends only on one hidden neural processor. Computation begins until stabilisa-
tion once the three adjustable parameters for the three valve sensors are feedback
into the neural network input. The neural network shows the final values during
stabilization at the seventh round (1 epoch meaning the NN completes 1 cycle for
the total nos. of training examples). So the desired output is also achieved. We
monitor the progress and outcome at the control station. The system shows the
on-line tuning using backpropagation technique to match the desired output of the
plant.
9.8 Chemical Plant NN Feedback Control System 133
The reaction states of the catalyst and the reactance were difficult to analyse.
Instead, their properties and characteristics were collected from laboratory data
analyst. Temperature input is sensed using the temperature sensor. Besides setting
the chemical target quality, the catalyst output density and the reactance quantity
are also set according to the control temperature. However, there arise the difficulty
in determining the parameters of the non-linear system. So we employ the neural
network system to control the variables for the catalyst, reactance and the tem-
perature, to reach its desired states. The neural network can counteract the system
error due to the hardware problem of the mechanical valves or sensors. The weights
134 9 Machine Learning
adapt automatically to the targeted set-point even if the input jams at a position due
to failure. The signal from the neural network feeds into the SCADA (Supervisory
Control And Data Acquisition) system and monitor accurately. The neural network
can also control their output to their final states by using PID controller to adjust the
final control element for the catalyst and reactance. We can include the network
advisor to create alarm and leads to human intervention when the controlled outputs
were absurd. The system thus acts as a safeguard to monitor the on-line process and
estimates the final product with references to the desired requirements. It serves as a
simulation tool also, to test different operating process conditions. It is particularly
advantages when justifying process enhancements and modifications. The final
result will be the product with the desired chemical properties. However, the speed,
number of iterations, accuracy and convergence for the neural network depend on
the careful design of the neurons used. The output of the desired state can also be in
real neurons to control their exact value instead of binary neurons to control a
certain range. System lag time contributes slightly to the drawback of the system.
The delay time to activate the final control element from the neural network or vice
versa when sensing creates an interval to real time reaction. However, in water
process control, system lag time is not critical as we do not expect a fast response
from liquid flow/level turbulence and stabilization.
From the case above, we can design a feedback with a sampling period, for
example, one sample per 20 s, to input the detected parameter values into the neural
network system. At the same time, we can also set an integrated delay of 10 s to
output from the NN controller to the plant. The delay allows for the training and
adaptation of the neural network computation. The neural network only activates
once it detects the set of input values. It then goes through the neural network layers
to train for the desired output. We initialize the weights to random values, and
neglect the thresholds in the NN system. Then we perform an off-line simulation to
compute the desired preset NN values for the on-line system. That will reduce the
online adaptation training time of the neural network system. The output of the
neural network is sent to control the valves, after going through the delay. The
system forms a closed loop control for each sampling cycle of the NN control
system.
The Rosemount wireless flow, level and temperature transmitters [28] are
deployed at the field site to do the job. The control station will receive the wireless
transmission signals for the three parameters feedbacked. The closed loop system
performs sampling at 0.05 Hz for the neural network computation. After going
through a delay sampler, the three output valve parameters are feedback instantly
into the field controller through wireless transmission detector. Each of the detected
signals goes through a signal conditioner circuit to scale the signal suitable for the
actuating element. We can also place the signal converter at the NN station before
9.8 Chemical Plant NN Feedback Control System 135
transmission. The output of the scaled signal is fed into the PID controller to adjust
the control valve in real time. After twenty seconds, the flow/level/heat of the
reactance and catalyst will be feedbacked into the neural system wirelessly. Before
that, we can calibrate each of the flow/level/temperature transmitters with their
valves’ positionings. Once calibrated, every valves’ positions will correspond to
their respected variables’ values. The NN system compares these quantities with the
desired amount. The valves’ control system and the neural network controller can
say to operate simultaneously (depending on the selection of the system sampling
frequency) during the continuous closed loop cycles. The speed of the feedback
control system is set faster by the sampling period of the system. In doing so, we
also had to reduce the delay feedback output of the NN.
We collected eight input/output sets of random samples for the 3-1-3 neural net-
work configuration. These samples were collected randomly from the different
values to the input neurons’ layer [1 0.5 0.2;0.5 0.5 0.5;0.5 0.5 0.2;0.5 0.5 1;0.5
0.37 0.5;0.5 0.59 0.5;0.33 0.5 0.5;1 0.5 0.5] for matching to the same desired output
[1 0 1]. With the desired output fixed, the neural network backpropagated itself.
Each set of its output parameters stabilized itself automatically after adaptation. We
record the weights for each different sets of the input/output. The output neuron
parameters were plotted in the graph, through the formula as follow:
!
X
3
Catalyst ¼ W54 fW4i Xig ð9:18Þ
i¼1
!
X
3
Temperature ¼ W64 fW4i Xig ð9:19Þ
i¼1
!
X
3
Reactance ¼ W74 fW4i Xig ð9:20Þ
i¼1
Note: W4i refers to the neurons’ connected weighing values between the input
layer and hidden layer; X1 is the catalyst input; X2 the reactance input; X3 defines
to the temperature input signal (where Xi references to each of its valve’s variable).
The catalyst output value may vary during tuning, to match the desired reference
output of the neural network. That goes along with the auto adjustment of the
temperature for the reaction. As can be seen in Fig. 9.13 from sample 7 to 8, the
temperature automatically reduces as we increase the catalyst input. That is auto
tuning of the system to maintain the chemical reaction of the mixture we set. The
two parameters go according to a scaling rather than its unit. As we know, the
136 9 Machine Learning
Temperature
Catalyst
0.03 -0.06
-0.08
0.02 -0.1
-0.12
0.01
-0.14
0 -0.16
1 2 3 4 5 6 7 8
Random Samples
Catalyst Temperature
function of the catalyst is to accelerate the reaction of the chemical mixture. So,
more catalyst will lower the activation energy require for more chemical reaction to
occur. Less catalyst makes the reaction slower. Thus, we increase the temperature
of the reaction or mixture to boost back the chemical reaction in the plant, to
produce the desired chemical mixture. The amount of heat boosted is equivalent to
the catalyst reduction during valves’ auto tunings. With a static valve positioning
for the reactance, the catalyst valve and the coolant valve auto adjusts themselves to
balance the mixture reaction required in the plant. The valves’ adjustment affects
the rate of the reaction and the quality of the mixtures, within the safe range of the
chemical production. Our aims are to meet these two requirements in the system.
Alternatively, our reference output for the neural network is provided to match
these two criterions. An advantage of the neural network control system is that we
do not need to calculate the error relationship between the valves’ settings and their
corresponded quantities of its product parameters. The continuous auto tunings of
the NN and the valves will reduce and eliminate the error deviation of the plant
parameters. Moreover, the control station will calculate the matching between the
actual plant and the desired chemical to correct the target signals. Figure 9.14
shows both the catalyst (top) and the temperature (below) for a set of the target.
The NN output neurons are calculated using Eqs. (9.18)–(9.20), from the eight
different input samples, to produce the same output target. The centerline shows the
calculated average of the two parameters. We estimate the three curves by poly-
nomial equations. With the given average and any of the parameter in any timeline,
we can calculate the other parameters. The parameter found will lie along the
polynomial of the parameter itself. In this case, we can calculate either of the
parameters offline, to set the predictor limit for the parameters. Thus, we can predict
the parameters’ timelines also.
So far, we have used the binary neurons for the NN system. Each neuron’s output
value is adjusted away from its real value during computations, for the neurons’
output function. Hence, the system accuracy is affected. Previously, we have set the
output layer neurons to its binary estimation. We lost the precision of the target
setting also, due to the estimation to the target binary. We want to improve the
system precision and accuracy. So we will now set the target output to their exact
real values, with a precision of two decimal points. For each neuron, we will use
their activation (sigmoid) function values as its output. Besides, we also update the
threshold values using the update formula as shown.
h j ðt þ 1Þ ¼ h j ðtÞ þ Dh ð9:21Þ
where g is the gain term; α is the momentum term; θ is the thresholds term of each
node.
[Recall: Eq. (9.13) where fj ðnetÞ ¼ 1 þ exp 1netj þ h j ]
ð ð ÞÞ
For example, we set our desired target quality as [0.93 0.35 0.71]. Upon ini-
tialization, the starting weights are similar to Table 9.1. The initial threshold values
biased at 0. We simulate for the first eight sampling inputs as in the program 9.1.
We train the system and record their weights and biased values, after meeting its
performance goal. Our mean square error set at exponential −24. According to the
Eqs. (9.18)–(9.20), we trace the parameters’ updated trends according to each of its
input samples. We verify the first three input sampling sets [0.15 0.47 0.17],
[0.42 0.23 0.74], [0.41 0.58 0.2] for the trend. For the first to the second input
sample, we can see the rise in the catalyst but fall in the reactance. Besides, the
temperature rises for the input samples. As the transitions for the input samples are
the valves’ parameters which take place at the site, it enables more of the chemical
reaction to occur at the site. The neural network system automatic adjust itself to
control the mixture to meet the target quality set. Thereby, causing the catalyst and
the reactance mixture to reduce together with the targeted temperature. As we can
see in Fig. 9.15, the catalyst drops in accordance to the reactance. So the mixture
desired outcome is maintained. The target temperature for the mixture also
138 9 Machine Learning
Fig. 9.15 Auto adjustment NN Layer Output For Real Neurons Target
trends of the NN system
Scaled by E-11
Catalyst
Temperature
Reactance
Samples
maintains throughout the mixing. For the 2nd to 3rd sample input, the reactance
increases and the temperature dropped. It results in the slowing down of the
chemical mixture. The resultant NN control reacts to boost back the chemical
reaction to match the targeted parameters and chemical quality. We can clearly
observe the rise in the parameters as in the figure.
The valve sensor can also provide valve on/off control for overflow prevention in
the plant system. Moreover, it can be used to open/close the coolant valve for the
heat exchanger when the temperature reaches the target limit. The Westlock valve
ranges a distance of 110° positioning turns during on/off. The linear or rotary valve
reports every 1.5° turns. However, the transmission range is limited to only 100 m
with a router.
The scaled value Eq. (9.23) from the valve will go through a converter unit to
allocate the range into suitable values for the input neurons. Before that, the scaled
value had to be in units of angular degrees. The scaled value is equivalent to the
valve scaled position. The neuron range of 0–0.73 derives from the valve operating
range of 0–110° turns. The converted value lies within the range of 0–1 for the
neuron inputs.
So the valve sensors’ signals go through a conversion for matching the NN input
range. For the output layer neurons’ signals, we had to convert back the values to
the scaled values using Eq. (9.24), if the valves do not read the actual neurons’
values. We can refine the system to produce a more sensitive output. To do that, we
just change the output functions of the neurons to real values instead of binary
140 9 Machine Learning
values. We can use the ‘logsig’ logarithm sigmoid function so that the output range
stays between ‘0’ and ‘1’. All these can be done at the control station for the input
and output of the neural network system before transmissions.
The field electronic valve automation may consist of a single valve automation unit
or with another valve adapter for transmitting readings back to the control station.
A controller situates inside the electronic valve (see Fig. 9.18). It activates the PID
input, which receives the signal through an antenna. The actuators then manipulate
the valves from the PID signals. Altogether, at least, two throttle valve automation
sets are required for the system. Either the on/off valve or the throttle valve are used
for the heat exchanger to control the temperature of the mixture. Additional auto-
matic wireless on/off control valve can be used for the system also. It is for the
purpose of controlling the upper and lower limit of the chemical tank. The auto-
mated on/off valves for the mixer tank control the liquid overflow. We can use the
digital set-point to trigger the overflow alarm as well as to control the automated
on/off valve. A 4–20 mA level transmitter can be used to detect the level in the
tank. We can align the signal and scaled it to the 0–0.73 range for the digital valve.
Such that when the level is low at 0 mA, the valve will receive a 0.73 digital signal
to open the valve fully. If the level reaches the full 20 mA signal, it will activate the
valve with a zero signal to close it (Fig. 9.17).
The NN control system can be programmed to perform the function. We can insert
a delay sampler between the input neurons and the input weights of the neural
network. We program the system to detect the input signals from the valves at every
20 s interval. It is the same as delaying the system for every 20 s. Another way is to
antenna controller
actuator
valve
Fig. 9.18 Wireless valve automation [32]. Courtesy of Emerson Process Management
set the sampling period for the wireless transmitting rate to 0.05 Hz. The NN will
collect the input values to tune it to its desired output. The zero deviations in the
output signals halt the NN from further training. Then, each output parameters are
transmitted wirelessly to the valves. We set a transmitting delay at the output of the
NN system to the valves. This delay can be set to 10 s or so, as long as it lies within
the system sampling period (set at 20 s). The delay time allows for the automated
valves’ adjustment turns, as well as the valve sensor feedback and wireless trans-
mitting times. Moreover, it also caters for the neural network training and adap-
tation time.
The output sampler turns on again, and the valves accept new input values every
20 s. The closed loop system controls the valves for the desired mixture chemical
with controlled temperature limit (Fig. 9.19).
German engineering ‘JULABO’ [37], offers the state-of-the-art temperature
control technology for a wide range of temperature measurements from −95 °C to
over 200 °C. Several challenging features suitable for lab-based and integrated
outdoor environment, especially for the chemical reaction. Features such as fast
heat-up and cool down times for low power electronic controlled smart pumps
provides a more reliable control technology for heat exchange units. Moreover, the
142 9 Machine Learning
advanced control system operates without changing the bath fluids. Wireless tem-
perature control is available for the chemical process control system. We can easily
integrate the system for process optimization.
The reference input to the system is the desired output of the neural network. We
conduct laboratory experiment for the quantity of the reactance [34] and catalyst
mixture allowed. The mixture is tested to match the quality requirement. We record
the required percentages of the mixture to produce the least heat temperature.
A proportional amount of the mixture is carried out in the actual plant with the
temperature monitored. We then collect the desired sample of the catalyst, reactance
and heat requirements without the NN system involved. Besides, we also collect
several input/output desired sets of the three valves’ settings as input parameters for
training the neural network. The valves’ settings and its parameters are the same.
Their ranges are between 0 and 1. The NN system is trained off-line to tune the
adapted weights and biased parameters to their stable sets of values. Finally, we are
ready to apply these NN parameters to the on-line system. In this way, the online
training time can be reduced.
The control station sets the matching and desire three valves’ positionings with their
parameters (catalyst, reactance and temperature) for the chemical mixture. The flow
and level transmitters of the two small tanks transmit their signals back to the
station and compare the quality of the mixing chemical with the proportional
chemical property, collected from the lab samples. Besides, the temperature signal
at the mixture tank also transmits back to the control station. The quality relates to
the quantities of the reactance and catalyst mixed at the desired temperature. We
first calibrate the temperature of the mixer tank with the heat exchange control
valve, with reference to the catalyst and reactance. The flow and level of each tank
determine the quantities of its chemical. Once the quality of the mixture matches at
the desired temperature, the ideal valves positionings for the three control param-
eters will be set. Calibration can be at the control station, or at the field valve
automated system or both. So we control the amount of catalyst, reactance and heat
produced in the chemical mixing plant. The neural network system controls the
three control valves as shown in Fig. 9.20.
9.10 Valves and Chemical Plant Tunings 143
The offline calculated NN parameters deploy to the real-time system. The trial test is
conducted at the actual plant to get the correct output that we want for the complete
system. We can adjust any initial settings of the three valves’ parameters for the
start. For every 20 s sampling delay, the NN receives three input values from the
valve sensors to calculate at least an iteration in the NN. Through the NN training,
the system can compute the correct output at the output neurons. These outputs
transmit through the delay, and then to the site control valves wirelessly. The valves
are adjusted automatically to produce the desired mixture within the controlled
temperature range. We verify the actual property of the mixture at the plant output.
The trial test completes once the quality satisfies.
There might be a problem that we are unable to boost the temperature up or cool
it down for the mixer tank. For example, when the catalyst input drops, the heat
might not be raised high enough to boost back the chemical reaction to take place.
Remember that we only use a coolant heat exchanger unit in the plant. Hence, our
remedy is to reinforce another heat exchanger to the system. The second exchanger
unit is to supply the heat source to raise the temperature enough for the chemical
reactions. So this heat exchanger is sourced with hot water instead of cooling water.
The control command for the valve of the second heat exchange unit (heat source)
will be opposite as the first (coolant source) unit. We define the valve manipulation
as:
where CCE is the coolant source, and CHE is the heat source, they both control the
valve position variables of the heat exchanger units. Furthermore, we may use four
144 9 Machine Learning
input/output neuron signals for the neural network system to control the chemical
plant. The additional input/output neuron variable references to the hot water
exchanger control valve. We can then fine tune the internal neuron layers if it is
better than the 4-1-4 NN configuration we proposed. The control valves operating
ranges for the reactance is set similarly as the catalyst valve as shown in Fig. 9.22.
Whereas, we set the two heat exchanger valves in the opposite direction as
according to the definition Eq. (9.25). The cooling valve will not set to fully close
while the heating valve will not be set to fully open. These settings can lower the
presence of heat in the reactance at the initial stage (Fig. 9.21).
Finally, we can implement the neural network to the real-time control system.
Training and adaptation are necessary on the online system to eliminate any
transmission network, instrumentations software and sensors errors. We can fit in
9.11 Computerized Neural Network Control System 145
the found NN parameters previously to reduce the training time. The NN param-
eters are automatically trained online again to adapt to the desired output of the
three parameters. The NN outputs are found and transmitted to tune each of the
corresponding valves. The continuous wireless closed loop network calibrates itself
to maintain the valves’ positions for the desired chemical output. In the system, we
can be aware of the on-site valves or instrumentation hardware failures if we detect
any changes in deviation in the actual chemical output with the set target (i.e. we
check for the matchings between the target quality (set valves) and the actual
chemical output quality, from the computerized advisor). Another advantage is that
we can change the desired output online by changing the reference signals to the
output neurons. The system will calibrate itself to its new weights and biased
values. Thus, the control valves changed according to the new values.
For the program, we input the chosen catalyst value for the plant. So the selected
catalyst valve position is referenced or proportional to the catalyst variable. Unlike
the catalyst and the reactance, the temperature is inversely proportional to the heat
exchange valve position. Thus, we inverted and scaled the temperature output
neuron value to control its valve position. We can control the heat exchange valve
to perform the same way as the catalyst valve position variable. First, we need to
calibrate the temperature according to the valve’s variable. We calibrate the tem-
perature of the desired chemical tank output, with reference to the heat exchange
valve position. For example, a valve range from 0 to 0.73 is calibrated to the
temperature from 0 to 73 °C. We can adjust the degree of warm water in the heat
exchanger unit. Scaling is not necessary if the neurons’ value matches the valves’
range. The converted valve’s variable ranges from 0 to 0.73, for the heat valve,
disregards to the actual temperature readout in the mixer tank. The computer station
does the conversions. For the coolant valve, we convert the variable for the valve
positioning, by using the formula Eq. (9.24), with reference to Fig. 9.22. The heat
exchange valve position is transmitted back to the input neuron with the same
conversion and scaling as at the temperature output neuron. We maintain the
reactance input set valve position at a level of percentage tolerance (at ± desired
valve setting). Similarly, as the catalyst parameter, if we convert the output neurons
of the reactance to the control valve, it has to be inverted back from the control
valve variables to the input receiving neuron. Remember that we set and convert all
the three parameters of the valve’s positioning values to the input neurons. The
neurons accept values from 0 to 1 for computation. Figure 9.24 shows the training
convergence for the 3-1-3 neural network configuration. After training, we simulate
the result to a random set of input for the three neurons. The simulation converges
146 9 Machine Learning
6 Epochs
Input Sample
9.11 Computerized Neural Network Control System 147
to the target output after six epochs. We record the training weights as shown. The
output Y matches our desired values [0.93 0.35 0.71]. Figure 9.25 illustrates the
output result. However, we can increase the numbers of target tracked at the same
time by increasing the hidden neurons in the program (Fig. 9.23).
--------------------------------------------------
Program 9.1: Neurons Simulated Valves
--------------------------------------------------
real= [0.15 0.47 0.17; 0.42 0.23 0.74; 0.41 0.58 0.2; 0.09 0.51 1; 1 0.48 0.39; 1 0.37
1; 1 0.53 0.2; 0.82 0.56 1;0.17 0.5 0.43];
E=transpose(real)
p = [1 0.5 0.2]; !input captured or feed in from field database
P=transpose(p); !correct
t = [0.93 0.35 0.71; 0.93 0.35 0.71; 0.93 0.35 0.71; 0.93 0.35 0.71; 0.93 0.35 0.71;
0.93 0.35 0.71;0.93 0.35 0.71;0.93 0.35 0.71;0.93 0.35 0.71];
T=transpose(t); !the most only 2 different set binary targets can be tracked accurately
net = newff([0 1;0 1;0 1],[1 3],{'logsig' 'logsig'});
net.trainParam.show = 50; !only 1set of real target can be tracked accurately
net.trainParam.lr = 0.05;
net.trainParam.epochs = 38000;
net.trainParam.goal = 1e-24;
net.trainParam.gradient = 1e-15;
net.iw{1,1}=[0.3 0.5 0.1] ; !initial data
net.lw{2,1}=[0.1; 1; 0]; !Initialised data
net.b{1,1}=[0]; ! biased at ‘0’ to reach best performance goal
net.b{2,1}=[0; 0; 0]
[net,tr]=train(net,E,T);
iw=net.iw{1,1}
lw=net.lw{2,1}
bias=net.b{1,1}
bias2=net.b{2,1}
Y = sim(net,P)
Tar=[0.93 0.35 0.71];
Target=transpose(Tar)
input=[1];
plot(input,Target,'r+',input,Y,'ko')
hold; xlabel('Input Sample');
ylabel('Output Y'); title('Output Layer Neurons'); hold;
----------------------------------------------------------------------------------
Output Results : Output Y matches the target, with a given input P
----------------------------------------------------------------------------------
TRAINLM
Epoch 0/38000, MSE 0.101745/1e-024, Gradient 1.43031/1e-010
Epoch 6/38000, MSE 1.77237e-025/1e-024, Gradient 1.78259e-014/1e-010
Performance goal met.
148 9 Machine Learning
lw = 0.9733
0.3275
0.2445
bias = 0.0014
bias2 = 2.0997
– 0.7829
0.7731
Y = 0.9300
0.3500
0.7100
Target = 0.9300
0.3500
0.7100
We can establish on-line purity assessment and track the chemical reactions of the
plant. Equipment from ‘Magritek’ can be used to monitor the state of the plant.
Spinsolve software can be customized to track the plant reactions. Moreover, we
can program a neural network system to advise on the differences between the
actual chemical plant and the desired target quality (see reference [36] DeltaV
system). The plant feedback variables from the automation, system or the chemical
software are stored and retrieved by the computerised advisor. We can return
position variables from the field valves into the computer neural network advisor by
using ODBC. So, all the field instrumentation information, including the valve
variables are updated continuously and stored in the database for retrieval.
9.11 Computerized Neural Network Control System 149
The NN advisor performs training for eight sampling targets for the chemical
desired qualities. The neural network for the advisor uses 3-5-1 NN configuration.
Each desired target shows in asterisk in the figure. For example, we select a target
quality (target sample 7) at 0.38. So we feed in reference valves input [1 0.83 0.2]
as the three valves variables to produce the target quality. The NN plant control
system (P9.1) operates, and control its valves to their positions in the field. If the
catalyst valve is stucked at position 0.89 (should be 1), the quality advisor will
receive the mismatch target at 0.32 (target sample 3). Thus, the incorrect or not
matching target lead us to troubleshoot the plant or valve error at the field site.
Hence, the intelligent advisor system determines the site hardware failure to activate
an alarm. Following up, we implement the fault correction at the field site
(Fig. 9.26).
150 9 Machine Learning
------------------------------------------------------------
Program 9.2: Computerized NN Quality Advisor
------------------------------------------------------------
real= [0.15 0.47 0.17; 0.42 0.23 0.74; 0.41 0.58 0.2; 0.09 0.51 1; 1 0.48 0.39; 1 0.37
1; 1 0.83 0.2; 0.82 0.56 1;0.17 0.5 0.43];
E=transpose(real)
t = [0.8204 ;0.5678 ;0.32 ;0.58 ;0.679 ;0.45 ;0.38 ;0.12 ; 0.42];
T=transpose(t); !Target qualities trained
net = newff([0 1;0 1;0 1],[5 1],{'logsig' 'logsig'});
net.trainParam.show = 50; !3-5-1 configuration to train more targets
net.trainParam.lr = 0.05; !at a time.
net.trainParam.epochs = 38000;
net.trainParam.goal = 1e-24;
net.trainParam.gradient = 1e-15;
net.iw{1,1}=[0.3 0.5 0.1;0.3 0.5 0.1;0.3 0.5 0.1;0.3 0.5 0.1;0.3 0.5 0.1]
net.lw{2,1}=[0 0 0 0 0]; !initialisztions
net.b{1,1}=[0; 0; 0; 0; 0]
net.b{2,1}=[0]
W1 = net.iw{1,1}
W2 = net.lw{2,1}
b1= net.b{1,1}
b2= net.b{2,1}
[net,tr]=train(net,E,T); !trainings
iw=net.iw{1,1}
lw=net.lw{2,1}
bias=net.b{1,1}
bias2=net.b{2,1}
Y1 = sim(net,E)
T
conne=database('db1','',''); ! on-line updated database stored in db1
bo = exec(conne,'select all Field1 from Table1');
sor=fetch(bo,3);
a=sor.Data{1,1};
b=sor.Data{2,1};
c=sor.Data{3,1};
inp=[a;b;c]
! inp = [0.89; 0.83 ;0.2]; incoming 3 valves feedback retrieved from db1
Y = sim(net,inp); !simulated quality feedback from the field
iw=net.iw{1,1}
lw=net.lw{2,1}
bias=net.b{1,1}
bias2=net.b{2,1}
input=[1 2 3 4 5 6 7 8 9]; figure(2);
plot(input,Y1,'k*')
hold; xlabel('ASTERIKS - Trained Target Sample');
9.11 Computerized Neural Network Control System 151
In computer vision, we often encounter problems of errors when all the pixels has
been thresholded. We often encounter two types of errors as a result of the extremes
of the two final level classifications as either foreground or background.
1. We are not able to catch all the included pixels in the group.
2. Some pixels caught should not be in the group.
So the choice of thresholding comes in, to balance these two types of error. The
threshold level is between 0 and 255 with reference to the black or the white
background respectively. We implement a two steps thinning algorithm without
violating the following constraints.
1. Does not remove end points.
2. Does not break connectivity.
3. Does not cause excessive erosion of the region.
The program consists of two separate programs. Mainly the binary .m file and the
thinning .m file. The binary program includes the ‘Binary’ function and the ‘Binarise’
sub-function. The main function process the seven different kinds of the images to
read in and the different threshold level. It will call the binaries sub-function to do the
binary processing. The outcome of this program will create seven images stored into
different filenames each. The outcome is the binary images produced.
The second program ‘thinning .m’ which has the thinning function to do the
thinning process. Besides, it also has six different sub-function to support the main
program function. They are mainly the function: initialize, change, searchblack,
transition, steponecd and steptwocd. The initialize function is to initialize the
replacement data “AData” and the stored data “SData”. After which the change
function is to convert the black seeds or pixels into white pixels in the image. It is
10.3 Brief Descriptions of the Program Algorithms 155
------------------------------------------
Program 10.1 Binarise Algorithm
------------------------------------------
%Binarise Original Images
function Binary
global map imga h CData Y height width t Y1 image
image=’img1.bmp’ %define image
[imga,map]=imread(image); %input image
height=336; %image height
width=339; %image width
t=150; %threshold level
figure(1) %open figure to view ready image
Binarise %apply thresholding to view the character clearly
imwrite(Y1,map,’bimg1.bmp’); %save image as a filename
image=’img3.bmp’ %an image is chosen
[imga,map]=imread(image);
height=349;
width=357;
t=70; %threshold level is input defined (changeable)
figure(3)
Binarise
imwrite(Y1,map,’bimg3.bmp’); %save as a different filename
image=’img4.bmp’
[imga,map]=imread(image);
height=746;
width=668;
t=70;
figure(4)
Binarise
imwrite(Y1,map,’bimg4.bmp’);
image=’img5.bmp’
[imga,map]=imread(image);
height=535;
width=576;
t=200;
figure(5)
Binarise
imwrite(Y1,map,’bimg5.bmp’);
image=’img6.bmp’
[imga,map]=imread(image);
height=436;
width=469;
t=70;
figure(6)
Binarise
imwrite(Y1,map,’bimg6.bmp’);
function Binarise %Binary function
global imga map Y CData h height width t Y1
10.3 Brief Descriptions of the Program Algorithms 157
h=image(imga);
colormap(map);
Y=get(h,’CData’); %grap image data (CData)
CData(1:height,1:width)=Y
for i=1:height %thresholding
for j=1:width
if CData(i,j)>=t
CData(i,j)=255;
elseif CData(i,j)<t
CData(i,j)=0;
end
end
end
Y1=CData(1:height,1:width) %Binarised matrix value
imwrite(Y1,map,’bimg.bmp’); %store temporary image in file
[Y1,map]=imread(‘bimg.bmp’); %read binarised image
imshow bimg.bmp; %show image
----------------------------------------==-
Program 10.2 Thinning Algorithm
--------------------------------------==---
function Thinning %thinning algorithm
global width height x y CData Yes AData seed SData
height=336; %image height depending on image input
width=339; %image width depending on image input
Yes=0; %initialisation
seed=0;
convert=0; %initialise convert
initialise; %initialise matrix
[Y1, map]=imread(‘bing1.bmp’); %changeable input image
h=image(Y1);
colormap(map);
Y=get(h,’CData’);
CData(1:height,1:width)=Y;
for y=1:height %Perform Step1
for x=1:width
if CData(y,x)==0 %if black seed found
searchblack; %do the 3 criterior of step 1
out1=Yes; %or the 4 conditions of step 1
transition;
out2=Yes;
steponecd;
out3=Yes;
out1+out2+out3;
if out1+out2+out3==3 %if satisfy the 3 criterior to convert
convert=1; %activate convert
AData(y,x)=CData(y,x); %flagged for conversion
else
SData(y,x)=CData(y,x); %store black seed for next round thinning decision
158 10 Computer Vision
for x=1:width
if SData(y,x)==CData(y,x) % if black seed found
searchblack;
out1=Yes;
transition;
out2=Yes;
steptwocd;
out3=Yes;
out1+out2+out3;
if out1+out2+out3==3
convert=1; %activate convert
AData(y,x)=CData(y,x);
seed=seed-1;
else
SData(y,x)=CData(y,x);
convert=0; %check for no convert, may be removed for total thinning
seed
end
end
end
end
change;
end
Y1=CData(1:height,1:width) %Binarise matrix value
imwrite(Y1,map,’timg11.bmp’); % store image into a file
[Y1,map]=imread(‘timg11.bmp’); %readin image to be displayed
figure(2);
imshow timg11.bmp; %display image
In the first five sets of the character examples, pictures two, three, and five, give the
same amount of thresholding of about 70 into the image, while that of image 1,
thresholds at 150 and image four thresholds at a value of 200. For image one, when we
Fig. 10.1 Chinese characters (images sets 1 and 2). Note T represents threshold level within
0–255
162 10 Computer Vision
Thinned at T=50
input a binarized level of 150 will perform the thinning well. If a value of 230 is input,
the resulting character after thinning will still be fined. But if we apply a threshold
level of 70, it will result in a blank image after binarized, so is after thinning.
Image 2 is binarized at a value of 70. We can binarize the image at a level of 10
also. The outcome after thinning is as good. However, if we use a value of 200 or
150 as the threshold level, the binarized image will produce some black patches.
And if thinned, the character will not be a skeleton. It will still be fat with only
minor trimmings of the character.
The black and dark original image 3, if binarized at 200, will cause the creation
of the black border boundary, which is far away from the character, to appear in the
image after thinning. It is the result of the excessive level of the threshold value
applied. However, when thresholded at 150, the final thinning result will still create
a slightly fatter image character. It is not the full thinning operation, and we cannot
produce the skeleton outcome. On the other hand, when binarized at a value of
about 10, will result in the breaking connectivity of the character when after
thinning. Image 4 has a faint image, so a higher value of the thresholding is needed.
Image 4 erodes when thresholded at a level of 50. The final result of the eroded
character after thinning will be a blank white image without any character in view.
If binarized at a value of 230, or slightly over thresholded, the outcome will be a
slightly fatter skeleton, which will still look like a character, but only never
skeletoned. Moreover, the borderline of the image will appear.
In image 5, the average threshold is at 70–10. It is because it has a dark original
image background, so lesser thresholding level is required. However, if we bina-
rized at a very large value of 200, the character itself will be over darken and tends
to become overconnected as if black ink leaks out from the character. Besides,
black dots started to appear in the image from nowhere. The character will worsen
when we thinned it. It will become a dark patch of an unrecognised character
(Figs. 10.1, 10.2).
given image is only an 8-bit colour depth image. It represents only one (8-bit) out of
the three primary colour (24-bit) components. Zhang Suen’s method of thinning
provides an erosion of the original image into a skeleton. Likewise, it can also just
thinned a bit, which results in the thick character still remainings. The thresholding
level affects the thinnings of the characters. If the threshold level is too high towards
white, applying thinning algorithm will convert more to the black side which will
eventually darken the image. However, if the threshold level is small towards the
value of black (zero), applying thinning will convert lesser of the value to the black
region thereby causing connectivity brokage of the character. It, therefore, results in
the eroding of the character from the original image. That is what happens to the
final results to some of the characters applied (Figs. 10.3, 10.4).
Appendix A
MC68HC11 Registers
' startup.bas
ProgramPointer $8000
DataPointer $2000
StackPointer $7FFF
sect text
cli ; enable debugger
ldx #_data_s
bra _crt2
_crt1 clr 0,x ; clear data area
inx
_crt2 cpx #_data_e
bne _crt1
sect data
_data_s equ *
'PORTA TESTER
int j,f
byte portg at $1002 do
byte ddrg at $1003 portg=$07
ddrg.1 = 1 delay(300)
byte portc at $1061 'no need portg=$0b
define ddrc delay(300)
'byte title()=" Microprocessor" portg=$ff
'byte portc at $1006 'single chip portd=$df
mode no need define ddrc delay(300)
for j=100 to 0 step -1 portd=$ef
for f= 0 to 1000 delay(300)
portg.1=0 portd=$f7
next f delay(300)
next j portd=$fb
ASM cli delay(300)
do portd=$ff
if portc.4=0 then portg.1=0 loop
if portc.4=1 then portg.1=1
portc.4=0 'useless command function delay(c)
loop int i
for c=c to 0 step -1
function delay(c) for i= 0 to 1000
int i next i
for c=c to 0 step -1 next c
for i= 0 to 1000 end function
next i
next c
end function
'PORTE TESTER
ProgramPointer $8000
DataPointer $0002
StackPointer $7FEF
172 Appendix B: MCU Port Testers
1. http://www.datasheet4u.com/datasheet/7/4/L/74LS08_FairchildSemiconductor.pdf.html
(2-input AND gate)
2. http://www.datasheet4u.com/datasheet/7/4/L/74LS32_FairchildSemiconductor.pdf.html
(2-input OR gate)
3. http://www.datasheet4u.com/datasheet/7/4/L/74LS04_FairchildSemiconductor.pdf.html (hex
inverting gate)
4. http://html.alldatasheet.com/html-pdf/171559/TI/74LS244/24/1/74LS244.html (Buffer or
Line driver)
5. http://www.ti.com/lit/ds/symlink/sn74ls74a.pdf (Dual D-Latch)
6. http://docs.google.com/viewer?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fwww.datasheet.hk%2Fdownload_
online.php%3Fid%3D1027398%26pdfid%3D384EA12E7F41ADD153FD14E6B124409A
%26file%3D0021%5Csn74ls76_186750.pdf&embedded=true (Negative-edge triggered J-K
flip-flop)
7. http://www.alldatasheet.com/datasheet-pdf/pdf/22437/STMICROELECTRONICS/L298.html
(Motor driver)
8. http://www.pepperl-fuchs.com/global/en/classid_142.htm (proximity sensor)
9. http://ph.parker.com/sg/en/solenoid-valves (soleniod valve)
10. http://pdf.datasheetcatalog.com/datasheet/siemens/BUZ12.pdf (BUZ12)
11. http://www.datasheetarchive.com/dl/Datasheet-093/DSA0066289.pdf (IN4001 diode)
12. http://cache.freescale.com/files/microcontrollers/doc/data_sheet/M68
13. HC12B.pdf?pspll=1 (MCU 68HC12 family)
14. http://html.alldatasheet.com/html-pdf/50893/FAIRCHILD/7407/403/1/7407.html
(open-collector output hex buffer)
15. http://www.datasheetarchive.com/dlmain/Databooks-2/Book259-13.pdf (4N28 opto-coupler)
16. http://www.alldatasheet.com/datasheet-pdf/pdf/8979/NSC/LM555.html (555 timer)
17. http://www.ti.com/lit/ds/symlink/uln2003a.pdf(darlington transistor)
18. http://courses.cs.tau.ac.il/embedded/docs/LPC2148_Education_Board/KS0070B.pdf (LCD
dot matrix)
19. http://www.ee.nmt.edu/*rison/ee308_spr98/supp/feb_9/hc11_h.html (hc11.h file).
20. The Intel Microprocessors 8086/8088,..80186,486..pentium,..core2 Architecture, Programming
& Interfacing - (2009) by Barry B. Brey
21. http://www.emsl.pnl.gov (process control)
22. Evolutionary Learning Algorithms for Neural Adaptive Control (Perspectives in Neural
Computing) by Dimitris Dracopoulos (Sep 12, 1997)
23. http://www.neurodimension.com/
24. A neural network approach to on-line monitoring of machining processes by Raju G
Khanchustambham, Neural Networks, 1992. IJCNN., International Joint Conference on
(Volume:2),1992.
25. http://www.documentation.emersonprocess.com/groups/public/documents/specification_
sheets/d301714x012.pdf (Remote Operation controller ROC800)
26. http://www.documentation.emersonprocess.com/groups/public/documents/specification_
sheets/d301731x012.pdf (Network Radio Module NRM)
27. http://www2.emersonprocess.com/siteadmincenter/PM%20Rosemount%20Documents/008
13-0100-4075.pdf (Smart Wireless THUM Adapter)
28. http://www2.emersonprocess.com/siteadmincenter/pm%20rosemount%20documents/00813-
0100-4648.pdf (Rosemount 648 Wireless Temperature Transmitter)
29. http://www.documentation.emersonprocess.com/groups/public/documents/instruction_
manuals/d103621x012.pdf (Wireless Valve Position Monitoring)
30. http://www.westlockcontrols.com/products/wireless/?id=tcm:528-34768&catid=tcm:528-32
300-1024#product-description-tab (Wireless Valve Monitoring System)
31. http://westlockcontrols.com/Images/WESTDS-09082-EN-1304.pdf (Manual for Wireless
Valve Monitoring System)
32. http://www2.emersonprocess.com/siteadmincenter/PM%20Articles/VM_FALL12_Wireless_
Reprint.pdf (Wireless Valve Automation)
33. http://www.scientistlive.com/content/flexible-solution-high-throughput-evaporation?dm_i=
371,3ZRZE,BIJ57N,EF9MF,1 (Evaporation Monitoring)
34. http://www.scientistlive.com/content/routine-purity-assessment-and-reaction-monitoring?
dm_i=371,3ZRZE,BIJ57N,EF9MF,1 (Reaction Monitoring)
35. http://www.magritek.com/2015/12/17/magritek-introduce-reaction-monitoring-kits-for-
spinsolve-benchtop-nmr/ (NMR Monitor)
36. www.EmersonProcess.com/DeltaV (DeltaV system)
37. http://www.julabo.com/ (Temperature control technology)
Index
L R
Ladder, 2, 91, 93, 94, 96, 98 Reaction, 124, 133–138, 141, 143
LCD, 44–54 Register, 7, 23, 34, 39, 41, 43, 52, 59–61, 69
Level(s), 27–29, 35, 39, 56, 61, 69, 93, 94, 96, Rotate/Rotating, 29, 69, 72, 74
98, 100, 115, 116, 118, 120, 134, 135, 140,
142, 145, 153, 154, 156, 163, 165 S
Lift, 2, 91–94, 96, 98–100 Sense, 19, 32, 65, 133, 138
Light(s), 2, 14, 27, 34, 91–94, 96, 98 Sensor, 6, 12, 19, 23–24, 27, 28, 34–35, 67, 71,
Liquid, 3, 27, 29, 118, 134, 140 115, 121, 124, 129, 130, 132, 133, 139,
Logic, 2, 12, 27, 29, 39, 91, 96, 122 141, 143, 144
Servomotor, 2, 79
M Signal, 2, 7, 24, 27, 35, 39, 51, 59, 61, 65, 67,
Mechanism, 2, 87, 88, 118 79, 80, 82, 87–89, 93, 115, 122, 124, 130,
Mechatronics, 1, 2, 27 134, 135, 140, 142
Memory, 5, 7, 12, 19, 26 Single, 3, 7, 63, 118, 140
Index 181
Software, 1, 2, 5, 14, 19, 39, 121, 138, 144, Timing, 19, 23, 38, 58, 94, 99, 100
148 Track, 51, 124, 147, 148, 153
Speed, 5, 7, 27, 35, 59, 61, 64, 71, 120, 134, Transient, 79, 120
135 Transistor, 28, 42, 67
Stop, 25, 27–29, 61, 69, 96, 98, 127 Trigger, 6, 19, 25, 29, 35, 140
Switch/Switches, 7, 12, 14, 19, 21–22, 28, 29, Turn(s), 6, 19, 29, 32, 63, 69, 139, 141, 164
34, 39, 61, 63, 67, 79, 91, 93, 96, 98, 106
System, 1, 2, 5–7, 17, 19–20, 27, 34–35, 58, V
63, 66, 87, 88, 91, 94, 98–101, 104, 106, Valve, 3, 27, 28, 87, 115, 132, 134–136,
115, 118, 120–122, 127, 129, 130, 138–143, 145, 148, 149
132–140, 142–144, 148, 149 Vision, 1–3, 153
T W
Tank, 2, 3, 27, 28, 115, 118, 140, 142, 143, Water, 2, 3, 27, 28, 115, 134, 143, 145
145 Wireless, 134, 138, 140–142, 145
Timer, 7, 35, 38, 59–60, 64, 82, 83, 94, 96, 98,
99