0% found this document useful (0 votes)
33 views1,027 pages

Antony J. Computer Interfacing and Automation. Hardware, Firmware..Software 2020

The book 'Computer Interfacing and Automation' by Dr. J. Antony focuses on hardware, firmware, and software design for automation and control systems, bridging the gap between academic knowledge and industry applications. It covers essential topics such as microcontroller technologies, PLC, SCADA, and IoT, making it suitable for students and professionals in electronics and computer sciences. The book includes practical examples and projects, particularly from accelerator-based physics research, to enhance the learning experience.

Uploaded by

budinski29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views1,027 pages

Antony J. Computer Interfacing and Automation. Hardware, Firmware..Software 2020

The book 'Computer Interfacing and Automation' by Dr. J. Antony focuses on hardware, firmware, and software design for automation and control systems, bridging the gap between academic knowledge and industry applications. It covers essential topics such as microcontroller technologies, PLC, SCADA, and IoT, making it suitable for students and professionals in electronics and computer sciences. The book includes practical examples and projects, particularly from accelerator-based physics research, to enhance the learning experience.

Uploaded by

budinski29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1027

Computer Interfacing and Automation

TM

Computer Interfacing

Computer Interfacing and Automation


and Automation

978-81-947787-8-3

` 1195/- Distributed by:

9 788194 778783 TM
Computer Interfacing and Automation
Hardware, Firmware and Software Design: Theory and Practice
Computer Interfacing and Automation
Hardware, Firmware and Software Design: Theory and Practice

Dr. J. Antony
BE (E & CE), MTech (USA), PhD (IIT)
Inter University Accelerator Centre
New Delhi
Computer Interfacing and Automation
Authors: Dr. J. Antony

Published by I.K. International Pvt. Ltd.


4435, 36/7, Ansari Road, Daryaganj, New Delhi-110002

ISBN: 978-81-947787-8-3

EISBN: 978-81-947787-1-4

©Copyright 2020 I.K. International Pvt. Ltd., New Delhi-110002.

This book may not be duplicated in any way without the express written consent of the publisher,
except in the form of brief excerpts or quotations for the purposes of review. The information
contained herein is for the personal use of the reader and may not be incorporated in any commercial
programs, other books, databases, or any kind of software without written consent of the publisher.
Making copies of this book or any portion for any purpose other than your own is a violation of
copyright laws.

Limits of Liability/disclaimer of Warranty: The author and publisher have used their best efforts in
preparing this book. The author make no representation or warranties with respect to the accuracy or
completeness of the contents of this book, and specifically disclaim any implied warranties of
merchantability or fitness of any particular purpose. There are no warranties which extend beyond the
descriptions contained in this paragraph. No warranty may be created or extended by sales
representatives or written sales materials. The accuracy and completeness of the information provided
herein and the opinions stated herein are not guaranteed or warranted to produce any particulars
results, and the advice and strategies contained herein may not be suitable for every individual.
Neither Dreamtech Press nor author shall be liable for any loss of profit or any other commercial
damages, including but not limited to special, incidental, consequential, or other damages.

Trademarks: All brand names and product names used in this book are trademarks, registered
trademarks, or trade names of their respective holders. Dreamtech Press is not associated with any
product or vendor mentioned in this book.

Edition: 2020

Printed at: Rekha Printers


This book is dedicated to my wife
Swapna and son, Alan and my parents.
PREFACE

Today’s engineers are different and versatile, making use of the current technologies to
build systems of their own. Technologies like Internet of Things (IoT) and System on
Chip (SoC) are taking a giant leap in the market. However, there is a huge void when
it comes to building the basic knowledge to understand and integrate the technology.
This is where this book comes handy. Readers may find a broad collection of books on
electronics & general programming. These, however, are unable to cater to the needs of
those who want to design and interface an electronic product, which is either their own
design or already designed by someone else. Hence, this book deals with hardware,
firmware and software for automation and also, the ultimate coverage of computer
interfacing in automation and control. This is a very promising topic today.
This book will cover a broad spectrum of readers. It is especially useful for students
pursuing their Diploma/BSc in Electronics, BTech and MSc students from both Electronics
and Computer Sciences and MTech and students pursuing PhD in Physics or Electronics.
Many practical examples have been taken from the accelerator-based physics research.
Accelerator research has been contributing to society in terms of technology inventions
like WEB at CERN. I was fortunate to be a part of LHC installation at CERN, Geneva,
from where I learned the importance of all technology topics discussed in this book.
The basic technologies which I have focused are mainly the microcontroller
technologies like ARM, interfaced to Ethernet and ATMEL processors, FPGA basics, etc;
whereas the commercial technologies which I focused on are PLC, SCADA and LabVIEW,
etc., which are indispensable for automation engineers.
This book is also written to bridge the gap between the academics and industry. For
both, this book is very useful. PLC and SCADA are basically the building blocks of
industrial automation. A lot of emphasis has been given to learning GUI design, as it
is a part and parcel of any control engineer. Learning C++ through Qt environment
makes one learn both together. GUI under Windows is demonstrated using LabView.
For those who are learning firmware design, ARM Mbed online compiler is used for
firmware design and it needs C++ programming basics which are designed using very
simple examples. For Windows users, the LabView GUI design is explained from basics.
This book covers the latest topic “IoT” and will be an asset to those who want to
learn Internet of Things. Moreover, interfacing has been given top most importance by
including chapters on RS232, SPI, GPIB, CAMAC, VME, etc., and related projects.
Constructive criticism for further improvement will be highly appreciated. The same
can be sent to me on: [email protected]
Dr. J. Antony
ACKNOWLEDGEMENTS

This book has come out from my work at IUAC, New Delhi, a premier research center
of accelerator-based research. This research needs all basic and advanced digital
electronics. Therefore, I acknowledge every scientist and engineer of IUAC who has
indirectly contributed to this book. I also acknowledge Mr. Alan. J. Antony, student of
BITS Pilani, who has taken a lot of pain reading through every chapter, specially his
effort to document this using his English skills at the young age. I also acknowledge
Directors of IUAC, New Delhi, for their support. I also thank Mr. Sumit Kumar and
Mr. Adarsh Kumar Yadav, who helped me to do some documentation for this book.
Finally, I acknowledge my wife and son, who supported me throughout in making
this book a reality.

Dr. J. Antony
CONTENTS

Preface vii
Acknowledgements ix
1. RS-232 Serial Communication 1
1.1 Introduction 1
1.2 Serial vs Parallel Data Transmission 2
1.3 RC Pulse Distortion in Digital Transmission 5
1.4 UART 6
1.5 RS-232 8
1.6 Other Serial Standards 13
1.7 DTE and DCE 16
1.8 DTE to DCE Communication 19
1.9 RS-232 Bit Format 22
1.10 Handshaking (Flow Control) 23
1.11 RS-232 C Protocol 31
1.12 Half-Duplex vs Full-Duplex 33
1.13 Asynchronous vs Synchronous 34
1.14 Electrical Standards in Detail 36
1.15 Signal Characteristics 37
1.16 Signal State Voltage Assignments 39
1.17 ASCII Commands 40
1.18 Level Shifter 40
1.19 Reading RS-232 Data to a PC Using Visual Basic 6.0 42
References 89
Review Questions 91
Answers 91
2. LabVIEW Programming Basics for Control Graphical
User Interface (GUI) Design 105
2.1 Introduction: Why LabVIEW? 105
2.2 LabVIEW Comes to Rescue 106
2.3 Basic Example of LabVIEW 110
xiiȳ˜—Ž—œ

2.4 Basic Semaphore: Introduction 125


2.5 Ctl File in LabVIEW 125
2.6 Advanced HTTP Server Library Comes with LabVIEW by Default 126
References 129
Review Questions 129
Answers 129
3. Microcontroller-based Embedded Design: Hardware Engineering 131
3.1 Microprocessor 131
3.2 Microcontroller 133
3.3 Hardware COTS Design (Component Level) 135
3.4 PLL Synthesizers 137
3.5 FT232R USB UART IC 138
3.6 Electronic Memory 139
3.7 PCB Design 141
3.8 Programming the Micro Memory 144
3.9 In-System Programming 146
3.10 Binary to HEX Generation 153
3.11 Connecting Programmer to Program ARM Chip LPC1768 153
3.12 How to Design Own ARM Mbed Board Compatible to LPC1768
Mbed ARM Board (Available in Market) 163
3.13 Conclusion 187
References 188
Review Questions 188
Answers 189
4. Proportional Integral Derivative (PID) 190
4.1 Introduction 190
4.2 Analog PID 190
4.3 Digital PID Controller 192
4.4 Analog vs Digital PID 193
4.5 Firmware for Digital PID Control 194
4.6 Accurate Water Heater System Design 195
4.7 Analysis of Output with Respect to Input 198
4.8 Accurate Heater of a Copper Block 204
4.9 Low-Temperature Cooling System for Variable Temperature Calibration
Setup (14 to 409 Kelvin) 205
4.10 Digital PID Control Code (Psedo Code Only) 205
References 206
Questions & Answers (1-5) 207
Answers (6-10) 216
˜—Ž—œȳxiii

5. RS-485, Data Logging and Supervisory Control (DSC) via Modbus


Using LabVIEW 218
5.1 Introduction 218
5.2 RS-485 Standard 219
5.3 Block Diagram of DSC 227
5.4 Modbus Serial Device Server 235
5.5 Data Acquisition Module 242
5.6 LabVIEW for Modbus Communication 246
5.7 Using Modbus I/O Servers (DSC or Real-Time Module) 249
5.8 Configure the Serial Device Server Utility 265
5.9 AIN, AOUT, DIN, DOUT Using Modbus 270
5.10 Modbus Interfacing of Honeywell PID Controller 277
References 282
Review Questions 283
Answers 283
6. SCADA Using Wonderware InTouch 286
6.1 Introduction : SCADA 286
6.2 Wonderware InTouch SCADA 287
6.3 Trends in Wonderware InTouch 309
6.4 Reading Data from an Excel Workbook into InTouch 313
Reference 320
Review Question 320
Answer 320
7. Programmable Logic Controllers, HMI and Variable Frequency Drives
(PLC and VFD) 321
7.1 Programmable Logic Controller (PLC) 321
7.2 Basic Ladder Programming 323
7.3 Control Three-Phase Induction Motors Using Delta VFD and
an AB Micrologix 1000 PLC a Project Example 340
7.4 Project: Build an Automation System Using Allen-Bradley
PLCs and InTouch Wonderware SCADA 350
References 369
Review Questions 369
Answers 369
8. C++ for Software & Firmware Design: Lay Strong Foundation First 371
8.1 Introduction 371
8.2 C++ Environment Setup 371
xivȳ˜—Ž—œ

8.3 Compile & Execute C++ Program 372


8.4 Solved Problems 372
References 408
Review Questions 408
Answers 408
9. Firmware Programming Using ARM Mbed Microcontroller &
Cloud Compiler 410
9.1 Why ARM Mbed? Using LPC1768 for Embedded System Applications 410
9.2 Introduction 410
9.3 Hardware Development Kit (HDK) 411
9.4 Software Development Kit (SDK) 411
9.5 Worldwide Developer Community 411
9.6 Free Online Development Tools 411
9.7 LPC1768 Based ARM Mbed Board: Hardware and Compiler
Library Support 412
9.8 Mbed and Programming Interrupts 416
9.9 Experiments/Projects Using ARM Mbed 1768 40-Pin DIP 426
9.10 Program Analog Input and Output Using 32-bit ARM Mbed
Microcontroller LPC1768 432
9.11 Program Digital Input and Output Using ARM Mbed – 32-bit
Microcontroller 438
9.12 Memory Function Types 443
9.13 Developing Advanced Embedded Systems Using 32-bit ARM Mbed 446
9.14 Program Bytes of Parallel Data Using 32-bit ARM Mbed 452
9.15 Programming PWM Using 32-bit ARM Mbed 464
9.16 Program 32-bit ARM Mbed Using I2C 467
9.17 Introducing SPI Programming with 32-bit Microcontroller ARM Mbed 473
References 483
Review Questions 485
Answers 485
10. GUI Designs Using Qt a C++ Toolkit 487
10.1 Introduction 487
10.2 Qt Creator 488
10.3 Qt Designer 489
10.4 Creating a Project in Qt 490
References 506
Review Questions 506
Answers 506
˜—Ž—œȳxv

11. Introduction to Web Automation Basics, H/W Accessories 507


11.1 Internet Networking 507
11.2 Hard Drivers 517
11.3 Relays and Solid State Relays 527
11.4 Controlling Machine Using Network/Proprietary Computer Software
or Mobile WI-FI 543
References 547
Review Questions 547
Answers 547
12. Computer Automated Measurement and Control (CAMAC) & VME Bus 548
12.1 Introduction 548
12.2 Dataway Lines 556
12.3 Mechanical Characteristics 561
12.4 Serial Connection of Crates 574
12.5 VME Bus 584
12.6 Implementation in Accelerators : A Case of Practically Working System
Study in Physics Machine Control 586
References 588
Review Questions 588
Answers 588
13. Field-Programmable Gate Arrays (FPGAs) & VHDL Basics 589
13.1 Introduction to FPGA 589
13.2 Spartan-3E Kit: A Popular Kit to Learn and Understand FPGA
Design Flow Basics 598
13.3 Understand Implementation & Design Flow by Using
Xilinx ISE Webpack 11.1 617
References 628
Review Questions 628
Answers 628
14. General Purpose Interface Bus (GPIB) 634
14.1 IEEE-488 Interface Bus (HP-IB/GP-IB) 634
14.2 History and Concept 638
14.3 The 488.2 Standard 641
14.4 SCPI Commands 642
14.5 Writing GPIB Programs 647
14.6 GPIB Instrument Control and LabVIEW® 652
14.7 Project: To Create an RT Measurement Setup 654
xviȳ˜—Ž—œ

14.8 GPIB and RS-232 Interfacing Using LabVIEW 659


Review Questions 686
Answers 686
15. 8-bit ATMEL Microcontroller-based Web Server and Qt Interfacing:
A Web I/O Server 687
15.1 DI/DO/AI/AO 687
15.2 Hardware Description 687
15.3 Software: Qt 690
15.4 Hardware: 8-bit ATMEL-Based Embedded Servers 693
15.5 Flowcharts of Qt Client GUI Design for DI/DO/AI/AO
Server Control/Readback Using QNetwork Access Manager 696
15.6 Typical Source Code in a Typical Qt Project 698
15.7 Snapshots of Output 699
References 701
Review Question 701
Answer 701
16. Wireshark for Network Analysis 702
16.1 Introduction 702
16.2 Design of an Embedded Automation Network of HTTP:
Case Study of a Designed System 703
16.3 HTTP Data Drop Checker and an Automatic Device-Health Checker 705
16.4 Switch Configuration and Cabling 709
16.5 Issues and Solutions 710
16.6 HTTP Protocol Analysis Using Wireshark 713
16.7 TCP Analysis 714
16.8 HTTP Analysis 717
16.9 Analyzing Errors in HTTP Using HTTP Error Code Filters 718
References 727
Review Questions 727
Answers 727
17. Networking basics and 8/32-bit Microcontroller-based Ethernet HTTP
Server-Client Interfacing 728
17.1 Introduction to Qt 728
17.2 Basic Concepts: Web Server 728
17.3 Basic Hardware and HTML Coding-Embedded Server & Client 736
17.4 TCP/IP Stack 738
17.5 TCP/IP Implementation in Microprocessors/Microcontrollers 739
˜—Ž—œȳxvii

17.6 Microprocessor Selection for TCP/IP Stack 740


17.7 TCP vs UDP 740
17.8 HTTP 743
17.9 Filters 747
17.10 Switches, Hubs and Wi-Fi Routers 747
17.11 Idea of a Web Client 748
17.12 DHCP Server 750
17.13 Address Resolution Protocol 750
17.14 C Program Practice 752
17.15 Working of the Project Programs of WEB-DAC 753
17.16 Designing 8-bit Ethernet Interfaces Using ATMEL Processors 760
17.17 Building HTTP Server Using ARM Mbed Library 762
References 767
Review Questions 768
Answers 768
18. Controller-Area Network (CAN) 769
18.1 Introduction 769
18.2 CAN Bus Node 771
18.3 Ethernet Challenge 782
18.4 Future of CAN 783
18.5 Summary 784
18.6 CAN Practical 785
References 791
Review Questions 791
Answers 791
19. LabVIEW FPGA Real Time & cRio Interfacing 792
19.1 Introduction 792
19.2 Real-Time Controller 793
19.3 Reconfigurable I/O FPGA 793
19.4 Working with NI 9381 794
19.5 Introduction to LabVIEW 795
19.6 Interfacing cRio with LabVIEW 795
19.7 How to Use LabVIEW in FPGA 796
19.8 LabVIEW FPGA Interface Mode 801
19.9 Compact RIO Scan Mode 801
References 842
Review Questions 842
Answers 842
xviiiȳ˜—Ž—œ

20. Android App Inventor & Interfacing 843


20.1 Introduction 843
20.2 Tutorials on App Inventor 843
References 884
Review Questions 884
Answers 884
21. Internet of Things (IoT) & Interfacing 885
21.1 Internet of Things 885
21.2 Internet of Things Using ARM Mbed Starter Kit 886
21.3 IBM Bluemix 888
21.4 IBM Watson 890
21.5 Node RED 898
21.6 MQTT Protocol 902
21.7 Internet of Things Using Python 903
21.8 Internet of Things Using LabVIEW 913
21.9 Results 915
References 916
Review Questions 916
Answers 917
22. Real-time DSP Filters Design Using the LPC1768 ARM
Cortex-M3 Microcontroller 918
22.1 Introduction 918
22.2 Methodology 932
22.3 Getting Started with Mbed 937
22.4 Input and Output of Digital Data 941
Reference 953
Review Questions 953
Answers 953
Appendix : Learn Python Script for Interfacing 955
Index 1001
RS-232 SERIAL COMMUNICATION
1

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Difference between DTE and DCE
Ȋȱ RS-232 protocol
Ȋȱ Asynchronous vs synchronous communication
Ȋȱ Hardware handshaking
Ȋȱ Software handshaking
Ȋȱ Importance of parity, length, and baud rate
Ȋȱ Voltage levels of TTL UART and RS-232 level shifter
Ȋȱ Interfacing RS-232 to PC
Ȋȱ Interface examples using VB6, Qt, C++, VB.NET, Linux and LabVIEW & Python
Ȋȱ How to build RS-232 firmware using microcontrollers

1.1 INTRODUCTION

In the early 1960s, a standards committee, today known as the Electronic Industries
Association, developed a common interface standard for data communications equipment.
At that time, data communication was thought to mean digital data exchange between
a centrally located mainframe computer and a remote computer terminal, or possibly
between two terminals without a computer involved. These devices were linked by voice
telephone lines and consequently required a modem at each end for signal translation.
Modem stands for ‘modulator demodulator’ which converts binary 1 and 0 to some
defined analog frequencies f1 and f2. While simple in concept, the many opportunities
for data error that occur when transmitting data through an analog channel require a
relatively complex design. It was thought that a standard was needed first to ensure
reliable communication, and second to enable the interconnection of equipment produced
by different manufacturers, thereby fostering the benefits of mass production and
competition. From these ideas, the RS-232 standard serial communication was born.
Serial communication is a common method of transmitting data between a computer
and a peripheral device such as a programmable instrument or even another computer.
Serial communication transmits data one bit at a time, sequentially, over a single
2 Computer Interfacing and Automation

communication line to a receiver. Serial is also the most popular communication protocol
that is used by many devices for instrumentation; numerous USB and GPIB-compatible
devices also come with an RS-232 based port. Serial communication is popular because
most computers have one or more serial ports, so no extra hardware is needed other
than a cable to connect the instrument to the computer or two computers together.
The Electronic Industries Association (EIA) standard RS-232 as of 1969 defines:
Ȋȱ Electrical signal characteristics such as signal voltages, signal timing, the slew rate
of signals, the voltage with stand level and short-circuit behavior and maximum
load capacitance.
Ȋȱ Interface mechanical characteristics, pluggable connectors and pin identification.
Ȋȱ Functions of each circuit in the interface connector.
Ȋȱ Standard subsets of interface circuits for selected telecom applications.
The standard does not define such elements as the character encoding or the framing
of characters, or error detection protocols and transmission bit rate. The character format
and transmission bit rate are set by the serial port hardware which may also contain
circuits to convert the internal logic levels to RS-232 compatible signal levels.
Due to its relative simplicity and low hardware overhead (as compared to parallel
interfacing), serial communications is used extensively in the electronics industry. Today,
the most popular serial communications standard in use is certainly the EIA/TIA–232–F
specification. This standard, which has been developed by the Electronic Industry
Association and the Telecommunications Industry Association (EIA/TIA), is more
popularly referred to simply as ‘RS-232’ where ‘RS’ stands for ‘Recommended Standard’.
In recent years, this suffix has been replaced with ‘EIA/TIA’ to help identify the source
of the standard. The official name of the EIA/TIA–232–F standard is “Interface between
Data Terminal Equipment and Data Circuit–Termination Equipment Employing Serial
Binary Data Interchange.” Although the name may sound intimidating, the standard is
simply concerned with serial data communication between the host systems through
DTE and DCE.
Over the years since this standard was developed, the Electronic Industries Association
published three modifications, the most recent being the EIA232F standard introduced
in 1997. Besides changing the name from RS-232 to EIA232, some signal lines were
renamed, and various new ones were defined, including a shield conductor.

1.2 SERIAL VS PARALLEL DATA TRANSMISSION

Digital data transmission can occur in two basic modes: serial or parallel transmission
as illustrated in Fig. 1.1. The type of transmission mode used depends upon the distance
and the required data rate.
RS-232 Serial Communication 3

Byte Serial communication Byte


b1 b2 b3 b 1 b 2 b3
b8 b7 b6 b5 b4 b3 b2 b1
b4 b5 b6 b4 b5 b6
b b8
7 b b8
7

Parallel communication
b1
b2
Byte b3 Byte
b1 b2 b3 b4 b 1 b2 b3
b4 b5 b6 b4 b5 b6
b5
b b8
7 b b8
7
b6
b7
b7

Figure 1.1 Serial vs parallel transmission

1.2.1 Serial Transmission

Serial communication/transmission is the process of sending data one bit at a time,


sequentially, over a single wire in one direction coordinated by start and stop bits
preceding and following each eight-bit character. Serial transmission, some overhead
time is needed since bits must be assembled and sent as a unit and then disassembled
at the receiver and can be either synchronous or asynchronous.

1.2.2 Parallel Transmission

Figure 1.2 Parallel and serial port


4 Computer Interfacing and Automation

In parallel transmission, multiple bits (usually 8 bits or a byte/character) are sent


simultaneously on different channels (wires, frequency channels) within the same cable,
or radio path, and synchronized to a clock. Parallel devices have a wider data bus than
serial devices and can, therefore, transfer data in words of one or more bytes at a time.
The timing for parallel transmission is provided by a constant clocking signal sent over
a separate wire within the parallel cable. Thus, parallel transmission is considered
synchronous (see Fig. 1.2).

1.2.3 Serial vs Parallel Data Transmission

The serial port is harder to “interface” than the parallel port. In most cases, any device
you connect to the serial port will need the serial transmission converted back to parallel
so that it can be used. Still it has many advantages.
Benefits of using serial data transfer rather than parallel?
Ȋȱ Serial transmission requires fewer interconnecting cables and hence occupies less
space.
Ȋȱ Serial cables can be longer than parallel cables. The serial port transmits a ‘1’ as
–3 to –25 V, and a ‘0’ as +3 to +25 V whereas a parallel port transmits a ‘0’ as 0 V
and a 5 V. There the serial port can have a maximum swing of 50 V compared to
the parallel port which has a maximum swing of 5 V. Therefore, cable loss is not
going to be as much of a problem for serial cables as they are for parallel.
Ȋȱ You don't need as many wires as parallel transmission. If your device needs to be
mounted a far distance away from the computer, then 3 core cable (Null Modem
Configuration) is going to be a lot cheaper than running 19 or 25 core cable.
However, you must take into account the cost of the interfacing at each end.
Ȋȱ Crosstalk is minimized in serial as there are fewer wires to talk on one another.
Ȋȱ Many ICs and peripheral devices have serial interfaces (see Fig. 1.3).

Figure 1.3 Serial data as displayed on a CRO


RS-232 Serial Communication 5

1.3 RC PULSE DISTORTION IN DIGITAL TRANSMISSION


Step-voltage input

In digital, pulses of ‘1’ and ‘0’ when transmitted over long distances cable capacitance
and resistance distort the output. For the step input, the output voltage Vo, which is
also voltage across capacitor C, rises exponentially towards the final value of V with a
time constant RC. The output voltage Vo is given by: (see Fig. 1.4)
Vo = V (1 – e-t/RC)

Figure 1.4 (a) Step input; (b) RC low-pass filter circuit; (c) output waves

Now let us consider, the time period of the circuit T may be long when tp < 0.1T or
short when tp> 10T or medium when T lies between the extremes, i.e., 10T > tp > 0.1T.
The output waveforms are shown in Fig. 1.5. This clearly indicates that RC distorts the
data and, therefore, causes transmission error.

Figure 1.5 (a) Input waveform; (b) RC low-pass filter circuit


6 Computer Interfacing and Automation

1.4 UART
1.4.1 What is UART?

UART, Universal Asynchronous Receiver/Transmitter, is a feature of microcontroller


useful for communicating serial data (text, numbers, etc.) to your PC. The device changes
incoming parallel information (within the microcontroller/PC) to serial data which can
be sent on a communication line. The UART takes bytes of data and transmits the
individual bits sequentially. At the destination, a second UART reassembles the bits into
complete bytes (see Fig. 1.6).
In addition to the basic job of converting data from parallel to serial for transmission
and from serial to parallel on reception, the UART will usually provide additional circuits
for signals that can be used to indicate the state of the transmission media, and to
regulate the flow of data in the event that the remote device is not prepared to accept
more data. For example, when the device connected to the UART is a modem, the
modem may report the presence of a carrier on the phone line while the computer may
be able to instruct the modem to reset itself or not to take calls by raising or lowering
one more of these extra signals. The function of each of these additional signals is defined
in the EIA RS-232-C standard (see Fig. 1.7 and Fig. 1.8).

Figure 1.6 Block diagram of UART

Figure 1.7 Serial data transmission


RS-232 Serial Communication 7

Peripheral bus
interface
Peripheral Rx block
bus TXD
Control RXD
CTS
Power
RxFIFO saving RTS

DCE/DTE Inter.
Interrupt DSR
Interrupts
& DMA RI
DMA Req. Requests
Rx block DCD

Control DTR
Peripheral Clock
clock gating
Power
RxFIFO saving
Clock
Module
gating BRM
clock ref_clk brm_clk
& driver

Figure 1.8 Block diagram of UART

1.4.2 Transmitting and Receiving Serial Data

UART takes bytes of data and transmits the individual bits in a sequential fashion. At
the destination, a second UART reassembles the bits into complete bytes. Each UART
contains a shift register, which is the fundamental method of conversion between serial
and parallel forms. Serial transmission of digital information (bits) through a single wire
or another medium is less costly than parallel transmission through multiple wires.
The UART usually does not directly generate or receive the external signals used
between different items of equipment. Separate interface devices are used to convert
the logic level signals of the UART to and from the external signaling levels. External
signals may be of many different forms. Examples of standards for voltage signaling
are RS-232, RS-422, and RS-485 from the EIA. Historically, current (in current loops)
was used in telegraph circuits. Some signaling schemes do not use electrical wires.
Examples are optical fibers, IRDA (infrared), and (wireless) Blue tooth in its Serial Port
Profile (SPP). Some signaling schemes use modulation of a carrier signal (with or without
wires). Examples are modulation of audio signals with phone line modems, RF
modulation with data radios, and the DC-LIN for power line communication.
Communication may be simplex (in one direction only, with no provision for the
receiving device to send information back to the transmitting device), full-duplex (both
devices send and receive at the same time) or half-duplex (devices take turns transmitting
and receiving).
8 Computer Interfacing and Automation

1.4.3 Features

The UART includes the following features:


Ȋȱ High-speed TIA/EIA-232-F compatible, up to 4.0 Mbit/s
Ȋȱ Serial IR interface low-speed, IrDA-compatible (up to 115.2 Kbit/s)
Ȋȱ 7 or 8 data bits
Ȋȱ 1 or 2 stop bits
Ȋȱ Programmable parity (even, odd, and no parity)
Ȋȱ Hardware flow control support for request to send (RTS) and clear to send (CTS)
signals
Ȋȱ Edge-selectable RTS and edge-detect interrupts
Ȋȱ Status flags for various flow control and FIFO states
Ȋȱ Voting logic for improved noise immunity (16× oversampling)
Ȋȱ Transmitter FIFO empties interrupt suppression

1.5 RS-232

RS-232C is the most common standard that is based on voltage change levels. The voltage
level between +3 V to +15 V is logic false, whereas logic true is between –3 V to –15 V.
The cable length is limited to just 50 feet to reduce the effects of electrical noise. It
formally defines the signals connecting between a DTE (data terminal equipment) such
as a computer terminal, and a DCE (data circuit-terminating equipment, originally
defined as data communication equipment), such as a modem. The RS-232 standard is
commonly used in computer serial ports (see Fig. 1.9).

Figure 1.9 A DB-25 connector as described in the RS-232 standard

RS-232 is the most widely used serial standard. Many laptop computers incorporate
a serial interface, and it was also used on many printers.
Ȋȱ Cabling – single ended
Ȋȱ Number of devices - one transmit and one receive
Ȋȱ Communication mode - full-duplex
Ȋȱ Maximum distance - 50 feet at 19.2 kbps
Ȋȱ Maximum data rate - 19.2 kbps at 50 feet
Ȋȱ Signaling mode - unbalanced
Ȋȱ Mark (1) – 5 to – 15 V
RS-232 Serial Communication 9

Ȋȱ Space (0) - + 5 to + 15 V
Ȋȱ Output current capability - 500 mA (see Fig. 1.10)
An RS-232 serial port was once a standard feature of a personal computer used for
connections to modems, printers, mice, data storage, uninterruptible power supplies,
and other peripheral devices. However, RS-232 is hampered by low transmission speed,
large voltage swing, and large standard connectors. In modern personal computers, USB
has replaced RS-232 from most of its peripheral interface roles. Many computers do not
come equipped with RS-232 ports and must use either an external USB-to-RS-232
converter or an internal expansion card with one or more serial ports to connect to
RS-232 peripherals. RS-232 devices are widely used, especially in industrial machines,
networking, and scientific instruments.
The RS-232 standard also limits the maximum slew rate at the driver output. This
limitation was included to help reduce the likelihood of crosstalk between adjacent
signals. The slower the rise and fall time, the smaller the chance of crosstalk. With this
in mind, the maximum slew rate allowed is 30 V/μs. Additionally, a maximum data
rate of 20 kbps has been defined by the standard. Again, with the purpose of reducing
the crosstalk.

Figure 1.10 RS-232 logic level specifications

The impedance of the interface between the driver and receiver has also been defined.
‘Žȱ •˜Šȱ œŽŽ—ȱ ‹¢ȱ ‘Žȱ ›’ŸŽ›ȱ ’œȱ œ™ŽŒ’’Žȱ ˜ȱ ‹Žȱ řȱ ”̛ȱ ˜ȱ ŝȱ ”̛ǯȱ ˜›ȱ ‘Žȱ ˜›’’—Š•ȱ ȬŘřŘȱ
standard, the cable between the driver and the receiver was also specified to be a
maximum of 15 meters in length. This part of the standard was changed in revision ‘D’
(EIA/TIA–232–D). Instead of specifying the maximum length of the cable, a maximum
capacitive load of 2500 pF was specified which is clearly a more adequate specification.
The maximum cable length is determined by the capacitance per unit length of the cable
which is provided in the cable specifications.
10 Computer Interfacing and Automation

1.5.1 Functional Characteristics

Since RS-232 is a ‘complete’ standard, it includes more than just specifications on electrical
characteristics. The second aspect of the operation that is covered by the standard
concerns the functional characteristics of the interface. This essentially means that RS-232
has defined the function of the different signals that are used in the interface. These
signals are divided into four different categories: common, data, control, and timing.
Table 1.1 illustrates the signals that are defined by the RS-232 standard. As can be seen
from the table there is an overwhelming number of signals defined by the standard.
The standard provides an abundance of control signals and supports a primary and
secondary communications channel. Fortunately, few applications, if any, require all of
these defined signals. For example, only eight signals are used for a typical modem.
Some simple applications may require only four signals (two for data and two for
handshaking) while others may require only data signals with no handshaking. Examples
of how the RS-232 standard is used in some ‘real-world’ applications are discussed later
in this chapter.

1.5.2 Mechanical Interface Characteristics

The third area covered by RS-232 concerns the mechanical interface. In particular, RS-232
specifies a 25-pin connector. This is the minimum connector size that can accommodate
all of the signals defined in the functional portion of the standard. The pin assignment
for this connector is shown in Fig. 1.12. The connector for DCE equipment is male for
the connector housing and female for the connection pins. Likewise, the DTE connector
is a female housing with male connection pins. Although RS-232 specifies a 25–position
connector, it should be noted that often this connector is not used. This is because most
applications do not require all of the defined signals and, therefore, a 25–pin connector
is larger than necessary. This being the case, it is very common for other connector types
to be used. Perhaps the most popular is the 9-position DB9S connector which is also
illustrated in Fig. 1.11. This connector provides the means to transmit and receive the
necessary signals for modem applications.

Figure 1.11 An RS-232 cable


RS-232 Serial Communication 11

Cable length

The standard does not define a maximum cable length but instead defines the maximum
capacitance that a compliant drive circuit must tolerate. A widely used rule of thumb
indicates that cables more than 50 feet (15 m) long will have too much capacitance unless
special cables are used. By using low-capacitance cables, full speed communication can
be maintained over larger distances up to about 1000 feet (300 m). For longer distances,
other signal standards are better suited to maintain high speed.

Table 1.1 Circuit names, direction and type

Circuit Circuit Name* Circuit Circuit


mnemonic Direction Type
AB Signal Common – Common
BA Transmitted Data (TD) To DCE Data
BB Received Data (RD) From DCE
CA Request to Send (RTS) To DCE Control
CB Clear to Send CTS) From DCE
CC CDE Ready DSR) From DCE
CD DTE Ready (DTR) To DCE
CE Ring Indicator (RI) From DCE
CF Received Line Signal Detector** (DCD) From DCE
CG Signal Quality Detector From DCE
CH Data Signal Rate Detector from DTE To DCE
CI Data Signal Detector from DCE From DCE
CJ Ready for Receiving To DCE
RL Remote Loopback To Dce
LL Local Loopback To DCE
TM Test Mode From DCE
DA Transmitter Signal Element Timing from DTE To DCE
DB Transmitter Signal Element Timing from DCE From DCE Timing
DD Receiver Signal Element Timing From DCE From DCE
SBA Secondary Transmitted Data To DCE Data
SBB Secondary Received Data From DCE
SCA Secondary Request to Send To DCE Control
SCB Secondary Clear to Send From DCE
SCF Secondary Received Line Signal Detector From DCE

Signals with abbreviations in parentheses are the eight most commonly used signals.
**This signal is more commonly referred to as data carrier detect (DCD)
12 Computer Interfacing and Automation

Figure 1.12 RS-232 with 9 pins and 25 pins

1.5.3 Limitations of the RS-232 Standard

Because RS-232 is used beyond the original purpose of interconnecting a terminal with
a modem, successor standards have been developed to address the limitations. Issues
with the RS-232 standard include:
Ȋȱ The large voltage swings and the requirement of positive and negative supplies
increase the power consumption of the interface and complicate power supply
design. The voltage swing requirement also limits the upper speed of a compatible
interface.
Ȋȱ Single-ended signaling referred to a common signal ground limits the noise
immunity and transmission distance.
Ȋȱ It is a point to point communication. The multi-drop connection among more than
two devices is not defined. While multi-drop ‘work-rounds’ have been devised,
they have limitations in speed and compatibility.
Ȋȱ Asymmetrical definitions of the two ends of the link make the assignment of the
role of a newly developed device problematic; the designer must decide on either
a DTE-like or DCE-like interface and which connector pin assignments to use.
Ȋȱ The handshaking and control lines of the interface are intended for the setup and
take down of a dial-up communication circuit; in particular, the use of handshake
lines for flow control is not reliably implemented in many devices.
RS-232 Serial Communication 13

Ȋȱ No method is specified for sending power to a device. While a small amount of


current can be extracted from the DTR and RTS lines, this is only suitable for low
power devices such as mice.
Ȋȱ The 25-way connector recommended in the standard is large compared to current
practice.
Ȋȱ The standard does not address the possibility of connecting a DTE directly to a
DTE, or a DCE to a DCE.

1.6 OTHER SERIAL STANDARDS

The distance limitation of 50 feet between the transmitter and the receiver in RS-232 is
overcome in RS-422a, RS-423a, and RS-485 standards. The RS-422a cable uses a 20 mA
current loop instead of voltage levels. This makes the systems more immune to electrical
noise so that the cable can be up to 3000 feet long. The RS-423a standard uses a differential
voltage level across two lines, also making the system more immune to electrical noise,
thus allowing longer cables (see Fig. 1.13).

Figure 1.13 Various serial standards, RS-232c, RS-422a, and RS-423a


14 Computer Interfacing and Automation

RS-422 Summary

This standard gives a much higher data rate than RS-232, but it uses differential
transmission techniques. Many RS-422 devices are compatible with RS-232 (see Figs.
1.14 and 1.15).
Ȋȱ Cabling - differential
Ȋȱ Number of devices - five transmitters and ten receivers
Ȋȱ Communication mode - full-duplex / half-duplex
Ȋȱ Maximum distance - 4000 feet at 100 kbps
Ȋȱ Maximum data rate - 10 mbps at 50 feet
Ȋȱ Signaling mode - balanced
Ȋȱ Mark (1) – 2 V to 6 V max. (B > A)
Ȋȱ Space (0) – 2 V to 6 V max. (A > B)
Ȋȱ Output current capability – 150 mA

Figure 1.14 RS-422/485 serial standard and pin configuration

RS-485 Summary

Ȋȱ RS-485 standard allows high-speed data transmission along with multiple


transmitters and receivers, and this makes it able to be incorporated into a network
solution.
Ȋȱ Cabling - differential
Ȋȱ Number of devices - 32 transmitters and 32 receivers
Ȋȱ Communication mode - half-duplex
Ȋȱ Maximum distance - 4000 feet at 100 kbps
Ȋȱ Maximum data rate - 10 mbps at 50 feet
Ȋȱ Signaling - balanced
Ȋȱ Mark (1) – 1.5 V to 5 V max. (B > A)
Ȋȱ Space (0) – 1.5 V to 5 V max. (A > B)
Ȋȱ Output current capability – 250 mA
RS-232 Serial Communication 15

Figure 1.15 Voltages of various serial standards

Each of these standards meets a different requirement. RS-232 still being widely used
despite the fact that it has been in use for over 40 years. However, the other standards
that have been introduced recently provide higher levels of performance that are useful
for many applications.

Table 1.2 Specifications of various serial standards


Specifications RS-232 RS-423 RS-422 RS-485
Mode of Operation Single-Ended Single-Ended Differential Differential
Allowed no. of Tx and Rx 1 Tx, 1 Rs 1 Tx. 10 Rx 1 Tx, 10 Rx 32 Tx, 32 Rx
Maximum cable length 50 Feet 4000 Feet 4000 Feet 4000 Feet
Contd.
16 Computer Interfacing and Automation

Maximum data rate 20 kbps 100 kbps / 10 100 kbps / 10 100 kbps / 10
Mbps Mbps Mbps
Minimum driver output range ±5 V to ±15 V ±3.6 V ±2 V ±1.5 V
Maximum driver output range ±25 V ±6 V ±6 V ±6 V
Tx load impedance (ohms) 3 k to 7 k dȹŚśŖ 100 54
Rx input sensitivity ±3 V ±200 mV ±200 mV ±200 mV
Rx input voltage range ±15 V ±12 V ±7 V –7 V to 12 V
Maximum Rx input resistance 3 k to 7 k 4 k min 4 k min d12 k

1.7 DTE AND DCE

There are usually four basic functional units involved in the communication of data: a
DTE and DCE on both ends of the transmission. The DTE generates the data and passes
them to a DCE. The DCE converts the signal to a format appropriate to the transmission
medium. When the signal arrives at the receiving end, this process is reversed.
Data terminal equipment (DTE) includes any unit that functions either as a source
of or as a destination for binary digital data. It can be a terminal, microcomputer, printer,
fax machine, etc.
Data circuit-terminating equipment (DCE) includes any functional unit that transmits
or receives data in the form of an analog or digital signal through a network. Commonly
DCEs include modems.
Many standards are developed to define the connection between a DTE and a DCE,
which provides a model for the mechanical, electrical, and functional characteristics of
the connection.
The most active organizations defining the interface standard are:
1. Electronic Industries Association (EIA)
2. International Telecommunication Union-Telecommunication Standards Committee
(ITU-T)
If the full EIA232 standard is implemented as defined, the equipment at the far end
of the connection is named the DTE device (usually a computer or terminal), has a male
DB25 connector, and utilizes 22 of the 25 available pins for signals or ground. Equipment
at the near end of the connection (the telephone line interface) is named the DCE device
(usually a modem), has a female DB25 connector, and utilizes the same 22 available pins
for signals and ground. The cable linking DTE and DCE devices is a parallel straight-
through cable with no cross-overs or self-connects in the connector hoods. If all the
devices exactly follow this standard, all cables would be identical, and there would be
no chance that an incorrectly wired cable could be used (see Figs. 1.16 and 1.17).
RS-232 Serial Communication 17

Figure 1.16 DTE and DCE communication block diagram

Figure 1.17 DB 9-pin and 25-pin female configuration


18 Computer Interfacing and Automation

Figure 1.18 shows the orientation and connector types for DTE and DCE devices:
Ȋȱ The EIA232 defines the interfaces as a 25-wire cable with a male and a female
DB-25 pin connection attached to either end. The length of the cable may not
exceed 15 meters.
Ȋȱ A DB-25 connector is a plug with 25 pins, each of which is attached to a single
wire with a specific function. However, fewer are used in current practice. Another
implementation of EIA232 uses a 9-wire cable with a male and a female DB-9 pin
connector attached to either end (see Fig. 1.18).
Ȋȱ 9-pin connector is more commonly found in PCs, but it covers signals for
asynchronous serial communication only.
Ȋȱ Male connector is used on DTE, and female connector is used on DCE.

Figure 1.18 DB 9-pin and 25-pin male configuration


RS-232 Serial Communication 19

1.8 DTE TO DCE COMMUNICATION

Many of the 22 signal lines in the EIA232 standard pertain to connections where the
DCE device is a modem and then are used only when the software protocol employs
them. For any DCE device that is not a modem, or when two DTE devices are directly
linked, far fewer signal lines are necessary.
You may have noticed in the pin out drawings that there is a secondary channel
which includes a duplicate set of flow-control signals. This secondary channel provides
for management of the remote modem, enabling baud rates to be changed on the fly,
retransmission to be requested if a parity error is detected, and other control functions.
This secondary channel, when used, is typically set to operate at a very low baud rate
in comparison with the primary channel to ensure reliability in the control path. In
addition, it may operate either a simplex, half-duplex, or full-duplex channel, depending
on the capabilities of the modem.
Transmitter and receiver timing signals (pins 15, 17 and 24) are used only for a
synchronous transmission protocol. For the standard asynchronous 8-bit protocol,
external timing signals are unnecessary.
The connector for DTE device is output pins that match up with the input pins on
DCE device, i.e., a straight through cable is used to connect the two devices. All signals
on one side are connected to the corresponding signals on the other side on a one-to-one
basis. The connection between DTE and DCE is same as with DB9 pin connector.

Table 1.3 Straight through connection (DB9) pin configuration

(DTE) (DCE)
1 DCD ------- DCD 1
2 RxD ------- TxD 2
3 TxD ------- RxD 3
4 DTR ------- DSR 4
5 GND ------- GND 5
6 DSR ------- DTR 6
7 RTS ------- CTS 7
8 CTS ------- RTS 8
9 RI ------- RI 9

The steps involved in transmitting and receiving the data across RS-232 interface are
given below.
1. Transmitting data (DTE to DCE)
(a) Assert DTR and RTS
(b) Wait for DSR
20 Computer Interfacing and Automation

(c) Wait for CTS


(d) Transmit the data
2. Receiving the data (DCE to DTE)
(a) Assert DTR
(b) Wait for DSR
(c) Receive the data
Connected to 25-pin DTE Connect to 25-pin DCE
(computer) (modem)

1.8.1 Null Modem Cables and Null Modem Adaptors


Null modem cable (no handshaking)
Connected to 25-pin DTE Connected to 25-pin DTE
(Computer) (Computer)
If you connect two DTE devices (or two DCE devices) using a straight RS-232 cable,
then the transmit line on each device will be connected to the transmit line on the other
device and the receive lines will likewise be connected to each other. A null modem
cable or null modem adapter simply crosses, receives and transmits the lines, so that
‘transmit’ on one end is connected to ‘receive’ at the other end and vice versa. In addition
to transmit and receive, DTR & DSR, as well as RTS & CTS are also crossed in a null
modem connection (see Figs. 1.18 to 1.22).

Figure 1.19 Straight connection : DTE to DCE 25-pin configuration


RS-232 Serial Communication 21

Socket L Socket R
DB25 female DB25 female
SH SH
1 1
2 2
3 3
4 4
5 5
6 6
7 7
20 20
8 8

11 11
12 12

Figure 1.20 Null modem cable: DTE to DTE-25-pin configuration

Figure 1.21 Female and male DTE to DCE connectors


22 Computer Interfacing and Automation

Figure 1.22 Female to female DTE to DTE connectors

1.9 RS-232 BIT FORMAT

True

False

Before Start Data Parity Stop Idle

Figure 1.23 RS-232 bit format

Each data character by character is divided into serial as shown above. The following
sample gives Hex0x8A. Each bit width depends on the speed (i.e.baud), and transmission
begins with a Start, then 8 or 7 bits (depending on the width), Parity and Stop (see Fig.
1.24).

Figure 1.24 RS-232 standard signal

For example, a 9600 baud transmission of the data in Fig. 1.23 would transfer up to
9600/(1+8+1+2) = 800 bytes per second (Start, data, parity, 2 stop bit).
RS-232 Serial Communication 23

1.10 HANDSHAKING (FLOW CONTROL)

Handshaking refers to methods with which a receiving device can control the flow of
data from a transmitting device. Sometimes a printer cannot print characters as fast as
it receives them from a computer. The printer must use handshaking to tell the computer
to suspend transmission. Handshaking is also useful when the printer runs out of paper
or when a computer sends data to another computer, and the receiving computer cannot
process the characters as fast as they are being transmitted (see Fig. 1.25).
When you know that a receiving device can process received characters faster than
the transmission rate, you can dispense with handshaking.
1. It allows the computer to stop your instrument from sending data when the PC
is not ready for it.
2. It allows your instrument to prevent the PC from sending data when the
instrument is not ready for it.
Types of handshaking
Ȋȱ Hardware handshaking
Ȋȱ Software handshaking

1.10.1 Hardware Handshaking/Hardware Flow Control

Hardware handshaking is the use of dedicated handshaking circuits to control the


transmission of data. The main problem is that an extra investment is needed. Additional
lines are necessary for the communication cable to carry the handshaking information.

Figure 1.25 DTE to DCE hardware handshaking

In the case of a PC (DTE) communicating to a modem (DCE), extra pins called DSR
and DTR lines are used to control the flow of data. In the computer, the CTS and RTS
lines are connected. These lines are all used for handshaking, to control the flow of data
from the sender to the receiver as shown in Fig. 1.26.
24 Computer Interfacing and Automation

Figure 1.26 Block diagram of handshaking, straight cable and null modem cable

Ȋȱ DSR/DTR - (data set ready, data terminal ready) these handshaking lines indicate
when the remote machine is ready to receive data.
First, the computer sets its RTS line to signal the device that some information is
present. The device checks if there is room to receive the information and if so, it sets
the CTS line to start the transfer. When using a null modem connection, this is somewhat
different. There are two ways to handle this type of handshaking.
One is where the RTS of each side is connected with the CTS side of the other. In
that way, the communication protocol differs somewhat from the original one. The RTS
output of computer A signals computer B that A is capable of receiving information,
rather than a request for sending information as in the original configuration. This type
of communication can be performed with a null modem cable for full handshaking.
Although using this cable is not completely compatible with the original way hardware
flow control was designed, if the software is properly designed edit can achieve the
highest possible speed because no overhead is present for requesting on the RTS line
and answering on the CTS line.
In the second situation of null modem communication with hardware flow control,
the software side looks quite similar to the original use of the handshaking lines. The
CTS and RTS lines of one device are connected directly to each other. This means that
the request to send query answers itself. As soon as the RTS output is set, the CTS input
will detect a high logical value indicating that sending of information is allowed. This
RS-232 Serial Communication 25

implies that information will always be sent as soon as sending is requested by a device
if no further checking is present. To prevent this from happening, two other pins on
the connector are used, the dataset ready DSR and the data-terminal ready DTR. These
two lines indicate if the device attached is working properly and willing to accept data.
When these lines are cross-connected (as in most null modem cables) flow control can
be performed using these lines. A DTR output is set if that computer accepts incoming
characters (see Fig. 1.27).

Figure 1.27 Hardware handshaking flowchart for a sending device


26 Computer Interfacing and Automation

Figure 1.28 Signals

Signal functions in detail: Primary communications channel (see Fig. 1.28).

Pin 2 – Transmitted Data (TxD): This signal is active when data is transmitted from
the DTE device to the DCE device. When no data is transmitted, the signal is held in
the mark condition (logic '1', negative voltage).
NOTE: Pin 2 on the DCE device is commonly labeled ‘Received Data’, although by
the EIA232 standard it should still be called ‘Transmitted Data’ because the data is
thought to be destined for a remote DTE device.
Pin 3 – Received Data (RxD): This signal is active when the DTE device receives data
from the DCE device. When no data is transmitted, the signal is held in the mark
condition (logic '1', negative voltage).
NOTE: Pin 3 on the DCE device is commonly labeled ‘Transmitted Data’, although
by the EIA232 standard it should still be called ‘Received Data’ because the data is
thought to arrive from a remote DTE device.
Pin 4 – Request to Send (RTS): This signal is asserted (logic ‘0’, positive voltage) to
prepare the DCE device for accepting transmitted data from the DTE device. Such
preparation might include enabling the receive circuits, or setting up the channel direction
in half-duplex applications. When the DCE is ready, it acknowledges by asserting Clear
to Send.
NOTE: Pin 4 on the DCE device is commonly labeled ‘Clear to Send’, although by
the EIA232 standard it should still be called ‘Request to Send’ because the request is
thought to be destined for a remote DTE device.
Pin 5 – Clear to Send (CTS): This signal is asserted (logic ‘0’, positive voltage) by
the DCE device to inform the DTE device that transmission may begin. RTS and CTS
are commonly used as handshaking signals to moderate the flow of data into the DCE
device.
RS-232 Serial Communication 27

NOTE: Pin 5 on the DCE device is commonly labeled ‘Request to Send’, although by
the EIA232 standard it should still be called ‘Clear to Send’ because the signal is thought
to originate from a remote DTE device.

Secondary communication channel

These signals are equivalent to the corresponding signals in the primary communications
channel. The baud rate, however, is typically much slower in the secondary channel for
increased reliability.
Pin 14 – Secondary Transmitted Data (STxD)
Pin 16 – Secondary Received Data (SRxD)
Pin 19 – Secondary Request to Send (SRTS)
Pin 13 – Secondary Clear to Send (SCTS)

Modem status and control signals

Pin 6 – DCE Ready (DSR) When originating from a modem, this signal is asserted
(logic ‘0’, positive voltage) when the following three conditions are all satisfied:
1. The modem is connected to an active telephone line that is ‘off-hook’.
2. The modem is in data mode, not voice or dialing mode.
3. The modem has completed dialing or call setup functions and is generating an
answer tone.
If the line goes ‘off-hook’, a fault condition is detected, or a voice connection is
established, the DCE Ready signal is reasserted (logic ‘1’, negative voltage).
IMPORTANT: If DCE Ready originates from a device other than a modem, it may
be asserted to indicate that the device is turned on and ready to function, or it may not
be used at all. If unused, DCE Ready should be permanently asserted (logic ‘0’, positive
voltage) within the DCE device or by the use of a self-connect jumper in the cable.
Alternatively, the DTE device may be programmed to ignore this signal.
Pin 20 – DTE Ready (DTR): This signal is asserted (logic ‘0’, positive voltage) by the
DTE device when it wishes to open a communications channel. If the DCE device is a
modem, the assertion of DTE Ready prepares the modem to be connected to the telephone
circuit, and, once connected, maintains the connection. When DTE Ready is reasserted
(logic ‘1’, negative voltage), the modem is switched to ‘on-hook’ to terminate the
connection.
IMPORTANT: If the DCE device is not a modem, it may require DTE Ready to be
asserted before the device can be used, or it may ignore DTE Ready altogether. If the
DCE device (for example, a printer) is not responding, confirm that DTE Ready is
asserted before you search for other explanations.
Pin 8 – Received Line Signal Detector (CD): Also called carrier detect, this signal is
relevant when the DCE device is a modem. It is asserted (logic ‘0’, positive voltage) by
the modem when the telephone line is ‘off-hook’, a connection has been established,
28 Computer Interfacing and Automation

and an answer tone is being received from the remote modem. The signal is reasserted
when no answer tone is received, or when the answer tone is of inadequate quality to
meet the local modem’s requirements (perhaps due to a noisy channel).
Pin 12 – Secondary Received Line Signal Detector (SCD): This signal is equivalent
to the Received Line Signal Detector (Pin 8) but refers to the secondary channel.
Pin 22 – Ring Indicator (RI): This signal is relevant when the DCE device is a modem
and is asserted (logic ‘0’, positive voltage) when a ringing signal is being received from
the telephone line. The assertion time of this signal will approximately equal the
duration of the ring signal, and it will be reasserted between rings or when no ringing
is present.
Pin 23 – Data Signal Rate Selector: This signal may originate either in the DTE or
DCE devices (but not both), and is used to select one of the two prearranged baud rates.
The asserted condition (logic ‘0’, positive voltage) selects the higher baud rate.

Transmitter and receiver timing signals

Pin 15 – Transmitter signal element Timing/Transmitter clock (TC): This signal is


relevant only when the DCE device is a modem and is operated with a synchronous
protocol. The modem generates this clock signal to control exactly the rate at which
data is sent on Transmitted Data (Pin 2) from the DTE device to the DCE device. The
logic ‘1’ to logic ‘0’ (negative voltage to positive voltage) transition on this line causes
a corresponding transition to the next data element on the transmitted data line. The
modem generates this signal continuously, except when it is performing internal
diagnostic functions.
Pin 17 – Receiver Signal Element Timing/Receiver clock (RC): This signal is similar
to TC described above, except that it provides timing information for the DTE receiver.
PIN 24 – Transmitter signal element Timing / External Transmitter Clock (ETC):
The DTE device provides timing signals for the modem. This signal is used only when
TC and RC (Pins 15 and 17) are not in use. The logic ‘1’ to logic ‘0’ transition (negative
voltage to positive voltage) indicates the time center of the data element. Timing
signals will be provided whenever the DTE is turned on, regardless of other signal
conditions.

Channel test signals

Pin 18 – Local Loop back (LL): This signal is generated by the DTE device and used
to place the modem into a test state. When local loop back is asserted (logic’0’, positive
voltage), the modem redirects its modulated output signal, which is normally fed into
the telephone line, back into its receive circuitry. This enables data generated by the
DTE to be echoed back through the local modem to check the condition of modem
circuitry. The modem asserts its test modem signal on Pin 25 to acknowledge that it has
placed in a local loop back condition.
RS-232 Serial Communication 29

Pin 21 – Remote Loop back (RL): This signal is generated by DTE device and used
to place the modem into a test state. When Remote Local back is asserted (logic ‘0’,
positive voltage), the remote modem redirects its received data back to its transmitted
data input, there by demodulating the received data and return to its source. When the
DTE initiates such a test, transmitted data is passed through the local modem, the
telephone line, the remote modem, and back to exercise the channel and confirm its
integrity. The remote modem signals the local modem to assert test mode on Pin 25
when the remote loop back test is under way.
Pin 25 – Test Mode(TM): This signal is relevant only when DCE device is a modem.
When asserted (logic ‘0’, positive voltage), it indicates that the modem is in local loop
back or remote loop back condition. Other internal self-testing conditions may also cause
the test mode to be asserted, and depend on the modem and the network to which it
is attached.

Signal ground and shield

Pin 7, Pin 1, and the shell are included in this category. Cables provide separate paths
for each, but the internal wiring often connects Pin 1 and the cable shell/shield to signal
ground on Pin 7.
Pin 7: Ground all signals are referenced to a common ground, as defined by the
voltage on Pin 7. This conductor may or may not be connected to protective ground
inside the DCE device. The existence of a defined ground potential within the cable
makes the EIA232 standard different from a balanced differential voltage standard, such
as EIA530, which provides far greater noise immunity.

1.10.2 Software Handshaking

Software handshaking is when handshaking signals are sent as data along the data wires
(TXD and RXD, lines 2 and 3), instead of along dedicated handshaking circuits, as in
hardware handshaking. This method is generally used where two computers are
communicating (either directly or via a modem) and when two-way communication is
possible.
Several standard protocols have been established to govern software handshaking.
The most common protocol is XON/XOFF.

XON/XOFF

Under the XON/XOFF protocol, the receiving device sends ASCII character DC3 (19
decimal, 13 hex) to the transmitting device when it wants to stop the transmitting device
from sending characters. It sends ASCII character DC1 (17 decimal, 11 hex) when it
wants the transmission to resume.
In usual practice, a buffer will be implemented. The DC3 character will be sent to the
transmitter when the buffer is almost full; the DC1 character will be sent when the buffer
is nearly empty (see Fig. 1.29).
30 Computer Interfacing and Automation

Start

Set ON/OFF
ag = ON

XOFF Yes Set ON/OFF


received? ag = OFF

XON Yes Set ON/OFF


received? ag = OFF

IS
Yes ON/OFF
ag off?

Yes

Is there
No
a character
to send?

Send the
character

No Was it
end-of-le? End

Figure 1.29 XON/XOFF flowchart for a sending device


RS-232 Serial Communication 31

1.11 RS-232 C PROTOCOL

The RS-232 protocol is a serial data communication between a transmitter and a receiver.
It is mostly used in systems where data synchronization, i.e., time specification of data
is not important. It has advantages over parallel data communication. Parallel data
communication needs a bunch of wire for data communication in this type which limits
the length of the cable and speed of data communication as well as noise introduction
due to crosstalk between the bunch of wires during data communication. Generally,
RS-232 is used for data transfer between PCs and serial receivers such as a modem,
printer, etc.
As information is sent in a bit-by-bit way in RS-232 cable data has to be broken in
such a way to transfer data at the transmitter terminal. Here only three cables are used
for data transmission; one is for transfer of data from the transmitter to the receiver,
one to send back data receiving information by the receiver to the transmitter and one
as aground line. As it is a serial communication between the transmitter and the receiver,
there is a chance of false interpretation of data by the receiver. So this method has its
own way of transmitting data between the transmitter and the receiver which is called
protocol. RS-232 protocol details are as follows.

1.11.1 Baud Rate

Baud is a measurement of transmission speed in asynchronous communication. The


computer, any adaptors, and the UART must all agree on a single speed of information,
i.e., ‘bits per second’.
For example, your robot would pass sensor data to your laptop at 38400 bps and
your laptop would listen for this stream of 1s and 0s expecting a new bit every 1/38400
bps = 26 μs (0.000026 s). As long as the robot outputs bits at the predetermined speed,
your laptop can understand it.
Remember always to configure all your devices to the same baud rate for communication
to work!

1.11.2 Start Bits, Data Bits, Parity, Stop Bits, Flow Control
Start bit

In RS-232 protocol, the start bit is the first bit which is transmitted to the receiver. RS-232
is a serial communication, so there arises to inform the receiver about when to start or
interpret the data which is sent by the transmitter. As soon as the start bit arrives, the
receiver understands that the next bit onwards the data is started.

Data bit

As soon as the arrival of the start bit takes place, the receiver arranges the bits to the
incoming data and interprets the data one by one.
32 Computer Interfacing and Automation

Error detection

One way of detecting errors is already discussed. It is the frame detection mechanism
which is used to test if the incoming bits were properly surrounded by a start and stop
bit pair. For further error checking, a parity bit can be used. The use of this bit is however
not mandatory. If the existence of wrong bits is rare (when communicating with an
internal modem, for example) or if a higher level protocol is used for error detection
and correction (Z-modem, RAS, etc.) communication speed can be increased by not
using the parity feature present on the UART.
Parity is a simple way to encode a data word to have a mechanism to detect an error
in the information. The method, used with serial communications, adds one bit to each
data word. The value of this bit depends on the value of the data word. It is necessary
that both the transmitter and receiver use the same algorithm to calculate the value of
the parity bit. Otherwise, the receiver may detect errors which are not present.

Parity bit

While data is transmitted via RS-232 cable, there is a chance of changes in the data
which is transmitted due to noise, crosstalk, etc. For error detecting purposes, an extra
bit is added to the data and sent to the receiver end. The transmitter calculates the value
of the bit depending on the information which was sent. The receiver performs the same
calculation and checks if the actual parity bit value corresponds to the calculated value.

Stop bit

Suppose that the receiver has missed the start bit because of noise on the transmission
line. It starts on the first following data bit with a space value. This causes a garbled
data to reach the receiver. A mechanism must be present to resynchronize the
communication. To do this, framing is introduced. Framing means that all the data bits
and parity bit are contained in a frame of start and stop bits. The period of time lying
between the start and stop bits is a constant defined by the baud rate and the number
of data and parity bits. The start bit always has space value; the stop bit always has
mark value. If the receiver detects a value other than mark when the stop bit should be
present on the line, it knows that there is a synchronization failure. This causes a framing
error condition in the receiving UART. The device then tries to resynchronize on new
incoming bits.
For desynchronizing, the receiver scans the incoming data for valid start and stop bit
pairs. This works, as long as there is enough variation in the bit patterns of the data
words. If data value zero is repeatedly sent, resynchronization is not possible for example.
The stop bit identifying the end of a data frame can have different lengths. Actually,
it is not a real bit but a minimum period of time the line must be idle (mark state) at
the end of each word. On PCs, this period can have three lengths: the time equal to 1,
1.5 or 2 bits. 1.5 bits are only used with data words of 5 bits length and 2 only for longer
words. A stop bit length of 1 bit is possible for all data word sizes.
RS-232 Serial Communication 33

Disadvantages of the parity system

The parity system using one bit for each data word is not capable of finding all errors.
Only errors which cause an odd number of bits to flip will be detected. The second
problem is that there is no way to know which bit is false. If necessary, a higher level
protocol is necessary to inform the sender that this information must be re-sent. Therefore,
on noisy lines, often other detection systems are used to assure that the sent information
is received correctly. These systems mostly do not operate on single data words but as
groups of words. The known coding systems are:
Ȋȱ Hamming coding
Ȋȱ CRC16 cyclic redundancy check
Ȋȱ CCITT-16 cyclic redundancy check
Ȋȱ CRC-DNP cyclic redundancy check
Ȋȱ CRC32 cyclic redundancy check

1.12 HALF-DUPLEX VS FULL-DUPLEX

Before exploring the terms half-duplex and full-duplex, we should first know the meaning
of ‘duplex’. Duplex means to send and receive data from the same device like a phone,
2-way radio or PC (see Fig. 1.30).
Now there are three ways of sending data from a device, i.e., simplex, half-duplex
and full-duplex. In simplex, data always travels in one way. Simplex channels are not
often used because it is not possible to send back error or control signals to the transmit
end.

Figure 1.30 Half-duplex operation

Full-duplex is defined by the ability of a UART to send and receive data simultaneously.
Half-duplex takes place when a device must pause either transmitting or receiving to
perform the other. A half-duplex UART cannot send and receive data simultaneously.
While most microcontroller UARTs are full-duplex, most wireless transceivers are half-
duplex. This is because it is difficult to send two different signals at the same time on
the same frequency, resulting in data collision. If your robot is wirelessly transmitting
data, in effect it will not be able to receive commands during that transmission, assuming
it is using a half-duplex transmitter (see Fig. 1.31).
34 Computer Interfacing and Automation

Figure 1.31 Full-duplex operation

1.13 ASYNCHRONOUS VS SYNCHRONOUS

Asynchronous and asynchronous transmissions are two different methods of transmission


synchronization. Synchronous transmissions are synchronized by an external clock while
asynchronous transmissions are synchronized by special signals along the transmission
medium.

1.13.1 Need for Synchronization

Whenever an electronic device transmits digital (and sometimes analog) data to another
electronic device, there must be a certain rhythm established between the two devices,
i.e., the receiving device must have some way of knowing, within the context of the
fluctuating signal that it’s receiving, where each unit of data begins and where it ends.

Synchronous transmission

In synchronous transmission, the stream of data to be transferred is encoded as fluctuating


voltages in one wire, and a periodic pulse of voltage is put on another wire (often called
the ‘clock’ or ‘strobe’) that tells the receiver “here’s where one bit/byte ends and the
next one begins.”
Practically, all parallel communications protocols use such synchronous transmission.
For example, in a computer, address information is transmitted synchronously—the
address bits over the address bus, and the read strobe in the control bus.

Asynchronous transmission

In one form of asynchronous transmission, there is only one wire/signal carrying the
transmission. The transmitter sends a stream of data and periodically inserts a certain
signal element into the stream which can be ‘seen’ and distinguished by the receiver as
a sync signal.
RS-232 Serial Communication 35

Advantages and disadvantages of asynchronous transmission and synchronous


transmission.

Advantages Disadvantages
Simple, doesn't require synchronization of Large relative overhead, a
both communication sides high proportion of the
Asynchronous
Cheap, because asynchronous transmission transmitted bits are unique
transmission
requires less hardware for control purposes and thus
The set-up is faster than other transmissions carry no useful information

Synchronous Lower overhead and thus, greater Slightly more complex


transmission throughput Hardware is more expensive

As we know, baud rate defines bits sent per second. But baud only has meaning if the
two communicating devices have a synchronized clock. For example, what if your
microcontroller crystal has a slight deviation of 0.1 s, meaning it thinks 1 s is actually
1.1 s long. This could cause your baud rates to break!
One solution would be to have both devices share the same clock source, but that
just adds extra wires. All of this is handled automatically by the UART, but if you would
like to understand more, continue reading.
Asynchronous transmission allows data to be transmitted without the sender having
to send a clock signal to the receiver. Instead, the sender and receiver must agree on
timing parameters in advance, and special bits are added to each word which is used
to synchronize the sending and receiving units.
When a word is given to the UART for asynchronous transmission, a bit called the
‘start bit’ is added to the beginning of each word that is to be transmitted. The start bit
is used to alert the receiver that a word of data is about to be sent, and to force the
clock in the receiver into synchronization with the clock in the transmitter. These two
clocks must be accurate enough not to have the frequency drift by more than 10% during
the transmission of the remaining bits in the word. (This requirement was set in the
days of mechanical teleprinters and is easily met by modern electronic equipment.)
When the data is being transmitted, the sender does not know when the receiver has
‘looked’ at the value of the bit, the sender only knows when the clock says to begin
transmitting the next bit of the word (see Fig. 1.32).
When the entire data word has been sent, the transmitter may add a parity bit that
the transmitter generates. The parity bit may be used by the receiver to perform simple
error checking. Then, at least, one stop bit is sent by the transmitter.
When the receiver has received all of the bits in the data word, it may check for the
parity bits (both sender and receiver must agree on whether a parity bit is to be used),
and then the receiver looks for a stop bit. If the stop bit does not appear when it is
supposed to, the UART considers the entire word to be garbled and will report a framing
error to the host processor when the data word is read. The usual cause of a framing
error is that the sender and receiver clocks were not running at the same speed, or that
the signal was interrupted.
36 Computer Interfacing and Automation

Figure 1.32 Asynchronous data bit

Regardless of whether the data was received correctly or not, the UART automatically
discards the start, parity and stop bits. If the sender and receiver are configured
identically, these bits are not passed to the host.
If another word is ready for transmission, the start bit for the new word can be sent
as soon as the stop bit for the previous word has been sent. In short, asynchronous data
is ‘self-synchronizing’.

1.14 ELECTRICAL STANDARDS IN DETAIL

The EIA232 standard uses negative bipolar logic. Whenever the serial port sends a logical
one (1) a negative voltage is effected on the transmit pin. Whenever the serial port sends
a logical zero (0), the positive voltage is affected. When no data is being sent, the serial
port’s transmit pin’s voltage is negative (1) and is said to be in a MARK state. The serial
port can also be forced to keep the transmit pin at a positive voltage (0) and is said to be
the SPACE or BREAK state. Sometimes negative logic assignment of EIA232 is the reverse
of that found in most modern digital circuit designs, so this should be checked first.
The EIA232 standard includes a common ground reference on Pin 7 in the DB25
connector and signal ground on Pin 5 in the DB9 connector. All the voltage signals i.e.
date, timing, control signal are measured with respect to this common ground. Both the
ends of the RS-232 circuit depend on the ground pin. Problems may occur when both
ends have a different ground signal. This may cause a hazardous ground loop. Thus
the use of a common ground limits RS-232 to applications with relatively short cables.
If the two devices are far enough apart or are on separate power systems, then the local
ground connections at either end of the cable will have differing voltages thus the
difference will reduce the noise margin of the signals.
RS-232 defines the purpose, signal timing and signal levels for each line. The output
signal level usually swings between +12 V and –12 V. The high level is defined as between
+5 V and +12 V, and a low level is defined as between –5 V and –12 V. With 2 V of noise
margin, a high level for the receiver is defined as between +3 V and +12 V, and a low
RS-232 Serial Communication 37

level is between –3 V and –12 V. The signal voltage between +3 V and –3 V, called, ‘dead
area’, and is designed to absorb line noise. A low level is defined as logic 1 and is
referred to as ‘marking’. Similarly, a high level is defined as logic 0 and is referred to
as ‘spacing’. The following figure illustrates the logic level (see Fig. 1.33).

Figure 1.33 Logical level of RS-232

Note: In the embedded system, if the device communicates at TTL level, the connection
between the embedded system and external device is simple. But if the device needs
RS-232 level signaling, we will have to insert an RS-232 line driver/receiver between the
processor and the device. Most of the devices used nowadays need three wires, i.e.,
transmitted data, received data and signal ground. No need for hardware flow control
signal. This simplifies the hardware connection as well as the software design. Figure
1.34 shows how the data looks like for ASCII-A.

Figure 1.34 Output data of RS-232

1.15 SIGNAL CHARACTERISTICS

In RS-232, user data is sent as a time-series of bits. Basically, the transmission or reception
of data takes place one bit at a time. A bit is either a logical 1 or 0. In general, address
data are in bytes, where a byte contains 8 bits. Both synchronous and asynchronous
transmissions are supported by the standard. In addition to the data circuits, the standard
defines a number of control circuits used to manage the connection between the DTE
and DCE (see Fig. 1.35). Each data or control circuit only operates in one direction that
is, signaling from a DTE to the attached DCE or the reverse. Since transmitted data and
received data are separate circuits, the interface can operate in a full-duplex manner,
supporting concurrent data flow in both directions. The standard does not define
character framing within the data stream or character encoding.
38 Computer Interfacing and Automation

Figure 1.35 Block diagram of DTE to DCE communication

The figure below is the equivalent circuit. All signal lines, regardless of whether they
provide data, timing, or control information, may be represented by the electrical
equivalent circuit shown here (Fig. 1.36).

Figure 1.36 Equivalent circuit of DTE to DCE communication

This is an equivalent circuit for an EIA232 signal line and applies to signals originating
at either the DTE or DCE side of the connection. Co is not specified in the standard, but
is assumed to be small and consisting of parasitic elements only. Ro and Vo are chosen
so that the short-circuit current does not exceed 500 mA. The cable length is not specified
in the standard; acceptable operation is experienced with cables that are less than 25”
in length.
Transmitter and receiver timing signals (pins 15, 17, and 24) are used only for a
synchronous transmission protocol. For the standard asynchronous 8-bit protocol,
external timing signals are unnecessary as asynchronous data is ‘self-synchronizing’.
When transmitting a byte, the UART (serial port) first sends a start bit which is a
positive voltage (0), followed by the data (general 8 bits, but could be 5, 6, 7, or 8 bits)
followed by one or two stop bits which is a negative voltage (1). The sequence is repeated
for each byte sent. Figure 1.37 shows a diagram of a byte transmission would look like.
RS-232 Serial Communication 39

Figure 1.37 Block diagram of byte transmission

The first characteristic is the length of the byte that will be transmitted. This length,
in general, can be anywhere from 5 to 8 bits. The second characteristic is parity. The
parity characteristic can be even, odd, mark, space, or none. If even parity, then the last
data bit transmitted will be a logical 1 if the data transmitted had an even amount of 0
bits. If odd parity, then the last data bit transmitted will be a logical 1 if the data
transmitted had an odd number of 0 bits. If mark parity, then the last transmitted data
bit will always be a logical 1. If space parity, then the last transmitted data bit will
always be a logical 0. If no parity then there is no parity bit transmitted. The third
characteristic is the number of stop bits. This value, in general, is 1 or 2.
Assume we want to send the letter ‘A’ over the serial port. The binary representation
of the letter ‘A’ is 01000001. Remembering that bits are transmitted from the least
significant bit (LSB) to the most significant bit (MSB), the bit stream transmitted would
be as follows: for the line characteristics 8 bits, no parity, 1 stop bit, and 9600 baud. LSB
(0 1 0 0 0 0 0 1 0 1) MSB. This represents (start bit) (data bits) (stop bit).

1.16 SIGNAL STATE VOLTAGE ASSIGNMENTS

Signal state voltage assignments: Voltages of –3 V to –25 V with respect to signal


ground (Pin 7) are considered logic ‘1’ (the marking condition), whereas voltages of +3
V to +25 V are considered logic ‘0’ (the spacing condition). The range of voltages between
–3 V and +3 V is considered a transition region for which a signal state is not assigned
(see Fig. 1.38).

Figure 1.38 RS-232 voltage to time graph


40 Computer Interfacing and Automation

Logic states are assigned to the voltage ranges shown here. Note that this is a ‘negative
logic’ convention, which is the reverse of that used in most modern digital designs. Most
contemporary applications will show an open circuit signal voltage of –8 to –14 V for
logic ‘1’ (mark), and +8 to +14 V for logic ‘0’ (space). Voltage magnitudes will be slightly
less when the generator and receiver are connected (when the DTE and DCE devices
are connected with a cable).
Note: If you insert an LED signal tester in an EIA232 circuit to view signal states, the
signal voltage may drop in magnitude to very near the minimum values of –3 V for
logic ‘1’, and +3 V for logic ‘0’. Also, note that some inexpensive EIA232 peripherals are
powered directly from the signal lines to avoid using a power supply of their own.
Although this usually works without problems, keep the cable short, and be aware that
noise immunity will be reduced.

1.17 ASCII COMMANDS

RS-232 is a message based communication system. For example, *IDN? is a common


command which means similar to “what is your name?” The device returns its model
number or serial number as preprogrammed. The American Standard Code for
International Interchange is the explanation of ASCII, which main code used in RS-232
communication. It was created in 1963 by American Standard Association Committee.
It is now known as American National Standard Institute (ANSI). By reordering and
expanding the symbols and characters used in telegraphy, ASCII was framed. In 1967,
it was changed to include upper and lower cases.

1.18 LEVEL SHIFTER

Back in the day circuits were noisy, lacking filters and robust algorithms, etc. Wiring
was also poor, meaning signals became weaker as wiring became longer (relates to the
resistance of the wire). So to compensate for the signal loss, they used very high voltages.
Since a serial signal is a square wave, where the wavelengths relate to the bit data
transmitted, RS-232 was standardized as +/–12 V. To get both +12 V and –12 V, the most
common method is to use the MAX232 IC (see Fig. 1.39).
Digital communication in electronics is essential for modern electronics, but the variety
of voltages applied can make communication between digital systems a challenge. Digital
logic levels are based on voltage levels that represent high and low signals. Depending
on the standard used, a signal could be misread or worse, cause damage to the circuit.
Shifting the voltage level of the logic signal through the use of level shifting circuitry
is a great way to maintain communication between digital systems that use different
voltages.
To communicate reliably between the logic voltage levels, level shifting techniques
or ICs are often the best choice. Unfortunately, no level shifting technology is perfect
and accommodating different communication standards, operational frequencies, and
voltage levels always involve some trade-offs.
RS-232 Serial Communication 41

Figure 1.39 RS-232 level shifter block diagram

1.18.1 Selecting a Level Shifter

There are several ways to implement a level shifter in a circuit, from simple circuits to
using specially made ICs. One-way communication may be able to take advantage of a
simple resistive divider, as long as little driving current is needed. Level shifting gets
more complicated when high-speed communication such as SPI and UART is used
where stray capacitance can start to limit the data transmission speed, and with I2C
which requires a true bidirectional communication.

1.18.2 Resistive Divider

A simple resistive divider network allows a higher voltage device to communicate with
a lower voltage device.

1.18.3 MOSFETs

It is the simplest way to achieve bidirectional level shifter which works perfectly for I2
C bidirectional communication systems. The MOSFETs are put directly on the bus lines
between the two voltage levels.
42 Computer Interfacing and Automation

1.18.4 Open Drain

Open Drain level shifters can translate between high and low voltages bidirectionally
without the need of a directional control input.

1.18.5 Push-Pull

Push-pull level shifters provide a strong output drive signal of up to several tens of mA
and support high-frequency operation (>100 mbps). Unfortunately, they require a
direction control input, which makes them natively incompatible with I2C.

1.19 READING RS-232 DATA TO A PC USING VISUAL BASIC 6.0

AIM: To read data from RS-232 to a PC using VB (see Fig. 1.40).


Components: PC with Windows, Visual Basic 6

Figure 1.40 Block diagram of experimental setup to read data to a PC using VB

Theory: To read data using VB6.0, you need to create a project in VB6.0 and add
components library called ‘MSComm control’ in VB 6.0 project form.

1.19.1 The MSComm Control

This programming assumes the user has a basic knowledge of Visual Basic programming.
The teaching method used is to show a basic example of a VB6.0 program which
communicates with any RS-232 transmitter by sending and receiving ASCII data and
then dissects the program to understand its operation. This example is just to get a
feeling that how VB GUI looks like and how to code for RS-232.
RS-232 Serial Communication 43

Serial data acquisition interfaces require the sending and receiving of ASCII data via
RS-232 to operate. To communicate with the RS-232 devices using VB6.0, the MsComm
control must be utilized to allow serial data transfer via a serial port (e.g., Com1-Com4).
MSComm is a custom control shipped with VB6.0 and must be loaded using the Tools
menu.
Add a form and create buttons as shown below. (This is just for practice)
The program was built using radio buttons for port control, three command buttons,
a text box to display analog data and the MSComm control for serial communications.
When run, the port is enabled using the radio buttons and then AN0 is read every time
the Read AN0 button is clicked. The analog data is then displayed in text box 1. PA0
can be set or reset using the SET PA0 or RESET PA0 buttons. When run, the program
appears as follows. AN0 and PA0 are just example buttons which can be assigned for
any operation. In this demonstration, it communicates to a board named - ‘RS-232112’
which is connected to COM 1.

The MSComm properties allow the setting of communication parameters including


port selection and port enabling functions. The properties window is shown below. Note
the default settings for MSComm allow communication with the RS-232 interfaces by
merely selecting a com port (com2 in our example), and enabling the port. The
communication parameters of 9600,n,8,1 are the default parameters and need not be
altered to communicate with RS-232 products unless the device to be communicated
has other settings given in manual.
44 Computer Interfacing and Automation

The com port must be enabled to allow communication with the RS-232 board. The
sample code for the Port Enable radio button is:

The port is enabled by setting MSComm1.PortOpen to TRUE. A CPA00000000


command is then sent using the MSComm1. Output function to configure port A as
output. The Chr (13) variable is a carriage return required by the RS-232 board.
The Read AN0 button reads analog port 0 and displays the data in text box 1. The
code for this button is shown below.

In this example, the RD0 command is sent using the MSComm1. Output function
and then the program loops until five characters are received into the serial buffer. (The
RS-232112 returns four ASCII characters ranging from 0000 to 4095 and a carriage return
in response to an RD0 command.
The SETPA0 button simply sends a SETPA0 command to the RS-232112. The code for
this button is shown below.
RS-232 Serial Communication 45

The RESPA0 button simply sends a RESPA0 command to the RS-232112. The code
for this button is shown below.

Before exiting the program, the comm port must be disabled. This is done with the
Disable port radio button. The code for this button is shown below.

1.19.2 Notes and Programming Hints

1. Port enabling: Port selection and ‘enable’ functions can be programmed in the
‘load’ and ‘unload’ subroutines in the ‘form’ object, or they may be controlled
by radio buttons or pull down menus.
2. Receiving data: When receiving data from the RS-232 board, be sure to wait for
the correct number of characters to be received in the serial buffer. Check your
RS-232 programming manual for the right number of characters to be received
and add one for the carriage return. The RS-232 transmitter sends both a carriage
return and line feed thus two must be added to the number of characters expected.
3. Using variables: In many cases it may be desired to send a string incorporating
a command and some variable. For example, the ‘MAddd’ command outputs to
port A, the integer value ddd. If ddd is a variable named PV, a string to set the
port to the value of this variable would look as given below.
46 Computer Interfacing and Automation

MSComm 1. Output = “MA” & Str(PV) + Chr(13)


The ‘Str’ function converts the variable to an ASCII string and it is appended to ‘MA’.
The Chr(13) is a carriage return.

Learn RS-232: In Linux, every port is also a file with Linux.


Linux based Practical Projects using following C++ class library example for serial

EXAMPLE 1: Develop C++ program to write to a file using libserial. class. (see Fig. 1.41)
Components: Linux PC, linSerial class library-free download (http://ibiblio/pub/linux/
libs/libserial.lsm)
RS-232 Serial Communication 47

RS-232
Tx
device
Linux with
Rx
C++
1000 A
compiler Ground
Power
Supply

Figure 1.41 Reading RS-232 data to a PC using Linux C++

In linux, everything is a file. Serial port is also a file.


The free linSerial class provides a simple framework for serial port in linux OS. This
class hides complexity of linux/unix termios interface. Since it is a C++ class, it can be
used simply by making an object. download (http://ibiblio/pub/linux/libs/libserial.lsm).
Program: A C++ program was written under the Linux operating system to test a linSerial
class. This class can be used to read and write to a file. The file name can be any text
file (e.g., yo.txt or a serial device names “/dev/cua0” which is equivalent to COM1 in
windows)
//
// FILE:
// demo.cpp
//
// FUNCTION:
// A simple demo of the linSerial class.
//
// HISTORY:
// Copyright (c) 1995, 1997 LinasVepstas
// Released under the conditions of the GNU General
// Public License.
#include “serial.h"
main()
{
ZULWHVRPHWHVWWRDQRUGLQDU\¿OH
linSerial j;
j.OpenDevice("yo.txt");
FILE*fh=j.GetFileHandle();
fprintf(fh,"Yo, Duuuuude ! \n");
j.Close();
}
EXAMPLE 2: C++ code to write to an RS-232 port in linux OS
#include “serial.h"
main(){
// send commands to the modem device
linSerial m;
48 Computer Interfacing and Automation

m.OpenDevice("/dev/cua0");
m.Set8N1();
m.SetSpeed(9600);
FILE*dh=m.GetFileHandle();
fprintf(dh,"ATZ");// Hayes command set
fprintf(dh,"ATDT1-212-555-1212");// Hayes command set
m.Close();
}
EXAMPLE 3: An example RS-232 Linux based program to communicate to an FP1000
field point device (serial device sold by M/s National Instruments).

Program (FP1000)
#include ''serial.h”
#include ''errlog.c”
#include ''serial.c”
#include ''iostream.h”
main( )
{
char s[200];
cout<< ''program to test all fp modules”<<endl;
cout<<''wait please ------”;
//send commands to modem device
linSerial*m=new linSerial;
m->openDevice (''/dev/cua0”);
printf(“opened\n”);
m->Set8N1( );
printf(“set 8n1\n”);
m->SetSpeed(9600);
printf(“9600 set\n”);
P!6HW6RIWZDUHÀRZ&RQWURO  
SULQWI ³6HWVRIWZDUHÀRZFRQWURO?Q´ 
FILE*dh=m->GetFileHandle( );
//fprintf(dh,''>00!z??\r”);
printf(“\n\n\n”);
fprintf(dh,''>00!B??\r”);
fscanf(dh,''%s”,s);
printf(''%s”,s);
m->close();
delete m;
exit(0);
}
In the above example,linSerial is a free class library available on the internet (link:
http://linas.org/serial/). The class code is given below.
RS-232 Serial Communication 49

class linSerial :
protected linErrLog
{
public: linSerial (void);
intOpenDevice (const char *);
intGetFileDescriptor (void) { return fd; }
FILE * GetFileHandle (void) { return serialport; }
void Close (void);
intSetupDefault (void);
intSetupRaw (void);
intSetupTerminal (void);
intSetSpeed (int);
intSetHardwareFlowControl (void) { return SetFlowControl (1); }
intSetSoftwareFlowControl (void) { return SetFlowControl (0); }
intSetBits (int, char, int);
int Set8N1 (void) { return SetBits (8, 'N', 1); }
int Set7E2 (void) { return SetBits (7, 'E', 2); }
void SetDTR (void);
void ClearDTR (void);
protected:
intSetFlowControl (int);
LQWIG¿OHGHVFULSWRU
FILE * serialport;
  FKDU ¿OHQDPH
private:
int speed;
short istty;
};
EXAMPLE 4: RS-232 firmware project
Aim: To design a hardware device which can work as an RS-232 transmitter to transmit
characters ‘A’ and ‘B’ at pin 28.
Required Tools: ARM Mbed 1768/Microcontroller (40 pins), online - MBED C++ compiler
for firmware development. (www.mbed.org)

Figure 1.42 Creating an RS-232 transmitter in firmware


50 Computer Interfacing and Automation

The firmware code of RS 232 for sending ‘A’ & ‘B’ (see Fig. 1.43)
#include” Mbed.h”
Serial device (p28,p27);//tx, rx of microprocessor//P28,P27 can
be USBTX,USBRX to emulate
Int main () {
Device.baud (19200);
Device.format (8,Serial::Odd 1);
Int delay counter;
For (;;)
{
For (delaycounter =0; delaycounter<100000; delaycounter ++);//
just to delay
Device.putc (0×41); // send ‘A’
Device.putc (0×42); /// send ‘B’
}
}
The above program will be converted to machine language binary file and will be
downloaded to the microcontroller. (refer www.mbed.org)
EXAMPLE 5: How to design an RS-232 transmitter to control the brightness of an
LED on the ARM Mbed LPC 1768 board using PWM based analog control using a
PC keyboard?

Figure 1.43
7KH¿UPZDUH
#include “Mbed.h”
//Serial pc(USBTX, USBRX); // tx, rx//This is useful to emulate
Serial target (USBTX,USBRX);
PwmOut led(LED1);
ÀRDWEULJKWQHVV 
int main() {
target.printf("Press 'u' to turn LED1 brightness up, 'd' to turn
it down\n");
while(1) {
RS-232 Serial Communication 51

char c = target.getc();
if((c == 'u') && (brightness < 0.5)) {
target.printf("increasing brightness\n");
brightness += 0.01;
led = brightness;
}
if((c == 'd') && (brightness > 0.0)) {
target.printf("decreasing brightness\n");
brightness -= 0.01;
led = brightness;
}
}
}

The serial interface defaults to a 9600 baud standard serial connection (8 bits, 1 stop
bit and no parity), so the host program should be set to the same settings. If you want
to communicate at a different standard baud rate, modify the settings of both the serial
interface and the host PC application!
The PC host application can be a terminal like Tera Term or Hyper Terminal.
The above program will increase brightness of LED by pressing ‘u’ decrease by ‘d’
in keyboard.

RS-232 INTERFACING OF INSTRUMENTS: PROJECTS USING PC


PROJECT 1: READ AND LOG RS-232 OUTPUTS OF A RADIATION METER
(4 NOS) USING LABVIEW (ASSUME 4 METERS HAVE TO BE READ FROM
COM 2, 3, 4 & 5) AND M/S ADVANTECH MULTIPORT SERIAL CONVERTER

Aim: To read and log RS-232 outputs of a radiation meter using LabVIEW.
Components: Ludlum Model375 area monitor, Ethernet to RS-232 converter, PC with
serial device server configuration utility, Adam Apex Dot Net utility, LabVIEW.

Theory

Ludlum Model 375 area monitor: Model 375 is a versatile, compact, and affordable
digital electronic controller designed for monitoring radiation. Its simple design
accommodates many different detectors suiting a wide variety of applications, and is
equipped with a local readout and alarms. These versatile units may also be connected
to optional auxiliary indicator/enunciators for alerting personnel at remote locations.
The user-friendly, digital design enhances setup and operation. These units may
also be networked to a PC-based central station where data are logged and alarms
posted.
This affordable and flexible system has found its way into many applications resulting
in a full complement of detectors, accessories, and options that include remote indicator
alarms, printers, relay outputs, weather-proof enclosures, Ethernet networking software,
industrial cameras, and more.
52 Computer Interfacing and Automation

Ludlum Model 375 area monitor

Ethernet to RS-232 Converter: EKI 1524 (Advantech) Multi-port Serial Box

Converter has one Ethernet and four com ports (COM2, COM3, COM4, and COM5).
Configurable as RS-232/RS-485. This is also known as serial device server device.

PC

Before starting the experiment, we have to install the serial device server configuration
utility, Adam Apex Dot Net utility, and LabVIEW software. (All free for tests available
online)

Procedure

Connect the experimental setup and connect to power. The radiation meter RS-232
output is fed to the RS-232 converter which is connected using Ethernet to PC. For
checking, we can give ping command so that we know the cable is connected otherwise,
give the IP address through the local area network.

Radiation meter connected to the Ethernet to RS-232 converter


RS-232 Serial Communication 53

First right click the ‘Serial Device Server Configuration Utility’ and click the Run as
administrator option.

We can find the above screen, by clicking Yes it will run the program and shows the
screen as below. We configure port 1 (COM2) as serial RS-232 port.
54 Computer Interfacing and Automation

If our PC have com ports, we can see those ports as shown above. Minimize the
above-given window and double click to run the Adam Apex Dot Net utility.
Click the desired com to set the Values like Baud rate, parity, Data bits, Stop bits,
Time out, Scan interval and then click Apply. Minimize this window and open the
LabVIEW, which is already installed. The window is shown below.
In this device the protocol is 2400,N,8,1. So one can use Tera term (free software) or
Hyper termnal to view this data. Remember to set receiving handshake as LF.
RS-232 Serial Communication 55

For radiation monitor, we have the saved file. So by clicking open the existing file
can be attached by right clicking the file so that in LabVIEW we can see the output and
block diagram of the LabVIEW program as shown below after setting the COM port
and Run program.
56 Computer Interfacing and Automation

This is the block diagram of the program involved, so that we can see the output
digital data, and we write it into a data file which is inside the While loop. To know in
detail about this, we can right click and click the Help so that we can see the details
about the written program.

PROJECT 2: TO BUILD AN RFID READER THROUGH TERA TERM & RS-232


(CARD READER)

Aim: To build an RFID reader interfaced using RS-232 using Tera Term/Hyper terminal
Components: RFID reader, USB to RS-232 converter, PC with Tera Term.

Theory
What is RFID?

Ȋȱ RFID (Radio Frequency Identification) is a technology that uses electromagnetic


fields to identify objects in a contact-less way, it is also called proximity identification.
Ȋȱ In a normal RFID communication, the RFID module is fixed, and the user takes
his card near it when he needs to start the interaction.
RS-232 Serial Communication 57

Ȋȱ RFID uses radio frequency waves to transfer data between a reader and a movable
item to identify, categorize, and track.
Ȋȱ RFID is fast, reliable, and does not require physical sight or contact between the
reader/scanner and the tagged item.

READING RFID READER MODULE ID-12 (A PCB SOLD IN MARKET AS RFID


READER)
Procedure

Connect the RFID reader to the power supply and its RS-232 output (9 pin D) to
RS-232 converter (MOXA U1110) using an RS-232 straight cable from which it is connected
to PC having Tera Term.

Set-up the Tera Term terminal to read RS-232 data by setting protocol 9600,N,8,1 on COMX.
We can see the below given window when we touch the card to RFID it displays
some number. This means card worked fine and returned the ID through RS-232.
58 Computer Interfacing and Automation

PROJECT 3: TO CONTROL A MACHINE WHICH IS POWERED THROUGH AN


AC CONTACTOR OF 15 A USING AN RS-485 DRIVEN DIGITAL OUTPUT
MODULE (ADAM-4055) AND LABVIEW VER 11 (THOUGH IT IS RS-485,
FINALLY IT COMES TO VIRTUAL RS-232 PORT IN PC)

Aim: To control a machine which is driven by an AC contactor of 15 A using RS-485


module (ADAM-4055) and LabVIEW Ver 11

Apparatus Required

Ȋȱ ADAM-4055 module
Ȋȱ EKI 1524 - Ethernet to 4-port RS-485 converter
Ȋȱ +24 V regulated power supply
Ȋȱ Small relay module, 8-channel
Ȋȱ Contractor rating 230 V AC/15 A, +24 V DC control
RS-232 Serial Communication 59

THE SCHEMATIC
60 Computer Interfacing and Automation

Steps

Ȋȱ Configure the serial server utility to map serial port of channel 2 as COM6 as
shown below.
Ȋȱ Ensure that Port2 (channel2) is RS-485 configured, and protocol is set as 9600,N,8,1.
Ȋȱ Ensure that Port1 is mapped to COM5, Port2 is mapped to COM6, Port3 is mapped
to COM7, and Port4 is mapped to COM8.
(As we used industrial PC which has already 4 serial ports, viz., COM1, COM2,
COM3, COM4 reserved)

Run Adam.NET utility to search device to find ADAM-4055 is installed as shown


below.
RS-232 Serial Communication 61

Refresh sub-nodes as shown above to map serial ports of EKI device.


62 Computer Interfacing and Automation

Open LabVIEW Version 11.


Open example program from LabVIEW 11. (Basic Serial Write Read.vi)
Fill in the string data “#010001\r” to On the LED as shown below.
RS-232 Serial Communication 63

Result: You will see that you can On a bit and On the contractor.

PROJECT 4: RS-232 INTERFACING TO CONTROL ONE BIT OF RS-485 DIO


ADVANTECH MODULE: (DIGITAL OUTPUT BIT) TO ON/OFF LED THROUGH
TERA TERM/HYPERTERMINAL

Aim: To On/Off LED through Tera Term. LED is part of ADAM4055. Bit can be a RELAY.
Components: ADAM-4055 with 16-ch isolated digital I/O module with Modbus with
LED, Ethernet to RS-485 converter, PC with Tera Term. (Hardware setup is same as in
project 3).

Theory

ADAM-4055 with 16-ch Isolated Digital I/O Module with Modbus with LED:
Ȋȱ I/O type: 8 DO/DI
Ȋȱ Input Voltage level: 10~50 VDC
Ȋȱ Open Collector to 40 VDC
Ȋȱ Over voltage protection: 70 VDC
Ȋȱ 2,500 VDC optical isolation
64 Computer Interfacing and Automation

Procedure

Connect ADAM module, Ethernet to RS-485 converter and PC.


Double click to open Tera Term.
RS-232 Serial Communication 65

Select Serial and enter port then press OK. Set the protocol details.
Go to Set Up, select Serial Port and in that select Local Echo.

In the terminal shown below enter the command #010001 to On the LED.
66 Computer Interfacing and Automation

Now, the LED is in On state. To Off the LED, we have to give #01000 command.
RS-232 Serial Communication 67

In this way, we can operate LED from large distances.

PROJECT 5: INTERFACING AN OXFORD INSTRUMENT USING VISUAL BASIC


6.0 RS-232 COMMUNICATION (DEVICE: M/S OXFORD ITC503)

We used a Moxa RS-232 to USB converter (U1110 converter) for connecting Oxford
temperature sensor to the computer as shown below. (device manual ITC503: amnol.
usv.pd/doc/itc503.pdf)
68 Computer Interfacing and Automation

The figure above represents GUI, designed using VB 6.0.


Aim: To control Oxford temperature controller using RS-232.

Step 1

Make a cable (Null modem) connect the PC to the device.


Program description when clicking the ‘Remote’ button.
Private Sub cmdremote_Click()
If cmdremote.Caption = “REMOTE" Then
retstring = sendcommand("C3")
'MsgBoxretstring
MsgBox “SET TO REMOTE OPERATION SUCCESSFULLY"
Label9.Caption = “NOW IN REMOTE"
cmdremote.Caption = “LOCAL"
cmdremote.BackColor = vbGreen
RS-232 Serial Communication 69

Else
retstring = sendcommand("C2")
'MsgBoxretstring
MsgBox “SET TO LOCAL OPERATION SUCCESSFULLY"
Label9.Caption = “NOW IN LOCAL"
cmdremote.Caption = “REMOTE"
cmdremote.BackColor = vbRed
End If
End Sub

Description

‘retstring = sendcommand("C3")’: As this command is written in the above program, the


‘send command’ function is called.
The following function is the main function which controls the device.
Public Function sendcommand(instring As String) As String
'MsgBox “GOT STRING" + Trim(instring) &Chr$(13)
''''''''''reading data
%X๱HUWRKROGLQSXWVWULQJ
' Diminstring As String
' Use COM1.
MSComm1.CommPort = Trim(comtxt.Text) '14
' 9600 baud, no parity, 8 data, and 1 stop bit.
MSComm1.Settings = “9600,N,8,1"
7HOOWKHFRQWUROWRUHDGHQWLUHEX๱HUZKHQ,QSXW
' is used.
MSComm1.InputLen = 0
' Open the port.
MSComm1.PortOpen = True
' Send the attention command to the modem.
MSComm1.Output = Trim(instring) &Chr$(13) ' Ensure that
' the modem responds with “OK".
' Wait for data to come back to the serial port.
Do
DoEvents
EX๱HU EX๱HU 06&RPP,QSXW
/RRS8QWLO,Q6WU EX๱HUYE&U
' Read the “OK" response data in the serial port.
' Close the serial port.
 0VJ%R[³(;(&87('68&&(66)8//<EX๱HU
MSComm1.PortOpen = False
'''''' end data
VHQGFRPPDQG EX๱HU
,I0LG EX๱HU  ³"7KHQ
70 Computer Interfacing and Automation

'MsgBox" SOME THING WRONG !!! PLEASE SEE !!!!!may be not in re-
mote or something else"
'Else
'MsgBox" SUCCESSFUL !!! “
'End If
End Function
‘cmdremote.BackColor’: As this command is written in above program so the
‘cmdremote.BackColor‘ function is called.
The following function controls the color.
Private Sub Timer1_Timer()
If cmdremote.BackColor = vbGreen Then
If Shape5.FillColor = vbBlack Then
Shape5.FillColor = vbGreen
Else
Shape5.FillColor = vbBlack
End If
Lblsensortemp.Caption = Str(Val(Mid(sendcommand("R1"), 3, 5)) /
10)
End If
End Sub

PROJECT 6: INTERFACING OXFORD INSTRUMENT IN VISUALBASIC.NET


(2008) RS-232 COMMUNICATION

We used a MoxaRS-232 to the USB converter for connecting Oxford temperature sensor
to the computer. (Model U1110 M/S MOXA)
RS-232 Serial Communication 71

Once the above physical layer is developed, we install the Moxa driver to create a
serial COM port on the computer.
Once the Moxa COM port is created, we test the working of the device using Tera
Term. Set the device parameters as 9600,N,8,1. Enable the local echo. Send a sample
command like ‘V’ to check the connectivity.
Imports System
Imports System.IO.Ports
Imports System.Threading
PublicClass Form1
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
'9600 baud, no parity, 8 data, and 1 stop bit.
'SerialPort1.BaudRate = 9600
'SerialPort1.Parity = IO.Ports.Parity.None
'SerialPort1.DataBits = 8
'SerialPort1.StopBits = IO.Ports.StopBits.One
7HOOWKHFRQWUROWRUHDGHQWLUHEX๱HUZKHQ,QSXW
' is used.
' MSComm1.InputLen = 0
' Open the port.
' MSComm1.PortOpen = True
' Send the attention command to the modem.
Try
SerialPort1.Write("X" + Chr(13))
Thread.Sleep(20)
SerialPort1.ReadTimeout = 100
RichTextBox1.AppendText(SerialPort1.ReadTo(Chr(13)))
'MSComm1.Output = “V" & Chr$(13) ' Ensure that
' the modem responds with “OK".
' Wait for data to come back to the serial port.
Catch ex As TimeoutException
RichTextBox1.AppendText("no data")
EndTry
SerialPort1.Close()
EndSub
EndClass
72 Computer Interfacing and Automation

Steps for interfacing Oxford temperature sensor in VisualBasic.net 2008 are as follows:
1. Start a new project
2. Create a new Button
3. Create a new Rich Textbox to show the output.
4. Create a new serial port
5. Set the parameters of the port manually (or can be set programmatically)
6. Now inside the function (callback) of the button, open the serial port using
SerialPort1.Open() where serialport1 is the name of serialport created.
RS-232 Serial Communication 73

7. Include the following header files Imports System, Imports System.IO.Ports,


Imports System.Threading.
8. Put a try-catch block, so as to check the connectivity is always on. If there is no
connectivity, no data will come in the textbox.
9. SerialPort1.Write("V" + Chr(13)), use this command to write a data, (send
command) to the temperature sensor device.
Chr (13) = Carriage Return - (moves cursor to leftmost side), \r
Chr (10) = New Line (drops cursor down one line), \n
10. Thread.Sleep(20) is given for waiting 20 ms for command to be sent.
11. SerialPort1.ReadTimeout = 100 , set RS-232 read timeout to 100 ms.
ReadTimeout Gets or sets the number of milliseconds before a timeout occurs
when a read operation does not finish. It gets or sets a value, in milliseconds,
that determines how long the stream will attempt to read before timing out.
12. RichTextBox1.AppendText(SerialPort1.ReadTo(Chr(13))), Read data from RS-232
Input Buffer up to the next CR (CHR(13))
13. Timeout exception is thrown when time allotted for a process or operation has
expired.
14. SerialPort1.Close(), Close the serial port.

PROJECT 7: INTERFACING OXFORD TEMPERATURE METER USING Qt


UNDER WINDOWS OR LINUX (Qt IS PLATFORM INDEPENDENT)

To build a Qt interface in Windows/Linux for RS-232 based instrument interfacing


Linux/Windows Qt interfacing RS 232 communication with instrument
We used a Moxa RS-232 to USB converter (U1110) for connecting the Oxford temperature
sensor to the computer as shown below. The computer is installed with Qt ver 4.0 (free).
First you need to create a project which will have following files.
74 Computer Interfacing and Automation

The figure above is GUI, designed using Qt evaluation.


.pro file code (This is auto generated code when creating new Qt project)
#-------------------------------------------------
#ProjectcreatedbyQtCreator2014-12-30T03:15:31
#-------------------------------------------------
QT+=coregui
greaterThan(QT_MAJOR_VERSION,4){
QT+=widgetsserialport
}else{
include($$QTSERIALPORT_PROJECT_ROOT/src/serialport/qt4support/se-
rialport.prf)
}
greaterThan(QT_MAJOR_VERSION,4):QT+=widgets
TARGET=OXFORD
TEMPLATE=app
SOURCES+=main.cpp\
mainwindow.cpp
HEADERS+=mainwindow.h
FORMS+=mainwindow.ui
First, you need to add a serial port to your project widgets. For that, do the above
command which adds the serial port according to the version of Qt that you have.
Everything else in the .pro file is by default.
.pro file is basically used to establish connections, specify your targets and sources
for your project.

Mainwindow.h code
#ifndef MAINWINDOW_H
GH¿QH0$,1:,1'2:B+
#include <QMainWindow>
#include <QDialog>
RS-232 Serial Communication 75

#include <QtSerialPort/QSerialPort>
GH¿QHYFPGY?U
GH¿QH[FPG;?U
GH¿QHUHPRWHFPG&?U
GH¿QHORFDOFPG&?U
namespace Ui{
class MainWindow;
}
class MainWindow:public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget*parent=0);
QByteArray getdata(char*);
~MainWindow();
private slots:
void vslot1();
void xslot1();
void remoteslot1();
void localslot1();
private:
Ui::MainWindow *ui;
};
#endif//MAINWINDOW_H
In the .h file add the < Qt Serial Port/Q Serial Port > library for accessing functions
and classes related to serial port. Whatever function you create yourself, to be defined
in Main Window Class, specify their prototypes either in private or public section.
76 Computer Interfacing and Automation

All of this is done in the edit tab.


For creating the user interface, click on the form subsection in edit tab. Create a UI
with different widgets you want to add as shown below.

If you want to trigger an action from a widget, like on clicking a button, add slots to
each button.
RS-232 Serial Communication 77

Slots are created by clicking on above edit slots/signals button.

Click on the edit button.


78 Computer Interfacing and Automation

Click on the plus (add) button. Give a specifically required callback function name.
Now after naming the function, you need to link it to the button action. For that press
OK. Then double click on clicked(), select the function name from Main Window section
and press OK.
Once all such slots (callback functions are named and linked), return to main window.h
file.
RS-232 Serial Communication 79

Now, add all the callback functions created above as private slots: inside the Main
Window Class definition. This is the prototype, needed because we will give the definition
of the function later after the class, externally. You will see that.
main.cpp

You don’t have to do anything in the main.cpp. Inside the mainwindow.cpp the
following code is added:
In the below code, define the definition of callback functions as:
voidMainWindow::remoteslot1()
{
replydata=getdata(remotecmd);
if(replydata[0]=='?')
{
ui->textEdit->setPlainText("error");
}
else
{
ui->textEdit->setPlainText(replydata);
}
}
80 Computer Interfacing and Automation

Where remoteslot1() is the name of callbaback function. Give this function definition
outside everything, independent of anything.
In our project, we have created a common Q Byte Array get data (char *) function
called inside every callback function. ‘remote cmd’ is the command given as input,
defined as #defineremotecmd"C1\r" in main window.h.
Now inside the getdata(char *cmmm) function, create a Q Serial Port object and
dynamically initialize it.
QSerialPort *serial2;
serial2=new QSerialPort(this);
serial2->setPortName("com11");
boolaa=serial2->open(QIODevice::ReadWrite);
qDebug()<<aa;
serial2->setBaudRate(9600);
serial2->setDataBits(QSerialPort::Data8);
serial2->setParity(QSerialPort::NoParity);
serial2->setStopBits(QSerialPort::OneStop);
serial2->setFlowControl(QSerialPort::NoFlowControl);
Now set the port parameters and open the port as shown above.
serial2->write(cmm); -> using this command, write the command onto the device.
ba2="";
ba="";
while(ba2!="\r")
{
ba2=serial2->read(1);
serial2->waitForReadyRead(1);
ba=ba+ba2;
}
qDebug()<<ba;
serial2->close();
return(ba);
ba and ba2 both are Q Byte Array. Using the above method read the response from
the device after sending the command. It is reading one character at a time and appending
continuously in ba. This process continues up to it encounters carriage return, i.e. \r.
wait For Ready Read(1) is used to make it wait 1 ms before it reads next character to
make every operation complete improper time.
RS-232 Serial Communication 81

Code for mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QtSerialPort/QSerialPort>
#include <QDebug>
#include <QtSerialPort/QSerialPortInfo>
#include <QIntValidator>
#include <QLineEdit>
#include <QThread>
QByte Array replydata;
QT_USE_NAMESPACE
MainWindow::MainWindow(QWidget*parent):
QMainWindow(parent),
ui(newUi::MainWindow)
{
ui->setupUi(this);
}
/*
voidgetdata2(char*cmm)
{
QSerialPort *serial2;
serial2=new QSerialPort(this);
serial2->setPortName("com11");
serial2->open(QIODevice::ReadWrite);
serial2->setBaudRate(9600);
serial2->setDataBits(QSerialPort::Data8);
serial2->setParity(QSerialPort::NoParity);
serial2->setStopBits(QSerialPort::OneStop);
serial2->setFlowControl(QSerialPort::NoFlowControl);
QByte Array ba;
QByte Array ba2;
ba2.resize(2);
serial2->write(cmm);
ba2="";
ba="";
while(ba2!="\r")
{
82 Computer Interfacing and Automation

ba2=serial2->read(1);
serial2->waitForReadyRead(1);
ba=ba+ba2;
}
qDebug()<<ba;
ui->textEdit->setPlainText(ba);
serial2->close();
}
*/
QByte Array MainWindow::getdata(char*cmm)
{
QSerialPort *serial2;
serial2=new QSerialPort(this);
serial2->setPortName("com11");
bool aa=serial2->open(QIODevice::ReadWrite);
qDebug()<<aa;
//if(!(serial2->isOpen()))
if(!(aa))
return ("Communicationfailure");
serial2->setBaudRate(9600);
serial2->setDataBits(QSerialPort::Data8);
serial2->setParity(QSerialPort::NoParity);
serial2->setStopBits(QSerialPort::OneStop);
serial2->setFlowControl(QSerialPort::NoFlowControl);
QByte Array ba;
QByte Array ba2;
ba2.resize(2);
int bb=serial2->write(cmm);//
qDebug()<<bb;
ba2="";
ba="";
while(ba2!="\r")
{
ba2=serial2->read(1);
serial2->waitForReadyRead(1);
ba=ba+ba2;
}
RS-232 Serial Communication 83

qDebug()<<ba;
//ui->textEdit->setPlainText(ba);
serial2->close();
//QByte Array temp="?";
return(ba);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::vslot1()
{
replydata=getdata(vcmd);
if (replydata[0]=='?')
{
ui->textEdit->setPlainText("error");
}
else
{
ui->textEdit->setPlainText(replydata);
}
//ui->textEdit->setPlainText();
//qDebug()<<replydata;
}
void MainWindow::xslot1()
{
replydata=getdata(xcmd);
if (replydata[0]=='?')
{
ui->textEdit->setPlainText("error");
}
else
{
ui->textEdit->setPlainText(replydata);
}
}
84 Computer Interfacing and Automation

void MainWindow::remoteslot1()
{
replydata=getdata(remotecmd);
if (replydata[0]=='?')
{
ui->textEdit->setPlainText("error");
}
else
{
ui->textEdit->setPlainText(replydata);
}
}
void MainWindow::localslot1()
{
replydata=getdata(localcmd);
if (replydata[0]=='?')
{
ui->textEdit->setPlainText("error");
}
else
{
ui->textEdit->setPlainText(replydata);
}
}

PROJECT 8: INTERFACING AN RS-232 POWER SUPPLY FOR CONTROLLING A


VOLTAGE VALUE VIA. RS-232
RS-232 Serial Communication 85

Process 1: Download manual of Programmable Power Supply for identifying RS-232


command set of GwInSTEK power supply PSP 405 using google, to control power supply
remotely.
Process 2: Download the serial driver of MOXA U1110 converter for windows and install
it on windows to see MOXA device on COMXX in the device manager.
Process 3: Download free python 2.7.13 and then install pyserial by typing “pip install
pyserial” from the dos prompt where pip.exe resides.
Process 4: Note down the most important command “SV 2.00” to remotely set 2 volts
using RS-232, its protocol setting 2400,N,8,1, terminator characters CR and LF.
Process 5: Download and use Tera Term (a free software) to test the above setup (Make
the RS-232 cable using just three wires as shown above) shown above from windows.
Type “SV 2.00” from Tera Term terminal and ensure your setup works and power supply
voltage is set to 2.00 volts. Ensure Tera Term serial port is selected as “COMXX”, protocol
as 2400,N,8,1 and terminal characters as CR and LF and echo ON.
Process 6: Now run the following python program given below to achieve the same
thing to remotely set voltage to 5 volts
Now run the following Python Program to communicate
import serial
 FRQ¿JXUHWKHVHULDOFRQQHFWLRQV WKHSDUDPHWHUVGL๱HUVRQWKH
device you are connecting to)
ser = serial.Serial(
port=’COM18’,
baudrate=2400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.EIGHTBITS
)
if (ser.isOpen() == 0):

ser.open()

input=1
while 1:
input = ‘SV 5.00’ # write voltage 5 volts
# send the character to the device
# (note that I happend a \r\n carriage return and line feed
to the characters - this is requested by my device)
ser.write(input + ‘\r\n’)
out = ‘’
# let’s wait one second before reading output (let’s give
device time to answer)
time.sleep(1)
print “Finished. Writing voltage value to Power supply ....”
86 Computer Interfacing and Automation

PROJECT 9: INTERFACING AN RS-232 TEMPERATURE DEVICE FOR READING


CHANNEL-1 TEMPERATURE DATA

Process 1: Download manual of Lakeshore Temperature monitor model 218 for


identifying RS-232 command set using google to read temperature monitor remotely.
Process 2: Download the serial driver of MOXA U1110 converter for windows and install
it on windows to see MOXA device on COMXX in the device manager.
Process 3: Download free python 2.7.13 and then install pyserial by typing “pip install
pyserial” from the dos prompt where pip.exe resides.
Process 4: Note down the following details given in the tables.
Process 5: Download and use Tera Term (a free software) to test the setup shown above
from windows. Type “KRDG ?1” from Tera Term terminal and ensure your setup (make
the RS-232 cable using just three wires as shown above) works and present temperatue
value from display is read as XXX.XXX Kelvin. Ensure Tera Term serial port is selected
as “COMXX”, protocol as 9600,O,7,1 and terminal characters as CR and LF and echo ON.

Serial Interface Specifications


Connector type: DE-9 D-style connector
Connector wiring: DTE
Voltage levels: EIA RS-232C specified
Transmission distance: 50 feet maximum
Timing format: Asynchronous
Transmission mode: Half duplex
Baud rate: 300, 1200, 9600
Handshake: Software timing
Character bits: 1 start, 7 data, 1 parity, 1 stop
Parity: Odd
Terminations: CR(0DH) LF(0AH)
Command rate: 20 commands per second maximum
ENTER COMMAND? KRDG? 1 Query Kelvin reading for input 1. Monitor
will return a temerature readng in Kelvin.
RS-232 Serial Communication 87

Process 6: Now run the following python program given below to achieve the same
thing by writing “KRDG ?1” to read channel1 temperature on screen.

Now run the following Python Program to communicate


import serial
 FRQ¿JXUHWKHVHULDOFRQQHFWLRQV WKHSDUDPHWHUVGL๱HUVRQWKH
device you are connecting to)
ser = serial.Serial(
port=’COM18’,
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
if (ser.isOpen() == 0):
ser.open()
print ‘Enter your commands below.\r\nInsert “exit” to leave the
application.’
input=1
while 1 :
input = ‘KRDG ?1’
# send the character to the device
# (note that I happend a \r\n carriage return and line feed
to the characters - this is requested by my device)
ser.write(input + ‘\r\n’)
out = ‘’
88 Computer Interfacing and Automation

# let’s wait one second before reading output (let’s give


device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
  SULQW³¿QLVKHGUHDGLQJDPHVVDJH!!´RXW
Process 7: Now run the following labview program given below to achieve the same.
The labview program is freely available from inside any LabVIEW.
Goto help->find examples-> find simple serial.vi
RS-232 Serial Communication 89

FOR FURTHER READING:

PLC & RS-232: How RS-232 can be implemented inside PLC ladder program, is
explained in Chapter 7. You will also find RS-232 & interfacing using multiple languages
in subsequent chapters.

REFERENCES

Ȋȱ Mastering Serial Communications by Peter W. Gofton


Ȋȱ http://www.societyofrobots.com/microcontroller_uart.shtml
Ȋȱ http://www.camiresearch.com/Data_Com_Basics/RS-232_standard.html
Ȋȱ http://claymore.engineer.gvsu.edu/~jackh/books/plcs/chapters/plc_serial.pdf
Ȋȱ http://en.wikipedia.org/wiki/Duplex_(telecommunications)
Ȋȱ http://www.webopedia.com/TERM/H/half_duplex.html
Ȋȱ http://www.edaboard.com/thread97651.html
Ȋȱ http://electronics.stackexchange.com/questions/42727/
what-is-the-difference-between-level-shifter-voltage-regulator-and-DC-DC-conver
Ȋȱ http://airccse.org/journal/jcsit/1010ijcsit09.pdf
Ȋȱ http://www.sqa.org.uk/e-learning/NetTechDC01BCD/page_10.htm
Ȋȱ http://www.radio-electronics.com/info/telecommunications_networks/RS-232/
signals-voltages-levels.php
Ȋȱ http://en.wikipedia.org/wiki/RS-232
90 Computer Interfacing and Automation

Ȋȱ http://www.commfront.com/RS-232_Protocol_Analyzer_Monitor/RS-232_
Analyzer_Monitor_Tester_Tutorial2.htm
Ȋȱ http://www.engineersgarage.com/articles/what-is-RS-232
Ȋȱ http://ecatalog.weg.net/files/wegnet/WEG-cfw-11-RS-232-rs485-serial-
communication-manual-0899.5741-manual-english.pdf
Ȋȱ www.theASCIIcode.com.ar
Ȋȱ Techopedia Dictionary
Ȋȱ Matlab Webserver
Ȋȱ Windmill Software Ltd, Data Acquisition Intelligence.
Ȋȱ University of Wiconsin-Madison, (https://tle.wisc.edu/blend/facilitate/
communicate)
Ȋȱ en.Wikipedia.org
Ȋȱ InetDaemon.com
Ȋȱ Adam Osborne, An Introduction to Microcomputers: Volume 1: Basic Concepts,
Osborne-McGraw Hill Berkeley California USA, 1980, ISBN 0-931988-34-9, pp.
116-126
Ȋȱ Zilog Product specification Z8440/1/2/4, Z84C40/1/2/3/4. Serial input/output
controller. 090529 zilog.com
Ȋȱ FAQ: The 16550A UART & TurboCom drivers 1994. 090529 cs.utk.edu
Ȋȱ T'so, Theodore Y. (January 23, 1999). Re: Serial communication with the 16650.
The Mail Archive. Retrieved June 2, 2013.
Ȋȱ bill.herrin.us - Hayes ESP 8-port Enhanced Serial Port Manual, 2004-03-02
Ȋȱ RS-232 Tutorial on Data Interface and cables. ARC Electronics. 2010. Retrieved 28
July 2011.
Ȋȱ S. Mackay, E. Wright, D. Reynders, J. Park, Practical Industrial Data
Networks:Design,Installation and Troubleshooting, Newnes, 2004 ISBN 07506
5807X, pages 41-42
Ȋȱ Horowitz, Paul; Winfield Hill (1989). The Art of Electronics (2nd ed.). Cambridge,
England: Cambridge University Press. pp. 723–726. ISBN 0-521-37095-7.
Ȋȱ PC 97 Hardware Design Guide. Redmond, Wash: Microsoft Press. 1997. ISBN
1-57231-381-1.
Ȋȱ Wilson, Michael R. (January 2000). TIA/EIA-422-B Overview. Application Note
1031. National Semiconductor. Retrieved 28 July 2011.
Ȋȱ Ögren, Joakim (18 September 2008). Serial (PC 9). Hardware Book. Retrieved 28
July 2011.
Ȋȱ http://controls.ame.nd.edu/microcontroller/main/node24.html
Ȋȱ http://en.wikipedia.org/wiki/RS32#RTS.2FCTS_handshaking
Ȋȱ http://www.radio-electronics.com/info/telecommunications_networks/RS-232/
signals-voltages-levels.php
Ȋȱ http://www.microlink.co.uk/link.html
RS-232 Serial Communication 91

REVIEW QUESTIONS

1. What is the main difference between half-duplex and full-duplex?


2. Out of half-duplex and full-duplex which one consumes more bandwidth during
communication?
3. For what purpose are the level shifters used in communication?
4. What are the main types of level shifters?
5. Now you have a connection to the server from your provider, and you can wander
the Internet. PC is a Data Terminal (DTE). The two modems (yours and the one
of your provider) are DCEs; they make the communication between you and
your provider possible. But now we have to look at the server of your provider.
Is that a DTE or DCE?
6. What is the difference between an RS-232 DTE and DCE port?
7. How can I tell what kind of port my serial device has?
8. What are examples of equipment that has a DTE port?
9. What are examples of equipment that has a DCE port?
10. What is the UART?
11. An interconnection of users that allows communication with one another is known
as a.....
12. RS-232CCOM port in personal computer has....
13. What is RS-232?
14. What is the importance of RS-232-C in serial communication? Name some
applications where you see its use?
15. The full RS-232C standard specifies a ____-pin ‘D’ connector of which 22 pins are
used.
16. Why RS-232 is serial communication?
17. Where is RS-232 needed? Still is it used in PCs?
18. Slow runs at up to 38 400 baud over short distances; lower speeds as the distance
increases owing to capacitance effects.
19. Only one device can be connected to an RS-232 cable. True or false?
20. Computers now rarely have serial ports and a USB-serial (for example) adaptor
may be needed. Discuss.
21. What is the disadvantage of RS-232 communication?

ANSWERS

5) DTE ends the communication line between you and the server although it gives
you the possibility to surf around the globe. Because when you want to go from your
provider server to another place, it uses another interface. So DTE and DCE are interfacing
dependent.
92 Computer Interfacing and Automation

6) The RS-232 spec references two kinds of device, DTE (Data Terminal Equipment)
and DCE (Data Computing Equipment). On DB serial connectors check if Pin 2 is an
input or output. There are different rules for DB25s and DB9s.

DB25:

If Pin 2 is labeled TX and is an OUTPUT the connector is DTE.


If Pin 2 is labeled TX and is an INPUT the connector is DCE.

DB9:

If Pin 2 is labeled RX and is an INPUT the connector is a DTE.


If Pin 2 is labeled RX and is an OUTPUT the connector is a DCE.
This is helpful in most cases, but it is a de facto standard, and it may not always
apply.
7) A rule of thumb for DB9 and DB25 connectors: If it’s male it is likely to be a DTE
if it’s female it's likely to be a DCE.
This is a good place to start if you have no documentation on the serial device. There
are many cases where this does not apply, for instance, most serial printers have a
female DB25 connector, but they are DTEs.
The only way to find out for sure what kind of connector a particular serial device
has is to check its documentation or contact its manufacturer and ask.
In the worst case, you may need to put a breakout box between the Lantronix product
and the serial device and manually swap connections between pins until you find a
connection that works. See the FAQs at the links below for information on common
cable configurations.
8) DTE ports are terminals, printers and the COM ports on a PC.
9) An example of a DCE port is a modem, ISDN adapters, satellites, microwave stations
and network interface cards.
10) The UART, or Universal Asynchronous Receiver / Transmitter, is a feature of
microcontroller useful for communicating serial data (text, numbers, etc.) to your PC.
The device changes incoming parallel information (within the microcontroller/PC) to
serial data which can be sent on a communication line. The UART takes bytes of data
and transmits the individual bits sequentially. At the destination, a second UART
re-assembles the bits into complete bytes.
11) UART
12)
Ȋȱ UART mode communication on serial lines TxD and RxD
Ȋȱ USB and not RS-232C port is used for communication between the mice and
computer
RS-232 Serial Communication 93

Ȋȱ ˜•ŠŽȱ•ŽŸŽ•œȱ˜›ȱ¡ȱŠŠȱ›Š—œ–’œœ’˜—œȱŠ›Žȱƺśȱȱ˜ȱƺŗśȱȱ˜›ȱ•˜’ŒȱŖȱ
Ȋȱ ˜•ŠŽȱ•ŽŸŽ•œȱ˜›ȱ¡ȱŠŠȱ›ŽŒŽ’ŸŽ›ȱŠ›Žȱƺřȱȱ˜ȱƺŘśȱȱ˜›ȱ•˜’ŒȱŖȱ
Ȋȱ Bluetooth device in mobile phone can be connected to the COM port
Ȋȱ Mobile phone Wi-Fi device can be connected to the COM port.
13) It is 3-wire, full-duplex, single-ended, 50”cable limit. RS-232 was developed in the
1960s, and among other things, specified an electrical standard, a protocol standard,
handshaking, and connector pin-out. In general, many current applications for RS-232
use only the electrical standard (3-wires, TDX, RXD, and Common) and connector
pin-out. While handshaking is still with us, it is usually best to disable it in software (if
possible) and/or ‘loop-back’ the pairs of signals (RTS to CTS, DTR to DSR, etc.) While
RS-232 was rumored to be on the ‘way out’ with the advent of many of the new
communications standards, it is still alive and well today. While the standard only
supports low data rates and short line length (50”) it is still widely used and, very useful
in many applications. With an external converter (RS-232<=>RS-485) many of the
limitations of RS-232 can be improved to take advantage of the superior properties of
differential communications (2-wire or 4-wire). The RS-232 interface is the Electronic
Industries Association (EIA) standard for the interchange of serial binary data between
two devices. It was initially developed by the EIA to standardize the connection of
computers with telephone line modems. The standard allows as many as 20 signals to
be defined but gives complete freedom to the user. Three wires are sufficient: send data,
receive data, and signal ground. The remaining lines can be hard wired on or off
permanently. The signal transmission is bipolar, requiring two voltages, from 5 to 25
volts, of opposite polarity.
14) RS-232 stands for Recommend Standard number 232 and C is the latest revision
of the standard. The serial ports on most computers use a subset of the RS-232C standard.
The full RS-232C standard specifies a 25-pin ‘D’ connector of which 22 pins are used.
Most of these pins are not needed for normal PC communications, and indeed, most
new PCs are equipped with male D-type connectors having only 9 pins. In the world
of serial communications, there are two different kinds of equipment:
DTE (Data Terminal Equipment)
DCE (Data Communications Equipment)
15) 25
16) Its speed is higher than parallel communication and less chance of crosstalk in
the data transfer. It can extend up to 50 feet where parallel communication has 2-3 m
distance.
17) When there is no importance for the timing of data to be received or sent, i.e.,
synchronization of time, is used. It is generally used between PCs and printer-like
systems.
18) No. USB model is in practice nowadays because they are simple to handle and
speedier than RS-232.
94 Computer Interfacing and Automation

CHAPTER SUMMARY THRU Q & A

1. What is RS-232? Give a general introduction.


RS-232 was first introduced in 1962 at the radio sector of the EIA. Voltage levels
with respect to ground represents an RS-232 signal. There is a wire for each signal
together with the ground (reference for voltage levels).
The interface is useful for point-to-point communication at slow speed. For
example, PORT COM1 can be used as mouse and PORT COM2 for a modem.
Due to the way the signals are connected, a common ground is required. This
implies limited cable length.

Signal description:
TxD: This pin carries data from the computer to the serial device
RXD: This pin carries data from the serial device to the computer
DTR signals: DTR is used by the computer to signal that it is ready to communicate
with the serial device like a modem. In other words, DTR indicates to the Dataset (i.e.,
the modem or DSU/CSU) that the DTE (computer) is On.
RS-232 Serial Communication 95

DSR: Similar to DTR, Data set ready (DSR) is an indication from the Dataset that it is
On.
DCD: Data Carrier Detect (DCD) indicates that carrier for the transmit data is On.
RTS: This pin is used to request clearance to send data to a modem.
CTS: This pin is used by the serial device to acknowledge the computer’s RTS Signal.
In most situations, RTS and CTS are constantly on throughout the communication
session.
Clock signals (TC, RC, and XTC): The clock signals are only used for synchronous
communications. The modem or DSU extracts the clock from the data stream and
provides a steady clock signal to the DTE. Note that the transmit and receive clock
signals do not have to be the same, or even at the same baud rate.
CD: CD stands for Carrier Detect. CD is used by a modem to signal that it has a made
a connection with another modem, or has detected a carrier tone. In other words, this
is used by the modem to signal that a carrier signal has been received from a remote
modem.
RI: RI stands for Ring Indicator. A modem toggles (keystroke) the state of this line when
an incoming call rings your phone. In other words, this is used by an auto answer
modem to signal the receipt of a telephone ring signal. The Carrier Detect (CD) and the
Ring Indicator (RI) lines are only available in connections to a modem. Because most
modems transmit status information to a PC when either a carrier signal is detected (i.e.
when a connection is made to another modem) or when the line is ringing, these two
lines are rarely used.
The lower picture is when the same input is given to a UART convertor.
Shortcomings of RS-232:
1. It’s impossible to screen a signal on a signal line effectively for noise. Screening
the entire cable one can reduce the outside noise but what do we do with the
internally generated noise? As the baud rate & line length increases the effect of
the capacitances produces crosstalks until the signal becomes unreadable.
2. The interface presumes a common ground for a single-ended signaling that limits
the noise immunity & transmission distance.
3. The large voltage swings and the requirement for positive and negative supplies
increase the power consumption of the interface and complicate power supply
design. The voltage swing requirement also limits the upper speed of a compatible
interface.
4. The handshaking (orderly exchange of electrical signals between DTE and DCE
to achieve the serial communication of bits in the following 3 phases: a) initiate
or establish the session, b) exchange the bits, and c) terminate or disconnect the
session) and control lines of the interface are intended for the setup and take
down of a dial-up communication circuit; in particular, the use of handshake
lines for flow control is not reliably implemented in many devices.
96 Computer Interfacing and Automation

2. What is DTE & DCE?


Data terminal equipment (DTE) is an end instrument that converts user information
into signals or reconverts received signals. These can also be called tail circuits. A DTE
device communicates with the data circuit-terminating equipment (DCE). The DTE/DCE
classification was introduced by IBM. Basically, V.35 is a high-speed serial interface
designed to support both higher data rates and connectivity between DTEs (data-
terminal-equipment) or DCEs (data-communication equipment) over digital lines. Two
different types of devices are assumed to each end of the interconnecting cable for a
case of simply adding DTE to the topology (e.g., to a hub, DCE), which also brings a
less trivial case of interconnection of devices of the same type: DTE-DTE or DCE-DCE.
Such cases need crossover cables, such as for the Ethernet or null modem for RS-232.A
DTE is the functional unit of a data station that serves as a data source or a data sink
and provides for the data communication control function to be performed in accordance
with the link protocol. The data terminal equipment may be a single piece of equipment
or an interconnected subsystem of multiple pieces of equipment that perform all the
required functions necessary to permit users to communicate. A user interacts with the
DTE (e.g., through a human-machine interface), or the DTE may be the user. Usually,
the DTE device is the terminal (or a computer emulating a terminal), and the DCE is a
modem or another carrier-owned device. A general rule is that DCE devices provide
the clock signal (internal clocking), and the DTE device synchronizes with the provided
clock (external clocking). D-sub connectors follow another rule for pin assignment.
Ȋȱ 25-pin DTE devices transmit on Pin 2 and receive on Pin 3.
Ȋȱ 25-pin DCE devices transmit on Pin 3 and receive on Pin 2.
Ȋȱ 9-pin DTE devices transmit on Pin 3 and receive on Pin 2.
Ȋȱ 9-pin DCE devices transmit on Pin 2 and receive on Pin 3.
This term is also generally used in the Telco and Cisco equipment context to designate
a network device, such as terminals, personal computers but also routers and bridges,
that is unable or configured not to generate clock signals. Hence, a PC to PC Ethernet
connection can also be called a DTE to DTE communication. This communication is
done via an Ethernet crossover cable as opposed to a PC to DCE (hub, switch, or bridge)
communication which is done via an Ethernet straight cable.
Data Circuit-terminating Equipment (DCE) is a device that sits between the data
terminal equipment (DTE) and a data transmission circuit. It is also called data
communications equipment and data carrier equipment. Usually, the DTE device is the
terminal (or computer), and the DCE is a modem. In a data station, the DCE performs
functions such as signal conversion, coding, and line clocking and may be a part of the
DTE or intermediate equipment. Interfacing equipment may be required to couple the
data terminal equipment (DTE) into a transmission circuit or channel and from a
transmission circuit or channel into the DTE. A general rule is that DCE devices provide
the clock signal (internal clocking), and the DTE device synchronizes with the provided
clock (external clocking). D-sub connectors follow another rule for pin assignment. DTE
devices usually transmit on pin connector number 2 and receive on pin connector number
3. DCE devices are just the opposite: pin connector number 2 receives and pin connector
number 3 transmits the signals.
RS-232 Serial Communication 97

(b)

3. What is a straight cable?


A straight cable is an RS-232 serial cable where the transmit and receive lines are
connected in a straightforward way.
98 Computer Interfacing and Automation

4. What is Null modem cable?


A null modem cable is an RS-232 serial cable where the transmit and receive lines
are crosslinked. In some cables, there are also handshake lines crosslinked. In many
situations, a straight through serial cable is used, together with a null modem adapter.
The adapter contains the necessary cross links between the signals. The original
application of a null modem was to connect two tele printer terminals directly without
using modems. As the RS-232 standard was adopted by other types of equipment,
designers needed to decide whether their devices would have DTE-like or DCE-like
interfaces. When an application required that two DTE's (or two DCE's) needed to
communicate with each other, then a null modem was necessary. Null modems were
commonly used for file transfer between computers, or remote operation.

5. What are voltage levels at the RS-232 output?


(a) +12 & –12 V
The RS-232 standard defines the voltage levels that correspond to logical one and
logical zero levels for the data transmission and the control signal lines. Valid signals
are either in the range of +3 to +15 V, or the range –3 to –15 V; the range between
–3 to +3 V is not a valid RS-232 level. Data signals and control signals use opposite
polarity to represent a ‘true’ or logic 1 asserted state. For data transmission lines (TxD,
RxD, and their secondary channel equivalents) logic one is defined as a negative voltage,
the signal condition is called marking. Logic zero is positive, and the signal condition is
termed spacing. Control signals have the opposite polarity; the asserted state is a positive
RS-232 Serial Communication 99

voltage, and the inactive state is a negative voltage. Examples of control lines include
a request to send (RTS), clear to send (CTS), data terminal ready (DTR), and dataset
ready (DSR).The standard specifies a maximum open-circuit voltage of 25 volts: signal
levels of ±5 V, ±10 V, ±12 V, and ±15 V are all commonly seen depending on the voltages
available to the line driver circuit. Some RS-232 driver chips have inbuilt circuitry to
produce the required voltages from a 5 V supply. RS-232 drivers and receivers must be
able to withstand indefinite short circuit to ground or any voltage level up to ±25 V.
The slew rate, or how fast the signal changes between levels, is also controlled. Because
the voltage levels are higher than logic levels typically used by integrated circuits, special
intervening driver circuits are required to translate logic levels. These also protect the
internal circuitry of the device from short circuits or transients that may appear on the
RS-232 interface and provide sufficient current to comply with the slew rate requirements
for data transmission. Because both ends of the RS-232 circuit depend on the ground
pin being 0 V, problems will occur when connecting machinery and computers where
the voltage between the ground pin on one end and the ground pin on the other end
are not zero. This may also cause a hazardous ground loop. Use of a common ground
limits RS-232 to applications with relatively short cables. If the two devices are far
enough apart or on separate power systems, the local ground connections at either end
of the cable will have differing voltages; this difference reduces the noise margin of the
signals. Balanced, differential, serial connections such as USB, RS-422 and RS-485 can
tolerate larger ground voltage differences because of the differential signaling. Unused
interface signals terminated to ground will have an undefined logic state. Where it is
necessary to set a control signal permanently to a defined state, it must be connected
to a voltage source that asserts the logic 1 or logic 0 level. Some devices provide test
voltages on their interface connectors for this purpose.
6. What is the meaning of 9600,N,8,1 in RS-232?
9600=baud rate, the baud rate is the total number of bits (information, overhead, and
idle) per time that is transmitted over the serial link. So we can compute the baud rate
as the reciprocal of the bit time.
N=null parity
8=data bits
1=stop bit
7. What is start, stop & parity bit in RS-232?
In asynchronous serial protocols such as RS-232, the frame consists of one start bit,
seven or eight data bits, parity bits, and stop bits. The start bit is used to signal the
beginning of a frame, and the stop bit is used to signal the end of a frame. The only bit
that probably needs a bit of explanation is the parity bit. Parity is used to detect
transmission errors. For even parity checking, the number of 1’s in the data plus the
parity bit must be an even number. For odd parity, this sum must be an odd number.
Parity bits are used to detect errors in transmitted data. Before sending out a frame, the
transmitter sets the parity bit so that the frame has either even or odd parity. The receiver
and transmitter have already agreed upon which type of parity check (even or odd) is
used. The bit time is the basic unit of time used in serial communication. It is the time
between each bit. The transmitter outputs a bit, waits one-bit time and then outputs the
100 Computer Interfacing and Automation

next bit. The start bit is used to synchronize the transmitter and receiver. After the
receiver senses the true-false transition in the start bit, it waits one half bit time and
then starts reading the serial line once every bit time after that.
8. Why is RS-232 an asynchronous communication system?
In program-to-program communication, synchronous communication requires that
each end of an exchange of communication responds in turn, without initiating a new
communication. A typical activity that might use a synchronous protocol would be a
transmission of files from one point to another. As each transmission is received, a
response is returned indicating success or the need to resend. In synchronous transmission,
we send bits one after another without start or stop bits or gaps. It is the responsibility
of the receiver to group the bits.

The term asynchronous is usually used to describe communications in which data


can be transmitted intermittently rather than in a steady stream. For example, a telephone
conversation is asynchronous because both parties can talk whenever they like. If the
communication were synchronous, each party would be required to wait a specified
interval before speaking. The difficulty with asynchronous communications is that the
receiver must have a way to distinguish between valid data and noise. In computer
communications, this is usually accomplished through a special start bit and stop bit at
the beginning and end of each piece of data. For this reason, asynchronous communication
is sometimes called start-stop transmission. Asynchronous here means ‘asynchronous
at the byte level’, but the bits are still synchronized; their durations are the same.
RS-232 Serial Communication 101

9. What is the maximum length & speed of RS-232?


(a) The maximum speed, according to the standard, is 20 kbit/s. However, modern
equipment can operate much faster than this. (i.e., Lynx can reach 115200 baud.)
(b) The length of the cable also plays a part in maximum speed. The longer the cable
and the slower the speed at which you can obtain accurate results. A large wire
capacitance and inductance limit the maximum length of the cable and/or the
maximum speed. Moreover, higher is the capacitance of the cable higher is the
interference between two adjacent signal wires. Fifty feet (15 m) @ max baud rate
is commonly quoted as the maximum distance. It is not specified in EIA standard,
but it is recommended respect these values.
(c) By using low-capacitance cables, full speed communication can be maintained
over larger distances up to about 1,000 feet (300 m). For longer distances, other
signal standards are better suited to maintain high speed.
10. What is UART?
The USART (Universal Synchronous/Asynchronous Receiver Transmitter) is used for
synchronous and asynchronous serial communication. . Our focus will be on asynchronous
serial communication. Asynchronous communication does not use a clock to validate
data. Serial data is transferred one bit at a time. Asynchronous serial interfaces are cheap,
easy to use, and until recently very common. USB is well on its way to replace the serial
comm ports on PCs. The USART communicates in a full-duplex mode (simultaneous
xmit, rcv).
The figure below shows the relationship between the various components in a serial
ink. These components are the UART, the serial channel, and the interface logic. An
interface chip known as the universal asynchronous receiver/transmitter or UART is
used to implement serial data transmission. The UART sits between the host computer
and the serial channel. The serial channel is the collection of wires over which the bits
are transmitted. The output from the UART is a standard TTL/CMOS logic level of 0
or 5 V. To improve bandwidth, remove noise, and increase range; this TTL logical level
is converted to an RS-232 logic level before being sent out on the serial channel. This
conversion is done by the interface logic shown in the figure below. In your system, the
interface logic is implemented by the comm stamp.

Asynchronous (RS-232) serial link


102 Computer Interfacing and Automation

A frame is a complete and non-divisible packet of bits. A frame includes both


information (e.g., data and characters) and overhead (e.g., start bit, error checking and
stop bits). In asynchronous serial protocols such as RS-232, the frame consists of one
start bit, seven or eight data bits, parity bits, and stop bits. A timing diagram for an
RS-232 frame consisting of one start bit, 7 data bits, one parity bits and two stop bits is
shown below. Note that the exact structure of the frame must be agreed upon by both
transmitter and receiver before the comm link must be opened.

RS-232 frame (1 start bit, 7 data bits, 1 parity bits, and 2 stop bits)

Most of the bits in a frame are self-explanatory. The start bit is used to signal the
beginning of a frame, and the stop bit is used to signal the end of a frame. The only bit
that probably needs a bit of explanation is the parity bit. Parity is used to detect
transmission errors. For even parity checking, the number of 1’s in the data plus the
parity bit must be an even number. For odd parity, this sum must be an odd number.
11. Why is RS-232 a full-duplex?
Full-duplex transmission (FDX) occurs when data is transmitted (or can be transmitted)
simultaneously by both devices. Special wiring is needed for FDX.

12. Can RS-232 be half-duplex?


Half-duplex Transmission (HDT) means when data is transmitted (or can be
transmitted) after the job is done by one device. Full-duplex means communication can
go in both directions. 'Full' when send/receive can occur simultaneously, 'Half' when
this is not possible, for whatever reason.
13. What is FPGA? Give a general introduction.
14. Draw the four clocking methods of SPI. & explain.
15. Give an example of RS-232 data collection, in C++ language, using a PC from
a device? Use linSerial class.
16. Following firmware generates the string ‘hello’ on a small serial character
display. Explain each line. (Use ARM MBED 1768)
#include”MBED.h”
Serial device(p28,p27);// tx,rx of nmicroprocessor
RS-232 Serial Communication 103

Int main(){
Device.baud(9600);// baud set as 9600
Device.format(8,serial::Odd,1);
Int delaycounter;
For(;;)
{
Wait(0.25);
Device.printf(“hello\n”); //printing “”hello” terminated by
\n(CR)
}
}
17. Draw the four clocking modes in SPI & explain.
The SPI bus protocol includes four modes. These modes determine the relationship
between the serial clock and the data bits. Many common microcontrollers contain
built-in hardware SPI ports. Some of these controllers make the SPI mode fully
programmable; others allow a more limited selection. To have direct compatibility with
the FM25160, the user should select Mode 0. In the SPI configuration register (if any)
for the controller, this requires setting the CPOL bit to 0 and the CPHA bit to 0. The
four modes are illustrated below. In some cases, users will be emulating the SPI protocol
in software using general-purpose port pins. In this case, the software can be written to
manipulate the port pins to achieve the correct relationship.
Note: in the case of a microcontroller host that has port pins with a default high state,
it will be necessary to set the SCK pin to low state manually prior to beginning a
transaction.
The desired relationship for Mode 0 is illustrated below. To highlight the differences,
Modes 1 through 3 are also shown.
104 Computer Interfacing and Automation

SPI modes
LABVIEW PROGRAMMING BASICS FOR CONTROL
2 GRAPHICAL USER INTERFACE (GUI) DESIGN

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ What is LabVIEW®
Ȋȱ Creating arrays
Ȋȱ What is control file in LabVIEW
Ȋȱ What is HTTP client
Ȋȱ What is HTTP server
Ȋȱ What is semaphore

2.1 INTRODUCTION: WHY LABVIEW?

Think of an instrument manual of real temperature PID controller sold in market


with model SELEC PID-300-–3-00-00 where a user has to press button by button to
operate. Isn’t it tedious? This is why we need user-friendly GUIs for easy operation by
computers.
The manual button-pressing example of SELEC device to use it as a temperature
controller:
Programming SELEC PID 300-3-0-00 DEVICE manually, very difficult!!!
Ȋȱ Press and hold + buttons for 3 seconds.
Ȋȱ A new menu will open displaying “LEVL.”
Ȋȱ Hold button and press or button to change the level numbers.
Ȋȱ In Level “0”, press
Ȋȱ Choose Input type (Thermocouple/PT100 or RTD, Refer manual). Hold button
and press or buttons to change the parameter value.
Ȋȱ Press : the display shows “RESL”. Choose the resolution by + /
Ȋȱ Press again: the display shows the next parameter “TEMP”, i.e. Temperature.
Choose °C or °F by pressing + / e.g. °C
Ȋȱ Press again: the display shows the next parameter “SPHL” (Set Point High
Limit). Set the Set point High Limit by + / e.g. 100 (must not exceed the
upper-temperature limit for the safe working of the sensor that is used).
106ȳComputer Interfacing and Automation

Ȋȱ Press again: the display shows the next parameter “SPLL” (Set point Low Limit).
Set the Set point Low limit by + / e.g. 0 (must not exceed the Lower
temperature limit for the safe working of the sensor that is used).
Ȋȱ Press again to go back to level selection, the display shows “LEVL” again
Ȋȱ Now Hold button and press till the display shows LEVEL 4.
Ȋȱ Press till the display shows “MAIN” (main output).
Ȋȱ Now Hold button and press to select “RLY2” for analog transmission.
Ȋȱ Now press till the display shows “LEVL” again. Hold button and press
till the display shows LEVEL 2.
Ȋȱ Press to select the parameter “A-LO” (Analog Low Scaling). Set the low end of
the input signal by + / . (Here according to the previously chosen examples
the Low-end limit of the input signal will be 0).
Ȋȱ Press to select the parameter “A-HI” (Analog High Scaling). Set the High end
of the input signal by + / . (Here according to the previously chosen
examples the High end of the input signal will be 100).
x Press and hold + buttons for 3 seconds to exit the menu.

2.2 LabVIEW COMES TO RESCUE

LabVIEW stands for Laboratory Virtual Instrumentation Engineering Workbench. It is


a platform and development environment for a visual programming language from
National Instruments. The graphical language on which it works is called the “G”
language. While working on a LabVIEW one can virtually create buttons, arrays, meters
and graphs directly on the screen and use them to control the instruments of your
requirement and along with that, we can also perform automation of all the instruments.
LabVIEW also facilitates engineers and scientists to acquire online data and plot the
corresponding graphs at the time of data collection. In practice, we can work on LabVIEW
very fast and efficiently.
In this chapter, basic demonstration of LabVIEW programming is done.

2.2.1 Data flow Programming

The execution of a particular program is determined by the structure of a graphical


block diagram on which the programmer connects different functional nodes by drawing
wires. These wires propagate variables, and any node can execute as soon as all its input
data become available.

2.2.2 Graphical Programming

The graphical approach also allows non-programmers to build programs simply by


dragging and dropping virtual representations of lab equipment with which they are
already familiar.
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ107

The LabVIEW programming environment, with the included examples and the
documentation, makes it simple to create small applications.

STEP 1

After Clicking on Blank VI, we will get three panels called Front Panel, Block Diagram,
and Tool Palette (see Fig. 2.1, Fig. 2.2, Fig. 2.3).
On the Front Panel, we can add toggle switches, wave charts, waveform graphs and
other user interface entities which are visible while the program is continuously running
(see Fig. 2.2).
The block diagram panel contains the logic on which the program is running that
encompasses all the “for loop”, “while loop”, “case structure”, “sequence structure”,
“event structure”, etc. (see Fig. 2.3).
All these above-mentioned functions will be demonstrated in this project report and
properly put to use while carrying out simple programming.
108ȳComputer Interfacing and Automation

Figure 2.1 Tool palette Figure 2.2 Front panel

Figure 2.3 Block diagram

You can switch between Front Panel and Block Diagram by using Ctrl-E command.
On Front Panel, we can add buttons, LED-indicators, etc. and on the Block Diagram
panel we will see its equivalent block diagram consisting of for loop (see Fig. 2.4).
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ109

Figure 2.4

Let us see, on selecting Numeric Controls how they occur in our two panels. Our
Front Panel will be like the one as shown below (see Fig. 2.5):

Figure 2.5

And its corresponding Block Diagram is shown below.

Figure 2.6
110ȳComputer Interfacing and Automation

Now we will start with some basic examples of simple programs that comprise
simultaneous functioning of numeric indicators, LED-indicators, etc.

2.3 BASIC EXAMPLE OF LABVIEW


2.3.1 Program for Changing two Indicators Simultaneously

In the above example add a numeric indicator slide indicator and a tank indicator. Then,
we join all of them and observe that the value will change simultaneously in all of them
(see Fig. 2.7).
We select a Numeric Control: it can easily be changed to a Numeric Indicator by a
right-click on the object and selecting Change to Indicator.

Figure 2.7
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ111

Now to make all these indicators to show the same reading, we have to wire them
together in the Block Diagram panel, and the connections which we will do will not be
visible on the above-displayed screen (see Fig. 2.8).

Figure 2.8 Block Diagram

Now when we run the program: the values in all the indicators will be changed
simultaneously (see Fig. 2.9).

Figure 2.9 Output File


112ȳComputer Interfacing and Automation

2.3.2 Program for using For Loop to Change Value 1-10 Automatically

Figure 2.10

Here we put all our indicators inside the for loop, and all of them are connected to
Iteration i. of the for loop is given a value of N = 10. This will simply change the value
continuously from 1 to 10. To see the changes in real-time, we have to allow a delay of
1000 milliseconds see Fig. 2.10).

2.3.3 Program for 2-D Array Creation

Here we have used two For Loops, one loop inside another, and given a delay of 100
milliseconds, as shown in the below block diagram (see Fig. 2.11):

Figure 2.11
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ113

Its corresponding Front Panel is as shown below (see Fig. 2.12):

Figure 2.12

2.3.4 Program for Making Array Indicator

Here array is made without using a for loop, and it is then used as a control switch
to glow LED-switches and some other indicators (see Figs. 2.13 and 2.14).
The block diagram is shown below:

In the block diagram there are 4


arrays out of them array 1 and 4
are control arrays and 2 and 3 are
there corresponding indicators.

Figure 2.13
114ȳComputer Interfacing and Automation

The Front Panel is shown below:

Here Array 1 and Array 2 are


connected as similar reading of 1,
4 and 9 is showing on the vertical
indicator.

Array 4 act as group of toggle


switches and array 3 as the LED
bulbs that can be switched on and
off by the toggle switches.

Figure 2.14

2.3.5 Program for Adding two Numbers and Subtracting a Constant Value from it

This example shows a block diagram that adds two numbers and then subtracts 50 from
the result. The program executes from left to right because the subtract function cannot
be executed until the addition function is over. The block diagram is given below (see
Fig. 2.15):

Figure 2.15
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ115

The Front Panel will show the two values it has to have a control numerical and one
indicator that will show the results (see Fig. 2.16).

Figure 2.16

2.3.6 Program for Temperature Conversion from ºF to ºC

For this, we use one multiplication, one division and one subtraction function to first
calculate it mathematically and then make the temperature in ºF as control and
temperature in °C. The block diagram is given below (see Figs. 2.17 and 2.18):

Figure 2.17
116ȳComputer Interfacing and Automation

The Front Panel is shown below:

Figure 2.18

2.3.7 Program for use of Case Structure that Consists of Condition of True and False
The Bock Diagrams are given below:
True Condition False Condition

Figure 2.19
The Front Panels are given below:

Figure 2.20
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ117

Here, by implementing the case structure, we have the choice to make a particular
part of program to work by giving it a True condition and switching on that condition
with the help of a toggle switch (Boolean) see Figs. 2.19 and 2.20).

2.3.8 Program to Demonstrate between Waveform Graphs and Charts

Figure 2.21

A waveform chart is a simple graph plot 1-D entity with respect to time: in other
words, a single numeric value that is changing with time. On the other hand, waveform
graph needs an array to do that. The Front Panel is given below (see Figs. 2.21 and 2.22):
The block diagram is given below:

Figure 2.22

2.3.9 LabVIEW Program to Create an Array using Random Number and for Loop

Here we place a random number generator inside the for loop and create an array
and see its output in waveform graph. The block diagram is given below (see Figs. 2.23
and 2.24):
118ȳComputer Interfacing and Automation

Figure 2.23

The Front Panel is given below:

Figure 2.24

2.3.10 Program that Makes Use of While Loop to Switch-on the LED

Here, the while loop will run until the stop button is pressed or the logic condition is
satisfied. The block diagram is given below (See Figs. 2.25 and 2.26):
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ119

Figure 2.25

The Front Panel is given below:

Figure 2.26

2.3.11 Program to Demonstrate the Function of a Flat Sequence Structure

Sequence structures are there to execute parts of the program one after the other from
left to right. The block diagram is given below (see Figs. 2.27 and 2.28):
120ȳComputer Interfacing and Automation

Figure 2.27

The Front Panel is shown below.

Figure 2.28

2.3.12 Program to Demonstrate the Function of Case and Flat Sequence Structures
Together

Here, by using case structure and flat sequence together along with the functioning of
a local variable, LEDs will be on one by one. Local variables play a significant role as
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ121

they actually control the switch only purposefully, placed in the other case to put-off
the LED 2 and LED 3 when LED 1 is on. The block diagram is shown below (see Figs.
2.29 and 2.30):

Figure 2.29

The Front Panel is shown below.

LED 1
LED 1 LED 1

Sequence switch
Sequence switch Sequence switch
LED 2 LED 2
LED 2

LED 3 LED 3
LED 3

Figure 2.30

Here local variables of LED 1 and LED 2 are used with a constant F that helps us
achieving this sequence, and it is this logic only which is used in traffic signals.

2.3.13 Program that Executes all the Functions Using Stacked Sequence

Flat sequences occupy a lot of space which is not useful for graphical programming. To
overcome that problem we use stacked sequence that will work exactly like the above
program. The block diagram is shown below (see Fig. 2.31):
122ȳComputer Interfacing and Automation

Figure 2.31

Here all the three previous programs’ flat sequence frames are grouped into one stack,
and its output is the same as we can see below in the Front Panel (see Fig. 2.32).

Front panel
LED 1
LED 1 LED 1
Sequence switch
Sequence switch Sequence switch
LED 2 LED 2
LED 2

LED 3 LED 3
LED 3

Figure 2.32

2.3.14 Program that Demonstrates the Use of Tab Container that Solves Similar
Purpose as that of Stacked Structures in Block Diagram Panel

Using tab container in Front Panel saves space on it and makes it very convenient to see
the entire control and display panel in a single screen, and that facilitates to change it as
and when required. The Front Panel and block diagram are shown below. (see Fig. 2.33)
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ123

Figure 2.33

2.3.15 Program that Demonstrates the Functioning of Event Structure

We will have to wait until an event occurs and then execute the appropriate case to
handle that event. The event structure has one or more sub-diagrams, or event cases,
exactly one of which executes when the structure executes to handle an event. These
structures can time out while waiting for the notification of an event. Wire a value to
the Timeout terminal at the top left of the event structure to specify the number of
milliseconds the event structure will have to wait for an event. The default is -1, which
indicates never to time out. The block diagram is given below (see Fig. 2.34):
Here, we have added A and Aprev by making use of a feedback loop, and we put
the whole logic in an event structure inside a while loop. As we placed it inside the
event structure, the while loop will not be able to stop the VI by pressing the Esc button,
124ȳComputer Interfacing and Automation

so, to achieve that we have added another structure to the same event structure and
placed out Esc button there. Now when we press the Esc button, the VI will stop
immediately.

Figure 2.34

Event structure can also fix the amount of duration a particular program should work
and again reset it to the initial condition after that duration. The Front Panel is shown
below (see Fig. 2.35):

Figure 2.35

Here, the Numeric indicator will restart from one after 250 milliseconds, or it will
restart every time we press the Esc button.
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ125

2.4 BASIC SEMAPHORE: INTRODUCTION

A semaphore is a way to limit the number of tasks that can simultaneously operate on
a shared (protected) resource. A protected resource or critical section of code might
include writing to global variables or communicating with external instruments. A
semaphore is similar to a MUTEX (mutual exclusion object) in other programming
languages.
It is useful for protecting two or more critical sections of code that should not be
called concurrently. Before entering a critical section, the thread must acquire a
semaphore. If no thread is already in the critical section, the thread proceeds to enter
that part of the diagram immediately. This thread must release the semaphore once the
critical section is complete. Other threads that want to enter the critical section must
wait until the first thread releases the semaphore.

Figure 2.36

To accomplish this, we create a semaphore and then place the Acquire Semaphore
and Release Semaphore VIs at the beginning and end, respectively, of each critical
section. Then each sub-VI can obtain and release the semaphore one at a time to assure
proper data control. At the end of the section use the Release Semaphore Reference VI
and stop the sub-VIs (see Fig. 2.36).

2.5 Ctl FILE IN LABVIEW

'Ctl' is the file type of LabVIEW controls. Controls are stored either in their parent VI
or in dedicated files. The latter helps to define similar controls on different VIs.
Type definitions in LabVIEW are a powerful tool for defining controls and indicator
data type in the program. A type definition, often called typedef in short, is a LabVIEW
custom control file (.ctl) that is configured to act as a “master in template” for the data
type of slave controls that have been linked to the typedef.
Type definitions are just one kind but the most important in LabVIEW custom controls.
The other kinds are “controls” proper and “strict type definitions.” A strict type definition
is like type definitions except that it also forces the appearance, and not just the data
type, of its linked controls to stay the same.
126ȳComputer Interfacing and Automation

In general, we should always use typedefs in our applications for controls that are
about to be reused in the program further. It will save hours of work and time and also
make our code easier to maintain.

2.6 ADVANCED HTTP SERVER LIBRARY COMES WITH LABVIEW BY DEFAULT

HTTP stands for Hyper Text Transfer Protocol. Many applications run concurrently over
the web, such as web browsing/surfing, e-mail, file transfer, audio and video streaming,
and so on. For proper communication to take place between the client and the server,
these applications must agree on a specific application-level protocol such as HTTP,
FTP, SMTP, POP, etc. (see Fig. 2.37).

Figure 2.37

HTTP is perhaps the most popular application protocol used on the Internet (or the
web) (see Fig. 2.38).
1. HTTP is an asymmetric request-response client-server protocol. An HTTP client
sends a request message to an HTTP server. The server, in turn, returns a response
message. In other words, HTTP is a pull protocol; the client pulls information
from the server (instead of server pushes information down to the client).
2. HTTP is a stateless protocol. In other words, the current request does not know
what has been done in the previous requests.
3. HTTP permits negotiating of data type and representation, so as to allow systems
to be built independently of the data being transferred.
4. Quoting from the RFC2616: “The Hypertext Transfer Protocol (HTTP) is an
application-level protocol for distributed, collaborative, hypermedia information
systems. It is a generic, stateless, protocol which can be used for many tasks
beyond its use for hypertext, such as name servers and distributed object
management systems, through the extension of its request methods, error codes,
and headers.”
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ127

Figure 2.38

Whenever we issue an URL from our browser to get a web resource using HTTP,
e.g. http://www.test101.com/index.html, the browser turns the URL into a request message and
sends it to the HTTP server. The HTTP server interprets the request message and returns
an appropriate response message, which is either the resource you requested or an error
message.
This process is illustrated below:
Whenever we enter an URL in the address box of the browser, the browser translates
the URL into a request message according to the specified protocol; and sends the request
message to the server (see Figs. 2.39).

Figure 2.39

For example, the browser translates the URL http://www.test101.com/doc/index.html into


the following request message:
128ȳComputer Interfacing and Automation

When this request message reaches the server, the server can take either one of these
actions:
1. The server interprets the request received, maps the request into a file under the
server's document directory, and returns the file requested to the client.
2. The server interprets the request received, maps the request into a program kept
on the server, executes the program, and returns the output of the program to
the client.
3. The request cannot be satisfied; the server returns an error message.
An example of the HTTP response message is:

The browser receives the response message, interprets the message and displays the
contents of the message on the browser's window according to the media type of the
response (as in the Content-Type response header). Common media type include “text/
plain’, “text/html”, “image/gif”, “image/jpeg”, “audio/mpeg”, “video/mpeg”, “application/
msword”, and “application/pdf”.
In its idle state, an HTTP server does nothing but listens to the IP address(es) and
port(s) specified in the configuration for the incoming request. When a request arrives,
the server analyzes the message header, applies rules specified in the configuration and
takes the appropriate action. The webmaster's main control over the action of the web
server is via the configuration, which will be dealt with in greater details in the later
sections.

2.6.1 HTTP over TCP/IP

HTTP is a client-server application-level protocol. It typically runs over a TCP/IP


connection, as illustrated below. (HTTP need not run on TCP/IP. It only presumes a
reliable transport. Any transport protocols that provides such guarantees can be used.)
(see Fig. 2.40)
Š‹ ȱ ›˜›Š––’—ȱ Šœ’Œœȱ ˜›ȱ ˜—›˜•ȱ ›Š™‘’ŒŠ•ȱ œŽ›ȱ —Ž›ŠŒŽȱ ǻ  Ǽȱ Žœ’—ȳ129

Figure 2.40

REFERENCES

1. http://home.hit.no/~hansha/documents/labview/training/Introduction%20to%20
LabVIEW/Introduction%20to%20LabVIEW.pdf
2. http://zone.ni.com/reference/en-XX/help/371361H-01/lvconcepts/
custom_cont_ind_type/
3. http://labviewwiki.org/Ctl
4. http://flylib.com/books/en/3.352.1.164/1/

REVIEW QUESTIONS

1. On which language is the LabVIEW programming based?


2. State the difference between the functioning of for loop and while loop?
3. State the difference between case structure and flat structure?
4. What are the advantages of using stacked structure?
5. What are local variables and how are they used?
6. What is .ctl file and what are the advantages of using it?
7. What are semaphores?
8. What is the HTTP client?
9. What is the HTTP server?

ANSWERS

1. LabVIEW programming is based on “G” language.


2. For loop runs for the time till the condition is satisfied but in the case of while
loop it runs indefinitely till the stop button is hit.
130ȳComputer Interfacing and Automation

3. Case structures are Boolean in nature that have TRUE & FALSE cases stacked
into a single structure on which the program code can be written. In case of flat
structures, they are simple structures which ensure that one set of the code is
run before the other, and it runs from left to right.
4. Stacked structure is similar to flat structure but here all the flat structures are
stacked into one structure; here the advantage is that it occupies very less space
on the VI, complete code can be seen, and modified easily.
5. Local variables are the alternative controls of the control variables which can be
placed away from them in some different stacks as per the requirement of the
program.
6. 'Ctl' is the file type of LabVIEW controls. Controls are stored either in their parent
VI or in dedicated files. The latter helps to define similar controls on different
VIs.
7. A semaphore is a way to limit the number of tasks that can simultaneously operate
on a shared (protected) resource. A protected resource or critical section of code
might include writing to global variables or communicating with external
instruments.
8. Whenever we issue a URL from your browser to get a web resource using HTTP,
e.g. http://www.google.com/index.html, the browser turns the URL into a request
message, and we are designated as HTTP client.
9. The HTTP server interprets the request message and returns an appropriate
response message, which is either the resource you requested or an error message.
MICROCONTROLLER-BASED EMBEDDED
3 DESIGN: HARDWARE ENGINEERING

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋ Microprocessors and Microcontrollers architecture and the difference between
them.

3.1 MICROPROCESSOR
A microprocessor is a small computer or CPU (central processing unit) that is used to
do arithmetic and logical operations, controlling the system and storing the data, etc.
The microprocessor processes the data of the input/output peripherals and gives the
results back to them to function. The first commercial microprocessor was released by
Intel in 1971 November named as 4004. It is a 4-bit microprocessor. But the first
microprocessor was developed by Garrett Research in 1968. Block diagram of a
microcontroller is shown below (see Fig. 3.1).

External Interrupt Counter Input

Interrupts 4k 128 Timer 1


Control FLASH RAM Timer 0

CPU

Bus Bus
Osc. 4 I/O Port
Control Control

P0 P2 P1 P3
Address/data
Figure 3.1 Block diagram of a microcontroller

The initial microprocessor used the Von Neumann architecture. In this architecture,
the data memory and program memory are placed in one memory. If the processor
wants to process an instruction from the memory or request from the I/O, it has to get
132ȳComputer Interfacing and Automation

the instruction through a bus from the memory or I/O, place it in the registers and
process it in the registers. The processor can save the result in the memory through the
bus. But this architecture has some drawbacks such as it is slow and data operations
cannot occur at the same time because they share the same common bus. Later Harvard
architecture was developed. In the Harvard architecture, the data memory and program
memory are placed as separate memory, and separate buses are connected to communicate
with each other. Microprogramming is slow in comparison to hardwired programming.
Hardwired implementation is mainly of logic gates and passive elements. Microcode is
used in microprogramming (see Fig. 3.2).

Figure 3.2 (a) Von Neumann architecture; (b) Harvard architecture

The instruction set architecture (ISA) also plays an important role in the microprocessors.
There are different instructions set architecture microprocessors available as given
below.
1. Complex Programming Instruction Set Computer: In the complex instruction set
computer (CISC) instruction set has complex instructions which take a long
time to execute; complex instructions may consist of op code addressing mode
operand, etc. The execution speed is slow. The X86 architecture is an example.
2. Reduced Instruction Set Computer (RISC): In the RISC the instruction set is small
and execution speed is fast. The implementation is simple and does not require
complex architecture. RISC is widely used in embedded applications. SHARC
and POWER PC uses RISC.
There are other architectures like Very Long Instruction Word (VLIW) and fusion of
RISC and CISC architecture, etc.
The microprocessor should be chosen according to the application: for small
applications, you don’t need CISC. You cannot use RISC for a large application. A
microprocessor should be selected according to the application and peripherals.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ133

3.2 MICROCONTROLLER

It is also a small computer in which CPU, a memory unit (RAM and ROM), I/O
peripherals, timers, and counters are embedded in one integrated circuit (IC) whereas
in a microprocessor all these units are combined on a board through buses. The
microcontroller can be interfaced easily to external peripherals like serial ports, ADC,
DAC, Bluetooth, Wi-Fi, etc. The interfacing process is fast when compared to the
microprocessor interfacing. Most of the microcontrollers use the RISC architecture. There
are also some microcontrollers which use the CISC architecture, like 8051, Motorola, etc.
(see Fig. 3.3).

Figure 3.3 A typical microcontroller schematic

3.2.1 Differences between Microprocessor and Microcontroller

1. Architecture: Most of the microprocessors use CISC and Von Neumann


architecture. Their microprocessors used Harvard and RISC as well. But
commonly microprocessors use CISC whereas microcontrollers use the RISC and
Harvard architecture. But there are some microcontrollers that use the CISC
architecture, like 8051 and SHARC. A microprocessor has ROM, RAM, secondary
storage memory I/O peripherals, timers; counters, etc. placed on a board and
connected through buses whereas in the microcontroller all these peripherals are
combined in a single integrated circuit (IC).
2. CPU Speed: Processors have more speed than controllers because of the clock.
Processors can have a high clock rate, even if they become heated. Due to high
clock rate the heat sink stops from overheating. Controllers may be slow when
compared to the processors, but they are reliably fast. The execution speed always
depends upon the clock. If we take the overall performance and application
execution speed microcontrollers are faster because all the peripherals are inbuilt.
Processors are slow because they get every resource from outside of the CPU
through buses.
3. Design Time: The design of an application microcontroller takes less time when
compared to the processor. The interfacing between the peripherals and
programming them is easier when compared to processors.
134ȳComputer Interfacing and Automation

4. Protection: If you programmed the microcontroller it is hard to get the program


from the ROM by other users. The ROM is locked, and it is very hard to retrieve
the program from the ROM of the microcontroller. The processor does not give
that much protection to its program.
5. Cost: The cost of microprocessors and implementing microprocessor-based
systems is costly when compared to the microcontroller based system. The
microprocessor system will never be a compact system. Most of the microcontroller
based systems are compact systems.
6. Applications: Processors are mainly used in computation systems, defense
systems, network communications, etc. Microcontrollers are mainly used in
embedded applications like watches, cellphone, mp3 player, etc.
Whatever is the difference between controllers and processors, processors cannot be
replaced by controllers and controllers cannot be replaced by processors. Each of them
has a unique way of usage in application development.

3.2.2 Comparison of Microcontroller and Microprocessor


Microcontroller

1. Microcontroller has inbuilt RAM or ROM and inbuilt timer.


2. Input and output ports are available.
3. Inbuilt serial port.
4. Separate memory to store program and data.
5. Many function pins on the IC.
6. The Boolean operation is directly possible.
7. It takes a few instructions to read and write data from the external memory.

Microprocessor

1. Do not have inbuilt RAM or ROM and timer.


2. Input and output ports are not available, require extra device like 8155.
3. Do not have an inbuilt serial port, requires 8250 devices.
4. Program and data are stored in same memory.
5. Less multifunction pins on IC.
6. The Boolean operation is not possible directly.
7. It takes many instructions to read and write data from external memory.
As you already know, support devices are external in a microprocessor based system
whereas support devices are internal for a microcontroller. Microcontrollers offer software
protection whereas microprocessor-based system fails to offer a protection system. This
is made possible in microcontrollers by locking the on-chip program memory which
makes it impossible to read using an external circuit. So that are basic differences, now
you can come up with some more. As we need to interface support devices externally
in a microprocessor based system, the time required to build the circuit will be more;
the size will be more, and power consumption will be more in a microprocessor based
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ135

system compared to the microcontroller, e.g., Intel 8085 (microprocessor) and Intel 8051
(microcontroller).

3.2.3 Advantages of Microcontroller

1. The instruction set of a microcontroller is more simple than a microprocessor, so


your program lines are less and simple.
2. The microcontroller has inbuilt memory whereas a microprocessor doesn’t have.
So if you are using a microprocessor, then you will have to interface external
memory (RAM or ROM). So by using a microcontroller your circuit size becomes
less.
3. As compared to processor IC, controller’s ICs are easily (the most popular 8051)
available in the market and also cheap so your application cost will be less.
4. Microcontroller has the memory on a single chip so it performs faster than a
processor.
5. Microcontroller also has I/O pins on its chip so you can directly connect your
sensor to sense temperature, and also display device. If you are using a processor
then you need another IC to connect the processor with your sensor and display
device and that makes your circuit bulky and expensive.

3.3 HARDWARE COTS DESIGN (COMPONENT LEVEL)


IC types and components – commercially off the shelf (COTS)

Figure 3.4 Different types of ICs and components

SMD resistors
SMD resistors come into several possible case sizes. Each size is described as a 4-digit
number. The first two digits indicate the length; the last two indicate the width (in 0.01“
or 10 mils units) (see Fig. 3.4).
For example, the three most popular sizes are:
s ŖŜŖřDZȱ–ŽŠ—œȱŖǯŖŜȞƼŖǯŖřȞǰȱ˜›ȱŜŖƼřŖȱ–’•œǰȱ˜›ȱŗǯŜƼŖǯŞȱ––
s ŖŞŖśDZȱ–ŽŠ—œȱŖǯŖŞȞƼŖǯŖśȞǰȱ˜›ȱŞŖƼśŖȱ–’•œǰȱ˜›ȱŘǯŖƼŗǯŘśȱ––
s ŗŘŖŜDZȱ–ŽŠ—œȱŖǯŗŘȞƼŖǯŖŜȞǰȱ˜›ȱŗŘŖƼŜŖȱ–’•œǰȱ˜›ȱřǯŘƼŗǯŜȱ––
136ȳComputer Interfacing and Automation

PQFP 240 pins

TQFP 144
TQFP 100

MM 1 CM 2 3 4

Figure 3.5 TQFP 100 and 144 pin IC and their respective sizes

TQFPs 100 pins and 144 pins are reasonably easy to solder manually because the pins
are sturdy. PQFPs 208 pins and 240 pins are not as easy because the pins bend very
easily. Pins are separated by 0.5 mm (see Fig. 3.5).

SMD BGAs

The bottom of a BGA (Ball Grid Array) component is actually a circuit board, with pads
covered by solder balls (that’s what you can see in the below figure). The BGA balls are
not made of solid metal but solder. During board assembly, the BGA goes through an
oven, melting the balls between the BGA circuit board and the application circuit board.
Balls are commonly separated by 1 mm or 1.27 mm, less often by 0.8 mm (see Fig. 3.6).

Figure 3.6 Typical BGA ICS with their respective sizes


’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ137

3.4 PLL SYNTHESIZERS

A phase locked loop (PLL) is a feedback control system. It compares the phases of two
input signals and produces an error signal that is proportional to the difference between
their phases. The error signal is then low-pass filtered and used to drive a voltage
controlled oscillator (VCO) which creates an output frequency. The output frequency is
fed through a frequency divider back to the input of the system, producing a negative
feedback loop. If the output frequency drifts, the phase error signal will increase, driving
the frequency in the opposite direction so as to reduce the error. Thus, the output is
locked to the frequency at the other input. This other input is called the reference and
is usually derived from a crystal oscillator, which is very stable in frequency. The block
diagram below shows the basic elements and arrangement of a PLL based frequency
synthesizer (Fig. 3.7).
The key to the ability of a frequency synthesizer to generate multiple frequencies is
the divider placed between the output and the feedback input. This is usually in the
form of a digital counter, with the output signal acting as a clock signal. The counter is
preset to some initial count value and counts down at each cycle of the clock signal.
When it reaches zero, the counter output changes state, and the count value is reloaded.
This circuit is straightforward to implement using flip-flops, and because it is digital in
nature, it is easy to interface to other digital components or a microprocessor. This allows
the frequency output by the synthesizer to be easily controlled by a digital system.

Example

Suppose the reference signal is 100 kHz, and the divider can be preset to any value
between 1 and 100. The error signal produced by the comparator will only be zero when
the output of the divider is also 100 kHz. For this to be the case, the VCO must run at
a frequency which is 100 kHz × the divider count value. Thus, it will produce an output
of 100 kHz for a count of 1,200 kHz for a count of 2, 1 MHz for a count of 10 and so
on. Note that only whole multiples of the reference frequency can be obtained with the
simplest integer N dividers. Fractional-N dividers are also readily available

3.4.1 Frequency Synthesis by Phase Lock

The disadvantages associated with direct synthesis are greatly diminished with the
frequency synthesis technique (often referred to as indirect synthesis) that employs a
phase locked loop (see Fig. 3.7).

f Phase q
Loop Filter VCO fo
fr Detector

qd f d

÷N

Figure 3.7 An indirect frequency synthesizer


138ȳComputer Interfacing and Automation

The figure above illustrates the basic architecture of the PLL frequency synthesizer.
The phase detector generates an output signal that is a function of the difference between
the phases of the two input signals. The detector output is filtered (and perhaps
amplified), and the dc component of the error signal is applied to the voltage controlled
oscillator. The signal, fed back to the phase detector, is the VCO output frequency
divided by N. The VCO control voltage forces the VCO to change frequency in the
direction that reduces the difference between the input frequency and the divider output
frequency. If the two-phase detector input frequencies are sufficiently close, the PLL
feedback mechanism forces the two-phase detector input frequencies to be equal. That
is fr = fd and the divider output frequency Fd is obtained by dividing the voltage-
controlled oscillator (VCO) output frequency: F 0 by N. Hence, Fd = F 0/N. Therefore,
the output frequency is an integer multiple F 0 of the reference frequency.
The PLL with a frequency divider in the loop thus provides a method for obtaining
a large number of frequencies from a single reference frequency. If the divide ratio N
is realized by using a programmable divider (integrated circuitry has made the digital
programmable divider an inexpensive circuit component), it is possible to easily change
the output frequency in increments of F 0. The PLL with a programmable divider
provides an easy method for synchronizing a large number of frequencies, all of which
are an integer multiple of the reference frequency. Frequency synthesis is a major
application of PLLs.

3.5 FT232R USB UART IC

The FT232R is the latest device to be added to FTDI’s range of USB UART interface
integrated circuit devices. The FT232R is a USB to serial UART interface with optional
clock generator output and the new FTDI Chip-ID™ security dongle feature. In addition,
asynchronous and synchronous bit bang interface modes are available. USB to serial
designs using the FT232R have been further simplified by fully integrating the external
EEPROM, clock circuit and USB resistors onto the device.
The FT232R adds two new functions compared with its predecessors, effectively
making it a “3-in-1“ chip for some application areas. The internally generated clock
(6 MHz, 12 MHz, 24 MHz, and 48 MHz) can be brought out of the device and used to
drive a microcontroller or external logic. A unique number (the FTDI Chip-ID™) is burnt
into the device during manufacture and is readable over USB, thus forming the basis
of a security dongle which can be used to protect customer application software from
being copied. The FT232R is available in Pb-free (RoHS compliant) compact 28-lead
SSOP and QFN-32 packages

Key Features

s Single chip USB to asynchronous serial data transfer interface.


s Entire USB protocol handled on the chip. No USB-specific firmware programming
required.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ139

s USB FTDI Chip-ID™ feature.


s Configurable CBUS I/O pins.
s Integrated 1024 bit internal EEPROM for I/O configuration and storing USB VID,
PID, serial number and product description strings.
s Device supplied preprogrammed with unique USB serial number.
s Support for USB suspend/resume.
s Integrated power-on-reset circuit.
s Fully integrated clock (no external crystal, oscillator, or resonator required).
s Fully integrated AVCC supply filtering (no separate AVCC pin and no external
R-C filter required).
s 3.3to 5.25 V single supply operation.
s Low operating and USB suspend current.
s Low USB bandwidth consumption.
s USB 2.0 Full Speed compatible.
s –40 to 85°C extended operating temperature range.
s Available in compact Pb-free 28-pin SSOP and QFN-32 packages (both RoHS
compliant).

3.6 ELECTRONIC MEMORY

Memory is an essential element of a computer. Without its memory, a computer is of


hardly any use. Memory plays an important role in saving and retrieving data. The
performance of a computer system depends upon the size of a memory. Memory is of
the following types (see Fig. 3.8):
1. Primary/Volatile Memory.
2. Secondary/Non-Volatile Memory.

Figure 3.8 Electronic memory types


140ȳComputer Interfacing and Automation

3.6.1 Primary/Volatile Memory

Primary memory is the internal memory of the computer. RAM and ROM both form
part of the primary memory. The primary memory provides main working space to the
computer. The following terms come under primary memory of a computer (discussed
below).

Random access memory (RAM)

The primary storage is referred to as random access memory (RAM) because it is possible
to select randomly and use any location of the memory directly to store and retrieve
data. It takes the same time to any address in the memory as the first address. It is also
called read/write memory. The storage of data and instructions inside the primary
storage is temporary. It disappears from RAM as soon as the power to the computer is
switched off. The memories, which lose their content on the failure of power supply,
are known as volatile memories. So we can say that RAM is a volatile memory.

Types of RAM

Static random-access memory (SRAM) is a type of semiconductor memory that uses


bi-stable latching circuitry to store each bit.
Dynamic random-access memory (DRAM) is a type of random-access memory that
stores each bit of data in a separate capacitor within an integrated circuit. The capacitor
can be either charged or discharged; these two states are taken to represent the two
values of a bit, conventionally called 0 and 1. Since capacitors leak charge, the information
eventually fades unless the capacitor charge is refreshed periodically.

3.6.2 Secondary/Non-Volatile Memory

Secondary memory is external and permanent in nature. The secondary memory is


concerned with magnetic memory. Secondary memory can be stored on storage media
like floppy disks, magnetic disks, and magnetic tapes. This memory can also be stored
optically on optical disks – CD-ROM. The terms which come under secondary memory
of a computer are discussed below.

Read only memory (ROM)

There is another memory in a computer, which is called Read Only Memory (ROM).
Again it is the ICs inside the PC that form the ROM. The storage of program and data
in the ROM is permanent. The ROM stores some standard processing programs supplied
by the manufacturers to operate the personal computer. The ROM can only be read by
the CPU, but it cannot be changed. The basic input/output program is stored in the
ROM that examines and initializes various equipment attached to the PC when the
power switch is ON. The memories, which do not lose their content on the failure of
power supply, are known as non-volatile memories. ROM is a non-volatile memory.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ141

Types of ROM

PROM: There is another type of primary memory, which is called Programmable Read
Only Memory (PROM). You know that it is not possible to modify or erase programs
stored in ROM, but it is possible for you to store your program in PROM chip. Once
the programs are written, they cannot be changed and remain intact even if power is
switched off. Therefore, programs or instructions written in PROM or ROM cannot be
erased or changed.
EPROM: An EPROM (Erasable Programmable Read Only Memory) is an erasable
ROM that can be changed more than once. However, writing new data to an EPROM
requires a special program circuit. EPROMs have a quartz window that allows them to
be erased by exposure to strong ultraviolet light (typically for 10 minutes or longer) but
the whole device is cleared at one time then rewritten with a process that again needs
higher than the usual voltage applied. Repeated exposure to UV light will eventually
wear out an EPROM, but the endurance of most EPROM chips exceeds 1000 cycles of
erasing and reprogramming.
EEPROM: An electrically erasable programmable read-only memory (EEPROM) uses
electrical signals to erase the memory. With EEPROM bytes of data are individually
writable, readable and erasable. These erasable memory devices require more time to
erase data and to write new data
FLASH: The flash memory chip is a close relative to the EEPROM. It differs in that
it can only be erased one block or “page“ at a time. It is a solid-state chip that maintains
stored data without any external power source. Capacity is substantially larger than
that of an EEPROM, making these chips a popular choice for digital cameras.

3.7 PCB DESIGN


3.7.1 Making a PCB: PCB Manufacturing Step by Step
Front-end tool data preparation

The board designer has prepared his layout on a Computer Aided Design or CAD
system. Each CAD system uses its own internal data format, so the PCB industry has
developed a standard output format to transfer the layout data to the manufacturer
(see Fig. 3.9).
1. Preparing the phototypes: Used laser photo plotters in a temperature and
humidity-controlled darkroom to make the films we will use later to image the
PCBs. The photo plotter takes the board data and converts it into a pixel image.
A laser writes this onto the film. The exposed film is automatically developed
and unloaded for the operator.
2. Print inner layers: To produce the inner layers multilayer PCB, we start with a
panel of the laminate. Laminate is an epoxy resin and glass fiber core with copper
foil pre-bonded onto each side.
3. Etch inner layers: We remove the unwanted copper using a powerful alkaline
solution to dissolve (or etch away) the exposed copper. The process is carefully
142ȳComputer Interfacing and Automation

controlled to ensure that the finished conductor widths are exactly as designed.
But designers should be aware that thicker copper foils need wider spaces between
the tracks. The operator checks carefully that all the unwanted copper has been
etched away.
4. Register punch and Automatic Optical Inspection (AOI): The inner core of our
multilayer is now complete. Next, we punch the registration holes to align the
inner layers with the outer layers. The operator loads the core into the optical
punch which lines up the registration targets in the copper pattern and punches
the registration holes.
5. Lay-up and bond: The outer layers of our multilayer consist of sheets of glass
cloth pre-impregnated with uncured epoxy resin (Prepreg) and a thin copper foil.
6. Drilling the PCB: Now we drill the holes for leaded components and the via holes
that link the copper layers together. First, we use an X-ray drill to locate targets
in the copper of the inner layers. The machine drills registration holes to ensure
that we will drill precisely through the center of the inner layer pads.
7&8. Electroless copper deposition and image the outer layers: The first step in the
plating process is the chemical deposition of a very thin layer of copper on the
hole walls. We image the outer layers in a clean room to make sure that no dust
gets onto the panel surface where it could cause a short or open circuit on the
finished PCB.
9&10. Plating and etching outer layers: Next, we electroplate the boards with copper.
The operator loads the panels onto the flight bars. He checks all the clamps to
ensure a good electrical connection.
Now, we have plated the panel with 25 microns of copper through the hole and
an additional 25–30 microns on the tracks and pads. The copper is covered with
a thin layer of tin as an etch resist. Now we will remove the unwanted copper
foil from the surface.
11. Apply solder mask: Most boards have an epoxy inks older mask printed on each
side to protect the copper surface and prevent solder shorting between components
during assembly.
12. RoHS-compliant surface finishes (electro less gold over nickel): The copper
component pads and holes have been left clear of solder mask. Now we apply a
solderable surface finish to protect the copper until the components are soldered
onto the board.
13. Plated gold edge connectors: For edge-connectors, we electroplate hard gold. First,
the operator puts protective tape on the board above the connectors. Then he
mounts the panel on a horizontal electroplating bath.
14. Silk-screen and cure: Most PCBs have a component legend to show which
component goes where. Today we use ink-jet printers to image the legends direct
from the board digital data.
15. Electrical test: We electrically test every multilayer PCB against the original board
data. Using a flying probe tester, we check each net to ensure that it is complete
(no open circuits) and that it does not short to any other net.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ143

16. Profiling (V-cut scoring and finishing): The final manufacturing stage is to profile
the PCBs and cut them out of the production panel. Alternatively, we can profile
the individual circuits on a V-cut or scoring machine. This has two cutters, one
above and one below the panel. Each cuts a V-shaped groove about 1/3 of the
thickness of the material, leaving a thin web holding the PCBs together. In the
last step of the process, a team of sharp-eyed inspectors gives each PCB a final
careful check-over.

Figure 3.9 Block diagram of double sided PCB manufacturing

3.7.2 Automatic CAM : Reflow Soldering Process

The reflow soldering process for lead-free components is similar to conventional eutectic
solder reflow process. Similar equipment and process are often used for both. However,
there are some important differences that must be taken into account for lead-free
soldering. That’s because the material set used for lead-free soldering is different and
higher reflow temperatures are required. Several important factors must be considered
for lead-free soldering (see Figs. 3.10 and 3.11).
PCB surface finishes must be able to withstand reflow temperatures without surface
damage. A wide range of lead-free solder paste alloys is available. The one selected
should be non-hazardous, mechanically reliable, thermal fatigue resistant, good wetting,
relatively low melting temperature and must be compatible with a variety of lead-bearing
and lead-free surface coatings.
Lead-free solder paste shelf life differs from the traditional eutectic solder paste. Paste
manufacturer recommendations should be carefully followed to avoid any issues.
144ȳComputer Interfacing and Automation

Master PCB-I Master PCB-II Cutting of SMT Stencils


by Laser Technology

Stencil-I Stencil-II Fiducial Matching


Master Board-I Master Board-II
Figure 3.10 Snapshots of reflow soldering

The production process cont...


RoHS compliant

Inside view,
One master board.
Two daughter boards

Figure 3.11 A typical device design using one master and two daughter boards

3.8 PROGRAMMING THE MICRO MEMORY


The microprocessor uses memory for holding the program code (program memory) and
the working data (data memory) in an embedded system. USB programmer feature uses
FT232R circuit to connect to microcontroller pins (see Fig. 3.12).
When the processes are powered up, the program data needs to be there and ready.
Non-volatile memory is generally required for program memory. There is often no need
to retain data when the product is switched off. Therefore, volatile memory is traditionally
preferred for data memory (see Fig. 3.13).
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ145

+5 V
USB

RLX from LPC 1768: P27

VCC TXD TX from LPC 1768: P28

4K7 4 RXD
VCCIO
RTS
Reset
F CTS
NC T DTP
NC 2
10K 3 DST
2 DSR
25
GND R
DCR

RI
USBDM CBUS1 7
CBUS2
USPDM CBUS3
CBUS4
3 V OUT
A T
G G G E
G
VCC N N N S
N T
100 nF D D D
D
100 nF 100 nF 4.7 nF

Figure 3.12 Pin-out diagram for FT232R converter

Computer Programmer

CN2 PRG

F LED 3
T LED 5 C 23 R 20
R 19 C
23 LED 4
2 LED 6 C 17 R7 R8 N
processor
micropro
ATMEL

R 5
LED 2 C 18 R9 R 10
LED 1 OSCl
C 19 R 11 R 12
L7 R3
C 20 R 13 R 14
C 15 R4
R 15 R 16
C 21
C 22 C 17 C 18
IGO
CN C16
3 CN 1 CN 4

Figure 3.13 Block diagram of programming the memory


146ȳComputer Interfacing and Automation

3.9 IN-SYSTEM PROGRAMMING


3.9.1 System Programming: Ways to Program Internal Flash Memory of
Microcontrollers

It uses serial SPI (serial peripherals interconnect) protocol. The Serial Peripheral Interface
Bus or SPI (pronounced as either ess-pee-eye or spy) bus is a synchronous serial data
link standard, named by Motorola; that operates in full duplex mode. Devices
communicate in master/slave mode where the master device initiates the data frame.
Multiple slave devices are allowed with individual slave select (chip select) lines.
Sometimes SPI is called a four-wire serial bus, contrasting with three-, two-, and one-wire
serial buses. SPI is often referred to as SSI (synchronous serial interface).
Application development for embedded systems is usually done on a desktop
computer (PC), using a high-level language like C or assembly language. After the
executable binary has been created by the cross development tools, this binary needs to
be uploaded to the target board. In most cases it will go to some kind of non-volatile
memory, requiring specific programming procedures (see Fig. 3.14).

Figure 3.14 In-system programming

3.9.2 Features of ISP

It is a 4-wire communications bus, typically communicates across short distances,


supporting single master with multiple slaves setup and synchronized with clocked
systems. It’s always operated full-duplex, communicates in both directions simultaneously
with multiple Mbps transmission speeds, transfers data in 4 to 16-bit characters, and
supports multiple slaves (see Fig. 3.15).
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ147

SCLK
SPL SCKL
MASTEB MOMI SPI
MOMI
slave
MISO MISO

SS1 SS

SS2
SCLK
SS3 MOMI SPI
slave
MISO

SS

SCLK
SPL
MOMI
slave
MISO

SS

Figure 3.15 Master-slave link

SPI bus wiring

s Bus wires
1. Master-Out, Slave-In (MOSI)
2. Master-In, Slave-Out (MISO)
3. System Clock (SCLK)
4. Slave Select/Chip Select (SS1#...SS#n or CS1…CSn)
s Master asserts slave/chip select line
s Master generates clock signal
s Shift registers shift data in and out
For in-system programming, the following items are needed.
1. A software tool running on the desktop computer, which can control the
programming interface via any standard port.
2. A programming adapter which allows connecting the programming interface to
any standard port available at the PC, like USB, RS-232, printer port, etc.
3. A special programming interface like SPI (Serial Programming Interface), JTAG
(Joint Test Action Group), etc.
All the three requirements must be fulfilled somehow, but there is a large variety of
real-world implementations. For example, the programming adapter may be integrated
148ȳComputer Interfacing and Automation

on the target board. In that case, for example, a USB cable may be used to connect the
PC directly to the target board. Sometimes the programming interface is accessible by
special microcontroller instructions or registers, which allows loading new firmware.

3.9.3 Source Code

The word source differentiates code from various other forms that it can have (for
example, object code and executable code) (see Fig. 3.16).
Initially, a programmer writes a program in a particular programming language. This
form of the program is called the source program, or more generically, source code. To
execute the program, however, the programmer must translate it into a machine language,
the language that the computer understands. The first step of this translation process
is usually performed by a utility called a compiler. The compiler translates the source
code into a form called object code. Sometimes the object code is the same as machine
code. Sometimes it needs to be translated into machine language by a utility called an
assembler.

Source Source Source Source


File File File File

Object Object Object Object


File File File File

Runtime Executable
Linker
Library Program

Block Diagram

Figure 3.16 Block diagram for how a program is executed

Program instructions in their original form


The source code is the only format that is readable by humans. When we purchase
programs, we usually receive them in their machine-language format. This means that
you can execute them directly, but you cannot read or modify them. Some software
manufacturers provide source code also.

3.9.4 Programming Software


Here are quite many tools available, each of which supports its own set of programming
adapters, interfaces and targets. And, quite important, not every tool is available for
every desktop operating system.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ149

These tools either run on a command line (CLI) or provide a graphical user interface
(GUI). Each has its advantages and disadvantages. While CLI tools are perfect for
automation, the large number of available options are easier to handle manually with
GUI tools. Some tools offer both worlds. A graphical interface controls an underlying
command line tool, which can alternatively run without the GUI (see Fig. 3.17).

Figure 3.17 A Microcontroller board with USB IC LPC 1768

Free programming software

Product Open Supported CLI GUI Supported


Source OSes Targets
AVRDUDE Yes Linux Yes Yes AVR
Windows OS
X
AVR Studio 4 – Windows Yes Yes AVR
JTAG-O-MAT Yes Linux Yes – ARM
Windows

3.9.5 PC Ports used with In-System Programming


Most simple programming adapters are available for the parallel printer port. Typically,
they are not much more than a logic buffer or level converter attached to the parallel
printer port; sometimes a few resistors do the trick. Like parallel printer ports, the RS-232
(COM port) interface has been largely replaced by USB. However, RS-232 serial ports
are still popular with embedded systems. More advanced programming adapters are
based on microcontrollers, and nearly all these controllers provide at least one UART,
the logic part of doing RS-232 communication. Thus, programming adapters with RS-232
ports are still in use (see Fig. 3.18).
The USB is much more complex than the parallel printer port or RS-232, but an
increasing number of microcontrollers provide this interface. Hence, more and more
programming adapters are offered for the USB port, because it is available on almost
every PC. After FTDI offered special chips, which can do JTAG programming via USB
without the need to write any firmware.
One disadvantage of the USB is its limited cable length. Most advanced programming
adapters offer Ethernet connectivity and allow remote programming and debugging
over the Internet.
150ȳComputer Interfacing and Automation

+5V
USB

RLX from LPC 1708 P27


VCC TXD TX from LPC 1768 P28
4 RXD
4 K7 VCCIO
RTS
RESET CTS
NC DTP
10 K NC F DST
T
DSR
25 2
GND 3 DCR
2
R RI
USBDM CBUS1 7
CBUS2
USPDM CBUS3
CBUS4
3 V OUT
A T
G G G E
VCC N N G N S
D D N D T
100 nF D
100 nF 100 nF 4.7 nF

GND GND
Figure 3.18 Pinout for FFT232R converter

3.9.6 AVR In-System Programming

There are a number of ways to program internal flash memory of AVR microcontrollers:
1. ISP, sometimes called SPI, because it is based on the serial peripheral interface.
2. JTAG programming is available on the larger devices as an alternative to ISP.
3. DebugWire is used on many devices with low pin count.

3.9.7 ARM In-System Programming

In-system programming of ARM microcontrollers with internal flash memory is typically


done via JTAG. One of the simplest JTAG adapters, hardware-wise, is the well-known
Wiggler for the parallel printer port, which has become a synonym for this type. Initially,
it was offered by Macraig or Systems.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ151

Today many JTAG adapters are based on the FT2232. The chip provides two USB
devices, and some programming adapters use the second one to offer an additional
RS-232 port.

3.9.8 In-System Programming of External Memory

Due to the Harvard architecture with mixed 8-bit data and 16-bit instruction code bus,
program execution of all members of the 8-bit AVR family is limited to internal flash
memory. This is true, even if an external bus interface is available. Nevertheless, the
external flash memory may be used as non-volatile data memory.
ARM microcontrollers with external memory bus are not limited in this way. A large
number of ARM microcontrollers does not even provide any internal flash memory, and
firmware must be stored in the external memory chips (see Fig. 3.19).

Figure 3.19 FT232R USB to TTL Serial Adapter Module

There are at least two major procedures for in-system programming of external
memory devices.
The first is based on JTAG boundary scan, which allows toggling almost any pin of
a JTAG enabled device. If all programming pins of the memory chip are tied to such a
devices, JTAG boundary scan can be used to apply the programming sequence to the
memory chip. This has the advantage that no initial software is required on the target
board because JTAG boundary scan is implemented in pure hardware. But, this is time
consuming.
152ȳComputer Interfacing and Automation

The second method uses the JTAG debugging interface, which allows the CPU execute
single instructions. This way a programming sequence for the external memory chip
can be executed, step by step. This is significantly faster than the boundary scan method,
but requires, that the CPU is initialized and running. A variant of this method can be
used with some RAM available. Instead of emulating single instructions, the whole
procedure is uploaded and then run by the CPU. The contents that need to be
programmed into the external memory chip may be transferred through another interface
or use the JTAG cable itself if a so-called JTAG COMM interface is provided.

Figure 3.20 LPC-ARM-JOBY board

3.9.9 Boot Loading Firmware

In general, boot loaders transfer an executable binary from some kind of an external
device to on-board memory and jumps to a specific entry point of this binary to execute
it. This is typically done after power-on or after resetting the system and not too
complicated when using RAM. In other words: A standard boot loader loads the binary
image into volatile memory each time the system is started.
Firmware boot loaders are somewhat different. They are able to program non-volatile
memory and are only needed during so-called firmware updates. Thus, they will be
activated on demand only. If internal flash is used, the device must provide self-
programming capabilities.

AVR firmware boot loaders

The tricky part on the AVR is that program code can run on internal flash only.
Programming the same flash that runs the flashing code must fail, because during
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ153

programming cycles the CPU won’t be able to load the next instruction code. Fortunately,
flash memory has been divided into two parts, the application and the boot area. A
program running in either of the two is able to program the other area.

ARM firmware boot loaders

Almost all devices have a boot loader stored in internal ROM. A programmable,
non-volatile bit in the chip decides, whether the CPU starts the boot loader or the
previously uploaded firmware after a hardware is reset. When erasing the device, the
boot loader will be activated.

3.10 BINARY TO HEX GENERATION

Command Prompt is a command line interpreter application available in most Windows


operating systems. Here I have taken a binary file and converted to hex. As the last line
indicates status: BIN to HEX conversion was successful (see Fig. 3.21).

Figure 3.21 Screen shot of binary to hex generation

3.11 CONNECTING PROGRAMMER TO PROGRAM ARM CHIP LPC1768


3.11.1 Flash Magic
Requirements

Flash Magic works on Windows 2000, XP, Vista and 7. 10 Mb of disk space is required.
154ȳComputer Interfacing and Automation

Introduction

Flash Magic is a tool which is used to program hex code in EEPROM of the microcontroller.
It is a free ware tool. It only supports the microcontroller of Philips and NXP. You can
burn a hex code into that controller which supports ISP (in system programming) feature.
To check whether your microcontroller supports ISP or not take a look at its data sheet.
So if your device supports ISP, then you can easily burn a hex code into EEPROM of
your device. Flash Magic supports several chips like ARM Cortex M0, M3, M4, ARM7
and 8051.
The procedure to program code memory is very easy and needs only five steps to
configure Flash Magic for better operation. Flash Magic uses Serial or Ethernet protocol
to program the flash of the device. Below is the screen shot of Flash Magic.

Initial Step

The PoPUP of device signature should l be read when we select the option ISP-> Read
device signature. If the device doesn’t read the signature first time, switch off (means
remove the two-pin +12 V power connector once from theLPC-JOBY board online) and
connect it back at once. Then again select the option ISP-> Read device signature. Repeat
this procedure till the device signature is read.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ155

Now here I am going to show you how to use this tool and configure it. First of all, go
to Options and then go to Advanced Options.
156ȳComputer Interfacing and Automation

Step-1: Communications

1. Select your target device


2. Select your COM port and if you are using USB to serial converter make sure
that you select proper COM port otherwise you cannot communicate
3. Now select baud rate. Ideally it should be 9600 (recommended). Avoid higher
than 9600 for proper communication
4. Now select your interface. If you are using DB-9 then it will be None (ISP)

Step-2: Erase

Now here tick mark the ‘Erase all Flash’ option. This is the most crucial thing because
a wrong selection in this step can result in the loss of boot loader in your chip. Nothing
to worry if you lost your boot loader because you can again load it but to load
boot loader you must program your chip through a universal programmer or any
other programmer which does not depend upon boot loader for loading hex code.
After loading the boot loader, you are again able to program your chip using Flash
Magic.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ157

Step-3: Hex File

This is very simple, and you need to set up a path of your Hex file which is to be loaded
on the chip.

Step-4: Options

In this always keep Verify after programming option --enable by a tick mark. You can
use another feature as well according to your need.

Step-5: Start

Now you are all set to burn your code memory. Just click on the start button and it will
start to load hex code in your chip. You can see the process at the bottom.
The RS232 board is connected to link between the computer and target board and
software that feed into is Tera Term.

3.11.2 Tera Term/Hyper Terminal

Tera Term is an open source free software terminal emulator (communication program)
for MS-Windows. It emulates different types of terminals, supports serial port connection.
It also has built-in macro-scripting language and the set of useful plugins.
T. Teranishi from Japan created the early versions of Tera Term. At the time, it was
one of the only freely available terminal emulator effectively supporting the Japanese
language. Development of Tera Term stopped in the late 1990s at Version 2.3. In 2002,
Ayer a Technologies released Tera Term Pro 3.1.3 supporting SSH2 (see Fig. 3.22).
158ȳComputer Interfacing and Automation

Figure 3.22 A typical Tera Term terminal for serial communication

In 2004, a software designer from Japan restarted development of the open source
version of Tera Term. He added his own implementation of SSH2 and lots of new features
on top of what was part of version 2.3. A complete list is published in the Tera Term
Support forum (see Fig. 3.23).
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ159

Figure 3.23 Tera Term interface with decrease/increase in intensity of LED light on PCB

3.11.3 Understanding Intel Hex File

Intel hex file is a file which contains binary data values to program microcontrollers,
EEPROMs, and other chips. The compiler converts source code into machine code and
outputs it into a hex file. This hex file then burnt into the chip using the burner for
make chip functional (see Fig. 3.24).

Typical look of a hex file is:


: 100B5400020AB8E493A3F8E493A34003F68001F2F5
: 100B640008DFF48029E493A3F85407240CC8C333A2
: 100B7400C4540F4420C8834004F456800146F6DF71
: 100B8400E4800B0102040810204080900006E47EFB
: 100B9400019360BCA3FF543F30E509541FFEE49366
: 100BA400A360010ECF54C025E060A840B8E493A32D
: 100BB400FAE493A3F8E493A3C8C582C8CAC583CA58
: 100BC400F0A3C8C582C8CAC583CADFE9DEE780BE10
: 010009000F6
: 00000001 FF
160ȳComputer Interfacing and Automation

Each line has six different meaningful parts, and these parts are:
1. Starting Code
2. Byte Count
3. Memory Address
4. Record Type
5. Data
6. Checksum

:100BA400A360010ECF54C025E060A840B8E493A32D

Six Different Paints

: 10 0BA4 00 A360010ECF54C025E060A840B8E493A3 2D

Meaning of Each Part

1 Starting Code
2 Byte count or Represents Number of Data Bytes
3 Memory Address
4 Record Type
5 Data
6 Checksum

Figure 3.24 Six different parts in each line of Hex code

1. Start code: It is a single character an ASCII code of colon(“:”). Every line of hex
file starts with a colon. It indicates the new line in the hex file.
2. Byte count: It consists of two hex characters and it represents the length of data
bytes in the record.
3. Memory address: It consists of a 4-digit memory location that represents the
starting address of subsequent data in the record. Data starts storing from this
memory location and it increments after storing of each data byte.
4. Record type: It consists of two hex digits. There are six types of records. This
field has only five possible values which are from 00 to 05.
Ÿ00 = Data record; which contains data and 16-bit address.
Ÿ01 = End of file records; every hex file must end with the end of file record
type for that record type field must contain “01". End of file records always
has the following format: 00000001FF.
Ÿ02 = Extended segment address records; it is also known as HEX86. Extended
segment record must have two data bytes. The absolute 32-bit address is
generated using the addition of extended segment address’s data field and
data record’s address field.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ161

Ÿ04 = Start segment address record; this is for 80x86 processors. It specifies the
initial contents of code segment and instruction pointer. Here the first two
values (bytes) of the data field are for the code segment, and other two are
for the instruction pointer.
Ÿ05 = Start linear address records; this is for 80386 and higher CPU. Contents
of the data field that is of 32-bit are loaded into the EIP register.
5. Data Field: This field contains data byte and address as well. The content of the
record field differentiates whether it is data or address.
6. Checksum: This is two hex digits appears at the end of each line. For calculating
this number 1st add every hex number of line not include “:” and checksum field
itself. Then perform 2’s compliment of the least significant byte.

3.11.4 Generating Hex File Using Keil

How we can generate hex file using Keil software is the all in one simulator which is
most popular in embedded and as well as in industry. By using Keil, you can develop
your source code in both the languages, that is, assembly language and C language, but
the hex file is common for both.
Step-1: In menu bar navigate to Project >> Options to target and click on it or in Project
workspace window right click on Target1 >> Options for Target and a new window
appears on your desktop.
162ȳComputer Interfacing and Automation

Step-2: In Options for Target window go to Target tab and enter the value of your crystal
frequency in Xtalfield. Make sure that you enter this in MHz.

Step-3: Now go to Output tab and just tick mark the Create HEX File check box and
hit ok.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ163

Now just rebuild your target and you are done. Your hex file is generated in the same
folder in which your project file is located. Now you can burn this hex file into the ROM
of the microcontroller.
Important Note: Keil does not provide any path selection option for storing generated
hex file. It automatically stores it in the same folder which contains your project file.

3.12 HOW TO DESIGN OWN ARM MBED BOARD COMPATIBLE TO LPC1768


MBED ARM BOARD (AVAILABLE IN MARKET)
The power of ARM mbed and its compatible low-cost DIP device design using LPC1768
ARM Chip with USB output for offline programming via Flash Magic for building
embedded application is discussed here. We have designed our own ARM mbed binary
compatible low-cost 40-pin DIP device using LPC1768 ARM chip, one of the most
successful ARM processors in the market. The board has FT232 based USB output for
off-line programming via free Flash Magic for building embedded applications in 32-bit
ARM CortexM3 processor running at 12 MHz clock. The board with 512 KB Flash and
32 KB RAM, which makes it far more capable than popular 8-bit prototyping alternatives.
The board was designed to use as daughter board to test many cryogenic instrument
motherboards built in-house. The analog input voltage range of IUAC board is from
0-10 V DC unlike 0-3.3 V in other ones. The reduction in circuit components provides
better noise margin in the functioning of analog inputs. Downloading programs is as
simple as using a USB flash drive (no external programmer is necessary). This is 100%
pin compatible to the binary files generated by ARM embedded applications by ARM
mbed 1768. One can program using the ARM mbed cloud computer and make use of
vast embedded library to produce .bin files on your desktop from any OS (Windows or
Linux or any other) which any time can be transferred to this IUAC board for tests. The
mechanical form factors are one-to-one compatible to the existing ARM1768 board except
that this board is designed to work as virtual USB ports to connected PC and Ethernet
port is not available. We will explore the power of ARM mbed ecosystem and how we
designed and tested our own device called IUAC mbed board.
ARM designs the technology that is at the heart of advanced digital products, from
wireless, networking and consumer entertainment solutions to imaging, automotive,
security and storage devices. We have developed an alternative board for off-line
programming with USB instead of buying commercial ARM mbed LPC1768 boards.
The mbed NXP LPC1768 is an easy-to-use MCU development board designed for
rapid prototyping. At its heart is a powerful 32-bit ARM Cortex-M3 processor running
at 96 MHz with 512 KB Flash and 32 KB RAM, which makes it far more capable than
popular 8-bit prototyping alternatives. A comprehensive firmware library and plenty of
sample codes help you get your program up and running quickly, and a free online
IDE and C++ compiler means that no software installation is required. Downloading
programs is as simple as using a USB flash drive (no external programmer is necessary).
You can use the mbed libraries commercially for free, on an unsupported as-is basis.
The mbed compiler generates a raw binary targeting the MCU; there is no boot loader
magic going on in the binary. The binary runs on the LPC1768 bare metal, there is no
runtime environment. The mbed microcontroller is “mbed Interface". It is just a USB
device that can program the raw binary into the LPC1768s flash memory (see Fig. 3.25).
164ȳComputer Interfacing and Automation

Figure 3.25 Schematic diagram of interaction with target board by USB

3.12.1 Description of Structure and Design of the System

The mbed NXP LPC1768 development board from ARM enables a quick and easy
creation of high-performance prototypes. Based on the powerful NXP LPC1768 Cortex-M3
processor, which runs at 96 MHz and offers 512 KB flash and 32 KB SRAM, the 32-bit
mbed can outperform popular 8-bit prototyping platforms like the Basic Stamp. The
mbed NXP LPC1768 also offers peripherals not typically found on lower-performance
prototyping boards, such as Ethernet, USB, a 12-bit ADC, a 12-bit DAC for a true analog
voltage output, in addition to more common interfaces like serial (UART), SPI, I2C, and
CAN. The mbed has a 40-pin DIP form factor with 0.1“-pitch male header pins already
soldered in, so it can be used with standard solder-less bread boards. We have developed
an alternative board for off-line programming with USB. Our comparison table can help
you choose the right mbed for your application.
One of the strengths of this platform is the mbed library, which provides an API-driven
approach to coding that eliminates much of the low-level work normally associated with
MCU code development. The code can be developed using meaningful peripheral
abstractions and API calls that are intuitive and well tested, freeing you up to experiment
without worrying about the implementation of the MCU core or its peripherals.
Another key feature of mbed is its unique C++ compiler and IDE. These free tools
are entirely web-based and run online, which means there is no software to download
or install. Supported browsers include Internet Explorer, Firefox, Safari, or Chrome
running on a Windows, Mac, or Linux PC. You can log in from anywhere and simply
pick up where you left, and this approach makes it easy to share code with others. And,
since you’re working with a web-based tool, you can be confident that it is already
configured and will stay up-to-date. The compiler uses the ARM Real View compiler
engine, so it produces clean, efficient, optimized code that can be used free-of-charge,
even in production. Existing ARM application code and middleware can be ported to
the LPC1768 microcontroller, and the mbed tools can be used alongside other professional
production-level tools, such as Keil MDK No external programmer is required to program
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ165

the mbed. When connected to your computer via the included USB cable, it shows up
as a mass storage device. Simply save the compiled binary file to the board to program
it (see Fig. 3.26).

Figure 3.26 Schematic diagram of mbed for LPC1768


3.12.2 SPI and CAN Interface by LPC1768 ARM Chip with USB
The SPI Interface: This interface can be used for communication with SPI slave devices,
such as FLASH memory, LCD screens and other modules or integrated circuits. The SPI
Interface can be used to write data words out of the SPI port, returning the data received
back from the SPI slave. The SPI clock frequency and format can also be configured.
The format is set to data word length 8 to 16 bits (see Fig. 3.27).

SCLK SCLK
SPI MOSI MOSI SPI
master MISO MISO slave
SS SS

Figure 3.27 The default settings of the SPI interface are 1 MHz, 8-bit, Mode0

The SPI master generates a clock to synchronously drive a serial bit stream slave. The
slave returns a bit stream, also synchronous to the clock.
CAN (Controller-area Network) is a bus standard designed to allow microcontrollers
and devices to communicate with each other without a host computer. In order to use
CAN, you need transceivers, which change the digital signal (RD/TD), outputted by the
166ȳComputer Interfacing and Automation

LPC1768 into a differential signal, which is transmitted along the CAN bus to the other
nodes. As well as this, you need two 120 ohm terminating resistors at either end of the
bus. Without both the transceivers and the terminating resistors, the bus will not work
properly. Below is an example circuit, which demonstrates how to set up a CAN bus, which
simply loops the data between the mbed LPC1768's two CAN buses (see Fig. 3.28).

Figure 3.28 Block diagram of CAN interface with LPC1768 board


The CAN Interface can be used on mbed pins p9/p10 and p30/p29. The CAN Interface
can be used to write data words out of a CAN port and will return the data received
from another CAN device. The CAN clock frequency can be configured.
3.12.3 Programming the LPC 1768 and Realization of the System
Getting started is as simple as using a USB Flash drive. Simply connect the mbed NXP
LPC1768 board to a Windows, Mac, or Linux computer and it will automatically appear
as a USB drive. Follow the link on the board to connect to the mbed website, where you
can sign up and begin designing. There are no drivers to install or set up programs to run.
Programming the LPC1768
There are two ways to get a binary into the LPC1768; JTAG and the In System
Programming (ISP) over a UART using the LPC1768s built-in serial boot loader. The
JTAG method is what you will find on a lot of development boards. It offers many
additional features (debug, semi-hosting, etc.) as well as just the ability to load the binary
image. Using the JTAG port requires a JTAG “wiggler“ to drive the JTAG interface and
some software that knows how to communicate over JTAG and load the binary. The
other method is ISP using the LCP1768 bootloader, which relies on a simple strategy:
1. Pull nReset low to put the LPC1768 into reset.
2. Pull the ISP pin (P0.14) low, to indicate the ISP is intended.
3. Pull nReset high. The LPC1768 comes out of reset and samples the ISP pin. If it
is low, the boot loader runs.
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ167

4. The boot loader communicates over a serial connection on UART0: TXD0 = p0.2
= pin 98; RXD0 = p0.3 - pin 99.
5. With a level shifter, you can quite happily connect to it from your computers COM
port and use Tera Term to type commands to it and see the reply, or use some
software to communicates and download binaries.
The boot loader software uses a series of commands to query the device status, erase,
and transfer and program binary data to the LPC1768's flash memory. We have used
Flash Magic.
Communicating with the LPC1768
To bridge control the pins, and bridge the boot loader serial port to my PC, I used my
mbed as a serial pass through and to drive the ISP and nReset pins. I'll refer to this
arrangement as mbed ISP.
1. Use GPIO pins (p29,p30) of my mbed to manipulate the nReset and ISP pins on
the custom PCB.
2. Use a serial port (p28,p27) to connect to the boot loader serial port on the LPC1768.
3. Use the USB serial port to communicate with the PC, and simply pass characters
back and forth between the LPC1768 and the PC via the mbed – think of it as
USBRS232+Level shifter.
As the nReset and ISP pins have pull-ups, they should be driven with an open collector.
Following this by using a digital input, driving as an output of value 0, or as an input
with no pull-up. If it starts simply by sending the “?“ character which is for auto baud
detection - the LPC1768 should reply “Synchronized.

3.12.4 Features and Comparison


Features of our device
Table 3.1 Features of LPC1768 Arm chip
NXP LPC1768 MCU Prototyping form-factor mbed. org Developer Website

A. High performance ARM® A. 40-pin 0.1“ pitch DIP E. Lightweight Online Compiler
Cortex™-M3 Core package, 54 × 26 mm F. High-level C/C++ SDK
B. 96 MHz, 32 KB RAM, 512 KB B. śȱȱȱ˜›ȱŖȬŗŖȱȹȱœž™™•¢ȱ G. Cookbook of published
FLASH C. Built-in USB drag ‘n’ drop libraries and projects
C. Ethernet, USB Host/Device, FLASH programmer. H. Easy-to-use, free online tools
2xSPI, 2xI2C, 3xUART, CAN, D. Drag-and-drop programming, I. API-driven development
6xPWM, 6xADC, GPIO. with the board, represented using libraries with
D. Uses the ARM RealView as a USB drive intuitive interfaces
compile engine

The mbed NXP LPC1768 is one of a range of mbed microcontrollers packaged as a


small 40-pin DIP, 0.1-inch pitch form-factor making it convenient for prototyping with
as older less breadboard, strip board, and through-hole PCBs. It includes a built-in USB
programming interface that is as simple as using a USB Flash Drive. Plug it in, drop on
an ARM program binary, and it’s up and running.
168ȳComputer Interfacing and Automation

Comparison with different mbed boards with our own board Compatible Mbed
LPC1768
The following figure shows the comparison of our board with other boards sold in the market
(see Fig. 3.39).

mbed NXP LPC1768 mbed NXP LPC11U24 mbed NXP LPC800 –‹ŽŗŝŜŞȹ*
Cortex M3 Cortex M0 Cortex M0+ Cortex M3
Powerful applications Low power applications Even less power Input 0–10 VDC
USB Host/Device USB device Arduino form factor USB Host/Device
Ethernet On-Chip USB drivers 8/16 bit application space USB-for offline
Can Low cost chip Low Cost board
Switch Matrix 40 pin DIP

* indegeneous .
Figure 3.29 Comparison with other boards

3.12.5 Applications of LPC1768 Arm Chip


Mechatronics controllers
This category of applications includes single and dual serial motor controllers with a
variety of features such as analog, RC, or USB control, speed/position feedback, channel
mixing, and more.
The Brushed DC Motor Drivers: Single and dual motor driver carriers get your brushed
DC motor projects up and running quickly using modern H-bridges with high-
performance MOSFETs that deliver hundreds of watts in a compact package. Give these
boards a PWM signal and make your motors go.
Stepper Motor Drivers: With features like adjustable current limiting and selectable
micro step resolutions; these drivers make it easy to get a stepper motor running with
simple step and direction control interfaces.
The Internet of Things
The Internet of Things is a term generally used to refer to a world where a large number
physical objects are addressable via the Internet (or similar network). Examples of
physical objects, in this case, could include things such as connecting the world's objects
in interoperable standards-based way promises to revolutionize such diverse areas such
as government, factory automation and farming (see Fig. 3.30).
A-mbed Internet of Things: HTML5 web sockets: mbed is all about prototyping
these sorts of things to build working proof-of-concepts. This project shows how to
build a system that can quickly deploy Internet of Things sensors using just a smart
phone, and how real-time sensor data can be transmitted and visualized using HTML5
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ169

web standards. This project uses the mbed microcontroller to read sensors and send the
real-time sensor data over an IP based network using HTML5 web sockets. Web sockets
are a new protocol in HTML version 5 which support easy real-time data links from
any source to any destination, including web pages. More information can be found at
websockets. This shows how data about real-world objects can be accessed by letting
microcontrollers connect to the Internet using HTML5 web standards, and visualize it
using standard clients such as phones or desktop browsers.
Sending and Receiving the data: Internet of Things using Wi-Fi: There’re guides
on creating an Internet of Things using different transports, including proper
implementation and different types of development boards. The example uses the new
mbed Cortex-M0 beta to make battery-powered prototypes of sensors communicating
via wi-fi. For this, we used a Wi-Fi module produced by Roving Networks. We used an
mbed with an ARM Cortex-M0 processor for low power consumption, as our demo was
fully wireless. We used standard sensors in mbed kits so we could utilize the libraries
already written for them. Note that the hardware is irrelevant; any device with Internet
connection and the right capabilities could replicate this demo. A sensor sending data
over web sockets needs a websocket server to connect to.mbed have provided a test
server at http://sockets.mbed.org.
Architecture

Figure 3.30 Overview of processing of Internet of Things

3.12.6 Combining MATLAB and Embedded Systems


To connect MATLAB with embedded systems, usually people use 8051 microcontrollers
and to create a GUI that can be directly linked to 8051 which has real-time application.
A basic solution is a UART, which is a COM port on the PC. The COM port can be
written directly from MATLAB, and the transmission is almost real time, but the
bandwidth is low. Embedded MATLAB uses an inference engine to enforce language
170ȳComputer Interfacing and Automation

constraints for simulation and code generation. Embedded MATLAB works with Real-
Time Workshop to convert code from a dynamically typed language (MATLAB) to a
statically typed language (C), without using dynamic memory allocation. To convert
data types accurately, the embedded MATLAB inference engine requires that you define
the class, size, and the complexity of data in the source code so it can assign data types
correctly at compile time. Supported MATLAB features embedded MATLAB supports
the following MATLAB features:
1. N-dimensional arrays
2. Matrix operations
3. Subscripting
4. Complex numbers
5. Numeric classes
6. Double-precision, single-precision, and integer, etc.
Interfacing mbed with MATLAB: There is a library of classes for interfacing with mbed
from MATLAB. This might be useful for things like using MATLAB to acquire and
process data from sensors connected to mbed, using MATLAB to control actuators
connected to your mbed. Implementing hardware in the loop programs in MATLAB,
where the sensors and actuators are connected to mbed but MATLAB carries out the
calculations and control.
MATLAB RPC: The MATLAB RPC library has been updated to improve the way it
works. The classes are now all in a separate name space. This means that the interface
can now be used from within a function, callback or custom class, as well from the
command line or within scripts. Existing scripts will work with the new library but
require you to add a line of code to the top of the script (see Fig. 3.31).
MATLAB Code: The MATLAB classes have been designed to make it feel very similar
to programming directly on mbed. Here is the complete MATLAB code required to flash
an LED ten times and then close the serial port. The RPC library is contained within
the “mbed“ name space, this means that you must first either import the mbed package
(using “import mbed.*”) or prefix all classes with the name space (e.g. “mbed. Serial
RPC (...)”). More examples of this format can be found in the source files.

Figure 3.31 Screen shot of Hello World for serial RPC


’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ171

The first step when programming for mbed in MATLAB is to create your mbed object.
You do this by creating an mbed object from the class for the relevant transport
mechanism. This can be serial or HTTP (see Fig. 3.32).

Figure 3.32 Screen shot of an example of building an mbed object by HTTP

As Embedded Ethernet Sniffer: The word sniffer is shorthand for “packet sniffer”, a
common networking term. A packet sniffer is a network monitoring tool that captures
data packets and decodes them into a desirable form for a user. Generally, they're
employed to debug and monitor network problems (see Fig. 3.33).

Figure 3.33 Protocols supported by the E-Sniff project


172ȳComputer Interfacing and Automation

An embedded sniffer occupies a spot in a LAN much as a normal computer would


(Fig. 3.34). It simply displays a snapshot of the data traffic at a given moment. An
embedded Ethernet sniffer is a passive device that never transmits data onto a LAN.
It’s configured to trap and capture data, based on a few parameters provided by a user.
When the target computer was used to browse the Internet. Implementing embedded
Ethernet requires the use of the off-the-shelf Ethernet controller as an Internet-ready
communication port in a design. The three parameters of interest are Ethernet addresses,
IP addresses, and TCP port numbers. We’ll begin by examining the fundamental concepts
and
building blocks for an Ethernet Sniffer used to monitor and capture TCP/IP frames.

(a) (b)
Figure 3.34 (a) Test bench setup; (b) Demo of working of Ethernet sniffer

A packet sniffer is any device that does not discard frames in the manner described
above. This is referred to as putting the interface into promiscuous mode. By processing
and logging all the packets going over the bus, a packet sniffer can eavesdrop on
communications between other hosts on the network. This enables interested parties to
view any and all network traffic, including emails, instant messages, remote logins, etc.
Thus, a packet sniffer can be used to verify network performance, troubles hoot net
work errors, and perhaps most importantly, intercept “confidential“ communications
between other users of the network. The computers transmitting and receiving give no
indication that the traffic has been intercepted, making a properly implemented packet
sniffer undetectable to the average user (see Fig. 3.34).

3.12.7 Own ARM mbed Board: Design Details & Programming

The small size OWN ARM-MBED compatible board is usually used with motherboard
which has several variants for measuring pressure, level, etc. (see Figs. 3.35 to 3.37).
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ173

Figure 3.35 The own board: ARM-40 pin DIP: View from top and bottom

Figure 3.36 View of own daughter board sitting on DIP 40-pin IC socket of an
own motherboard for device design
174ȳComputer Interfacing and Automation
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ175

Figure 3.37 Hardware design schematics using N × P 1768

Firmware testing
The following are a few experiments performed, and tested to compare the compatibility
of ARM mbed board with our own board (see Figs. 3.38 and 3.39).
Experiment 1

Figure 3.38 VFD display with SPI interface


176ȳComputer Interfacing and Automation

Aim: To display the moving string “JOBY“ and “ALAN“ in an SPI display, using this
board.

Figure 3.39 Schematic diagram

Open the compiler from the cloud to write the program as follows:
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ177

Compile for LPC1768


The program in C++ is as follows:
////program for single spidiaply
#include "mbed.h"
SPI spi(p5, p6, p7); // mosi, miso, sclk
//DigitalOut cs(p8); // this is cs , in display it is STB
DigitalOut cs(p27);
int main() {
int offset=0;
while(1) {
offset=offset & 0x000F ;
// spi configuration
spi.format(16,3);
spi.frequency(1000000); // spi freq 10 KHz
// initialize display 8 bit interface cs=1
cs = 0;
spi.write(0xF830);
cs=1;
wait(.1);
// dis clear
cs = 0;
spi.write(0xF80C); //0C
cs=1;
wait(.1);
////
// clear all chars
cs = 0;
spi.write(0xF801);
cs=1;
wait(.1);
///
// take cursor to line1 0,0
cs = 0;
spi.write(0xF880+offset);
cs=1;
wait(.1);
//write A
178ȳComputer Interfacing and Automation

cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA4A);
cs=1;
wait(.1);
//write A
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA4F);
cs=1;
wait(.1);
//write A
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA42);
cs=1;
wait(.1);
//write A
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA59);
cs=1;
wait(.1);
//// take cursor to line 2 0,0
cs = 0;
spi.write(0xF8C0+offset);
cs=1;
wait(.1);
//write B
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA41);
cs=1;
wait(.1);
//write B
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ179

spi.write(0xFA4C);
cs=1;
wait(.1);
//write B
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA41);
cs=1;
wait(.1);
//write C
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0xFA4E);
cs=1;
wait(.1);
offset = offset+1;
}
}
Compile the program to generate spidisp.bin in d:\bin2hex directory
In command prompt, type bin2hex file1 file2 as below:
180ȳComputer Interfacing and Automation

Start the Flash Magic program (below).

Now try ISP->read device signature. You will see as below:


’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ181

Suppose you get a message like the one given below while doing ISP->read device
signature.

Power ON/OFF/ON the:PC1768 IUAC board power momentarily and then click ISP->read
device signature, then it may work.
Close
Now START programming.
You will see LEDs blinking on ISP programmer while transfer of data.
See the progress
Now Connect SPI display to LPC_JOBY board and see SPI display flashing “JOBY“
“ALAN”
182ȳComputer Interfacing and Automation

You will get the finish message as below:

Result: The SPI display (Noritake VFD Model) was connected to both the boards on
after another and found to be working the same way in both.

Experiment 2

Aim: To write string of data “joby“ through USB port every 0.25 second in a loop

Figure 3.40 Schematic diagram


’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ183

Open the compiler as follows (you may use Keil MicroVision 4 for development):

Compile for 1768


The program in C++ is as follows:
#include "mbed.h"
Serial device(p28,p27); // tx rx
int main() {
device.baud(9600);
for (;;)
{
wait(0.25);
device.printf("joby\n");
}
}
Compile the program to generate spidisp.bin in d:\bin2hex directory
In command prompt, type bin2hex file1 file2 as below:
184ȳComputer Interfacing and Automation

Start the Flash Magic program


’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ185

Now try ISP->read device signature. You will see as given below.

Suppose you get a message like the one given below while doing ISP->read device
signature

Power ON/OFF/ON the PC1768 IUAC board power momentarily and then click
ISP->read device signature, then it may work.
Close
Now START programming
You will see LEDs blinking on ISP programmer during transfer of data
See the progress
Now to test the experiment result, do the following
1. Remove the ISP programming cable from LPC_JOBY board
2. Connect a cable ( two wire) joining pin 27 and pin 28 to FDTi chip
3. Connect USB cable (one end micro USB and the other end Flat-USB) to PC
4. Open Tera Term VT serial port emulator as follows
186ȳComputer Interfacing and Automation

If the above screen doesn’t appear, check the serial port setup by setup->serial port and
ensure the settings as follows:

Now change the terminal settings as followed by setup->terminal


’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ187

Now the window looks much better as follows, as the end of character of every line
is terminated by LF:

3.13 CONCLUSION

The ARM Embed compatible low-cost DIP device using LPC 1768 ARM chip with USB
output was designed, fabricated and tested for off-line programming via flash magic
for building embedded applications. The MBED LPC1786 with USB is best suitable and
also quite compatible with Ethernet but it may affect the analog signal performance a
bit due to heavy current switching of Ethernet PHY layer transformer. But we have
188ȳComputer Interfacing and Automation

presented in this chapter, our design has additional features as compared with available
ready boards in the market with a low cost suitable for low noise applications. With the
fast development of the field of applications of the network, digital distributed control
system, it is necessary to make a higher demand of the functioning accuracy and reliability
of the system. Our embedded system can adapt to the strict requirements of the data
acquisition and control system such as the function, reliability, cost, size, power
consumption, and remote access and so on.

REFERENCES

1. http://developer.mb
2. ed.org/handbook/CAN/SI
3. http://www.standardics.nxp.com/support/documents/microcontrollers/pdf/user.
manual.lpc17xx.pdf,Chapter 32, Page 605 onwards.
4. www.flashmagictool.com
5. http://mbed.org/handbook/SerialPC
6. http://sockets.mbed.org
7. http://cegt201.bradley.edu/projects/proj2007/dsniff/senprojreport.pdf1
8. E-sniff: An Embedded Ethernet Packet Sniffer by Alex Hoyl and Advisors:Mr.
Steven Gutschlag, Dr. Aleksander Malinowski
9. http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1
406&dDocName=en546569.
10. http://in.mathworks.com/?s_tid=gn_mlc_main
11. http://in.mathworks.com/academia/courseware/?s_tid=hp_mi_mlcourse_101
12. http://cegt201.bradley.edu/projects/proj2007/dsniff/senprojreport.pdf1
13. J Antony et al.International Journal of Instrumentation, Control & Automation
(IJICA), Volume 1, Issue 1, 2011
14. dw2013-rapid-prototyping-with-mbed pdf
15. http://www.electronicshub.org/
difference-between-microprocessor-and-microcontroller/
16. http;://en:wikipedia.org/wiki/file:freq_synk
17. http;://2.blogspot.com/cbiom.Flash Magic
18. http;://processor.wikiti.com/php
19. www.webopedia.com/teraterm

REVIEW QUESTIONS

1. What is a microprocessor and how it’s different from a microcontroller?


2. What are the advantages of a microcontroller over a microprocessor?
’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ –‹ŽŽȱ Žœ’—DZȱ Š› Š›Žȱ —’—ŽŽ›’—ȳ189

3. Write a note on FT232R USB UART IC.


4. What are a micro memories? How are they classified? What is a flash memory?
5. Explain the role of RS-232 Board in programming the microprocessor.
6. What is flash magic? Give the different steps in starting the microprocessor
memory.
7. Explain how to generate a hex file using Keil.
8. Give the block diagram of the flow of ISP.
9. If the reference signal is 100 kHz, and the divider can be preset to any value
between 1 and 100. The error signal produced by the comparator will only be
zero when the output of the divider is also 100 kHz. For this to be the case, what
the VCO must run at and produce an output?

ANSWERS

2 & 3.
s The instruction set of microcontroller is simpler than a microprocessor, so your
program lines are less and simple.
s The microcontroller has inbuilt memory whereas microprocessor doesn't have.
So if you are using a processor, then you have to interface external memory
(RAM or ROM). So by using microcontroller your circuit size became less.
s As compared to processor IC controller’s ICs are easily (most popular 8051)
available in the market and also cheap so your application cost will become less.
s A microcontroller has memory on a single chip so it performs faster than a
processor.
s A microcontroller also has I/O pins on its chip so you can directly connect your
sensor to sense temperature and also display device if you are using processor
then you need another IC, and that will connect processor with your sensor and
display device, and that makes your circuit bulky and expensive.
4. The flash memory chip is a close relative to the EEPROM; it differs in that it can
only be erased one block or “page“ at a time. It is a solid state chip that maintains
stored data without any external power source. Capacity is substantially larger
than that of an EEPROM, making these chips a popular choice for digital cameras.
5.
s Step-1 Communication
s Step-2 Erase
s Step-3 Hex file
s Step-4 Options
s Step-5 Start
8. Fd = FŖȹ/N For this to be the case, the VCO must run at the frequency which is 100
kHz × the divider count value. 100 kHz for a count of 1, 200 kHz for a count of 2,
1 MHz for a count of 10 and so on.
PROPORTIONAL INTEGRAL DERIVATIVE
4 (PID)

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋ What a PID controller is?
Ȋ Practical analog and digital PID implementations.

4.1 INTRODUCTION
PID stands for “Proportional Integral Derivative”. A PID controller can be explained as
a generic loop feedback mechanism proven for so many years. It can measure any process
variable (e.g., temperature, pressure, speed, etc.), and it will check against a desired set
point (e.g., 100°C or 1 psi or 100 rpm). It then attempts to adjust the process variable
by changing the controller output (e.g., PWM signal to an electric heater) which will
bring the process variable closer to the desired set point over a time period which is
decided by three constants P, I and D.

4.2 ANALOG PID

A PID controller is a control loop feedback mechanism (controller) widely used in


industrial control systems. It calculates an error value as the difference between a
measured process variable and a desired set point. The controller attempts to minimize
the error by adjusting the process through the use of a manipulated variable. There is
a three-term control: the proportional, the integral and derivative values, denoted P, I,
and D, and also three basic mathematical functions are applied to the error signal, Verror
= Vset(or Vref) - Vsensor. This error represents the difference between where you want to

P Kp e (t)

r (t) e (t) t
y(t)
+
Setpoint S Error I K t Ú e ( t ) dt S Process Output
0

de (t )
D Kd
dt

Figure 4.1 Block diagram of PID controller


›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ191

go (Vset orVref), and where you’re actually at (Vsensor). The controller performs the PID
mathematical functions on the error and applies their sum to a process (motor, heater,
etc.) If tuned correctly, the signal Vsensor should move closer to Vset. (see Fig. 4.1)

4.2.1 Defining Mathematically

The PID control scheme is named after its three correcting terms, whose sum constitutes
the manipulated variable. The proportional, integral, and derivative terms are summed
to calculate the output of the PID controller. Defining u(t) as the controller output, the
final form of the PID algorithm is: (see Fig. 4.2)
t
d
u(t )= MV(t )= K p e (t )+ Ki Ú e(t ) dt + Kd e(t )
0
dt
where
Kp: Proportional gain, a tuning parameter
Ki: Integral gain, a tuning parameter
Kd: Derivative gain, a tuning parameter
e: Error = SP – PV
t: Time or instantaneous time (the present)
T: Variable of integration; takes on values from time 0 to the present t.

Figure 4.2 Analog PID controller


192ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

A first level tuning is done manually as follows:


1. Set Kp : Starting with Kp = 0, Ki = 0 and Kd = 0, increase Kp until the output starts
overshooting and ringing significantly.
2. Set Kd : Increase Kd until the overshoot is reduced to an acceptable level.
3. Set Ki : Increase Ki until the final error is equal to zero.
Output process: Eout represents a simplified model of a process to be controlled like
heater temperature. To include the effects of the heater’s thermal mass, we’ve added
some time delay into the output using two cascaded RC filters. Although Vout is simulated
in volts, we know it really represents other variables, like temperature in °C.
Sensor: The sensor tells you, typically by a voltage, what’s happening at the control
system output. For temperature, a thermistor circuit could produce 0.01 V/°C. Esensor
models this feedback device. Because a sensor does not respond instantly, an RC filter
is also added here to model its finite response time.

4.3 DIGITAL PID CONTROLLER

Nowadays, digital controllers are used in many large- and small-scale control systems,
replacing the analog controllers. It is now a common practice to implement PID controllers
in its digital version, which means that they operate in discrete time domain and deal
with analog signals quantized in a limited number of levels. Moreover, in such controller
we do not need much space and they are not expensive. A digital version of the PID
controller is shown in Fig. 4.3.
e (t)

A/D

kp eD [k]

k + c D [ j]
+
k i  eD [ n ]
e D [ j] n=0
+

kd (eD [k] – eD [k – 1]

D/A

c ( t)

Figure 4.3 Digital PID controller

In its digital version, the integral becomes a sum and the deferential a difference. The
continuous time signal e(t) is sampled in fixed time interval equals a determined sample
period, here called Tc (in figure Tc = 1). An A/D (analog to digital) converter interfaces
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ193

the input and a D/A (digital to analog) converter interfaces the output. This sampled
and digitalized input, called eD[j], exists only in time instants t = kTC for all k t 0. A
lower bound for the sample period is the computing time of a whole cycle of the digital
PID (which includes the A/D and D/A conversion).

4.4 ANALOG VS DIGITAL PID

At the basic principles of this technology, control circuits are encountered very often in
electronics. For instance, a voltage regulator is present in almost every circuit. More
elaborate controllers for dealing with other physical quantities, such as rotational speed
velocity, temperature, pressure, flow and so on. Control technology deals with finding
solutions for such problems.

4.4.1 Analog vs Digital PID Controller

It is far easier to tune a digital PID controller, than an analog controller. Tuning an
analog controller, requires multi-turn potentiometers and a lot of actual “tweaking” of
those pots. Occasionally, you need to change out capacitors in an analog controller, too.
Once pot. values have been fixed, and permanent resistors have been soldered in place,
there is amplifier, resistor, and capacitor drift to contend with. Analog systems sometimes
require precision-valued components, which are expensive.
In a digital system, all you have to do is re-compile some code with the new coefficients
coded in. This takes less time, and less effort (than soldering, picking component values,
etc.)
In general digital systems are more immune to electric interference, and are far less
prone to drift in calibration.
They are essentially more reliable.
Digital controllers can generally communicate with a central computer through a
digital communication bus. They can often also be configured and tuned using the same
bus (one does not have to physically go to each device to calibrate and tune it as is the
case with analog controllers). Digital controllers are becoming less expensive than analog
controllers as well.
Analog controller combines several advantages over a digital controller which can be
summarized as follows.
1. An analog system provides larger bandwidth, higher speed and eliminates
quantization noise.
2. High performance data converters are required for a digital signal processing
controller (DSP-based) controller. The performance of the converter in terms of
its speed, conversion precision and noise greatly influences the fidelity of the
controller. An analog controller eliminates the need for ADCs and DACs, thus
improving performance and saving power, space and cost. As the power of the
DSP is reduced, the power consumption of the data-converters will dominate,
thus their elimination is very advantageous.
194ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Still why aren’t analog PID controllers designed and used despite these advantages? The
answer to this question is the unavailability of electronically-reconfigurable, reliable and
precise analog arrays. The controller must be reconfigurable because the PID parameters
have to be tuned according to the plant. The precision and range of the reconfigurable
system must provide sufficient flexibility to implement PID control for a variety of plants.
The non-existence of accurate simulators for FPAAs (field programmable analog array)
(including parasitic and interconnect affects) is another problem.

4.5 FIRMWARE FOR DIGITAL PID CONTROL

There is no specific way a PID should be implemented in the firmware; the methods
discussed in this application only touch upon a few of the many possibilities. The PID
routine is configured in a manner that makes it modular. It is intended to be plugged
into an existing piece of firmware, where the PID routine is passed the 8-bit or 16-bit
error value (Desired Plant Response – Measured Plant Response). Therefore, the actual
error value is calculated outside of the PID routine. If necessary, the code could be easily
modified to do this calculation within the PID routine. The PID can be configured to
receive the error in one of two ways, either as a percentage with a range of 0 to 100%
(8-bit), or a range of 0 to 4000 (16-bit). This option is configured by a #define statement
at the top of the PID source code with the PID’s variable declarations. (see Fig. 4.4)

Start
Application initialization
Call PIDInitialize

ISR (with PID code)


Application main
Code...
Code...(Calculates Error)

error0:error1 Call PIDMain pid_out0:pid_out2

Code...(Applies PID Result to Plant)


Code...
End

Figure 4.4 PID firmware implementation

The gains for proportional, integral and derivative all have a range of 0 to 15. For
resolution purposes, the gains are scaled by a factor of 16 with an 8-bit maximum of
255. A general flow representing the PID routine would be implemented in the main
application code is presented in Fig. 4.4.
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ195

4.6 ACCURATE WATER HEATER SYSTEM DESIGN


Ethernet I/F
DC power
A digital display unit heater (0 to 20W)

IA current source

+ 0 to 100°C V
Desired Solid state AC
PID algorithm Arm
temperature – PWM relay power
inside processor
(e.g. 50°C) (OPT.ISO) transformer
processor

ADC

Water

0 to 10 V DC Heater
Meter Thermocouple
(0–100°C sensor
T-sensor Bucket
of water
Figure 4.5 Design of water heater

4.6.1 Proportional Control Theory

In the proportional controller, the controller output is proportional to the error signal,
which is the difference between the set point and the process variable. In other words,
the output of a proportional controller is the product of the error signal and the
proportional gain. This can be mathematically expressed as (see Fig. 4.5):
Pout = Kpe(t) + p
Here, p – controller output with zero error.
Pout – output of the proportional controller
Kp – proportional gain
e(t) – Instantaneous error at time t, e(t) = SP-PV
SP - set point
PV- process variable
The sensors are often used in the temperature measurements/sensing of body
continuously. Examples include thermocouple, diode thermometer, etc.
Do we need PID?
Yes, we can measure the temperature using the PID controller. Voltage is electrical
analogy to temperature.
In proportional control
A voltage, VP(t) proportional to eR(t) is sent to the heater
VP(t) = KPeR(t))
where Kp is the proportional constant.
196ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Assertion
In proportional control, the temperature will never reach the set value, but will settle
at lower value.
Reason
When T = 0, eR(t) = 0, VP = 0. No power is given to the heater. This will happen at
time t = infinity only, i.e., the temperature will never reach the set value.

4.6.2 Water Heater System in PI Control

Proportional integral control


Proportional + Integral (PI) controllers were developed because of the desirable property
that systems with open loop transfer functions of type 1 or above have zero steady state
error with respect to a step input.
The combination of proportional and integral terms is important to increase the speed
of the response and also to eliminate the steady state error. The PID controller block is
reduced to P and I blocks only as shown in Fig. 4.6.

R+ e U Y
P Plant

Controller
I block

Figure 4.6 Proportional integral (PI) controller block diagram

The proportional and integral terms is given by:


t

u (t )= K p e (t )+ K i Ú e (t )d t
0

Here, Kp and Ki are the tuning knobs adjusted to obtain the desired output.
The electrical circuit is shown as follows (Fig. 4.7):

1 C1 R2
sT1
R1
e (t)
– u (t)
E (s) U(s)
KP + +

Figure 4.7 Electrical circuit


›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ197

Tuning PI controllers
General approach to tuning:
1. Initially there is no integral gain (TI large)
2. Increase KP until we get satisfactory response
3. Start to add in integral (decreasing TI) until the steady state error is removed in
time.
Anti-windup in I and PI controllers
Under some operating conditions, non-linearities in the plant or controller can stop
an integral controller from removing the steady state error. If the integrator output is
not limited, then during this time the total of the integrated error will continue to build.
Once the restrictions are finally removed, problems can arise because this built up
energy must be removed before the integral control can act normally. This can take a
long time. To avoid this, anti-windup circuits are added that place ±limits on the integral
total. These limits are usually placed on the summed output of the P&I controller as
well (see Fig. 4.8 and Fig. 4.9).

C1 R2

R(s) E(s) R1 U(s) C(s)


+ –1 – Gp (s)
– +

Figure 4.8 P&I controller

7 1 5 U2 VCC
15 V 3 15 V
+ R7 VCC
6

VCC 1 2
– 10 kW
2 R15
100 kW 4
C1 741 25 W
R10 Key = A
1 MW 50% 10 uF 14
7 1 5
U5
R11 12 Q1
7 1 5
U3 3
7 1 5 U1 + 6
R12 13
3
100 kW 50% 11 + R6 8
6 2
D2498
Key = A + R9 7C2 3 – 10 kW
6 2
– 10 kW 9
R14 4
R8 741
2
– 1 kW 10 mF
16 10 kW 741 4 741
4
100 kW 4 10 kW
15 R13 50%
Key = A
From LM35 0
10 kW 7 1 5 U4
10 3
+ 6
R5
R4 5 2
– 10 kW
10 kW 4 741
100 kW 50% 6
Key = A

Figure 4.9 An analog PID temperature controller circuit (OPAMP based analog)
198ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

4.6.3 Water Heater System in PID Control: The Analysis

A sudden change in system conditions may lead to sudden change in its temperature.
KP and KI both will act on the system and temperature may overshoot
Term proportional to the rate of change in temperature is required. Term proportional
to derivative of eR(t) will counter
d
Do ut = K d e (t )
dt
The PID control output:
t
d
u (t )= MV (t )= K p e (t )+ K i Ú e (t ) d r + K d e (t )
0
dt

A water heater closed loop system block diagram is shown in Fig. 4.10.

Va (s) PID
Voltage Differential Amplier; Kp
amplier System
reference VR
VR er ( t ) + PID(t)
VR + Integrator; Kp ++
– Heater

To set Differentiator; Ki
tem. T (t)
Vth ( t ) Adder

eR (t) = VR – VTH(t) Vth (t) T(t)


Thermocouple
Sensor
Figure 4.10 A closed loop system , with feedback provided by the sensor
(The heater should attain the set temperature as fast as possible and should
continue to Remain at the set temperature)

4.7 ANALYSIS OF OUTPUT WITH RESPECT TO INPUT

Aim:
Ȋ Find the Laplace transform of individual blocks – s-domain.
Ȋ Find the impulse response function, h(t) of individual blocks.
Ȋ Find the transfer function, H(s) (ratio of output to input in s-domain) of the
individual blocks.
Ȋ Integral/differential equations become algebraic equations in “s”.
Steps:
Ȋ Find the response (temp), when the input, VR(t) is set at a given value
Ȋ Analyse in time domain
Ȋ Find the impulse response function of the whole system
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ199

Ȋ Convolute the impulse response function with input to get the output
Ȋ Analyse in s-domain (complex domain)
Ȋ Find the transfer function of the whole system
Ȋ Multiply the transfer function of the whole system by the input (s-domain)
Ȋ Take inverse Laplace transform to get the output in time domain

4.7.1 Block-by-Block Analysis

PID is a controller which is widely used in industrial control systems with control loop
feedback mechanism. This control system involves three-term control: the proportional,
the integral, and derivative values. The PID controller theory based on the following
equation:
t
d
u (t )= MV (t )= K p e (t )+ K i Ú e (t )d t + K d e (t )
0
dt
where
Kp: Proportional gain, a tuning parameter
Ki: Integral gain, a tuning parameter
Kd: Derivative gain, a tuning parameter
e: Error
t: Time or instantaneous time (the present)
t: Variable of integration; takes on values from time 0 to the present
Laplace transform
Laplace transform is used to convert a function f(t) in the time domain to a function
F(s) in the s-domain (s is a complex number).

F (s ) = Ú exp ( - st ) f (t )d t

Laplace transform makes complex differential equation into simple algebraic equation
to solve easily.
Disturbances(s)

Set point Controller Process


(SP) output variable
PID controller Process

Measured
process variable

Sensor

Figure 4.11 General PID controller with sensor


200ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Feedback
1. The PID block
P
eR (t) + VPID (t)
I +
+

D
t
deR
V( PID ) (t ) = K p (t )e R (t ) + K1 Ú e R (t )d t + K D
t0
dt
LVPID (t ) =VPID (s)
K1
VPID (s ) = K P E R (s ) + (s ) + sK D E R (s )
ER
Assming zero initial value
The transfer function:
K1
H PID (s ) = VPID (s )/ E R (s ) = K P + + sK D
s
2. The heater
The heater
VHTR (t) T (t)

VHTR(t) = Input voltage


For a short duration input voltage applied at t = 0, the heater temperature
rises to finite value and for t > 0 decreases exponentially.
T(t)ve-at
The transfer function: HHTR(s) = VHTR(s)/W(s) = 1/(1+s)
3. Temperature sensor (thermocouple)

The heater
Temperature, T (S) Voltage, VTH (s)

Transfer function: HTh(s)/␶(s)


If the sensor gives 1v for 1k (after signal conditioning), HTh(s)
4. Reference voltage source

Voltage, VR(s)
VR (t)

A constant voltage source, calibrated to set temperature


›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ201

5. Differential amplifier

VR (t) +
eR (t)

VTh(t)

Compares the temperature sensor voltage and the reference voltage and gives a voltage
proportional to the difference between them
V (t ) - V (t ) = e (t ) , the error signal
R Th R

VR (s ) - VTh (s ) = E R (s )
PID control – analysis in s-domain
HPID (s)
P
VR(s) ER(s) VPID (s)
Refer. + I + HHTR ( s )
– – VHTR(s)
D τ(s)
VTH(s)
VTH(s) τ(s)
Hth ( s )

Aim: To find transfer function of the whole system that is to find the ratio of
output (␶(s)) to input (VR(s))
␶(s) = VHTR(s) HHTR(s) = VPID(s) HHTR(s) VHTR(s) = VPID(s)
␶(s) = ER(s) HPID(s) HHTR(s) VPID(s) = HPID(s) ER(s)

4.7.2 PID Control: Analysis in s-Domain

The transfer function for whole system is:


ts H PID (s ) H HTR (s )
H(s) = =
us ÈÎ1 + H Th (s )H PID (s )H HTR (s )˘˚

where the individual transfer function is: HTh (s) = 1


Ki
H PID (s ) = K P + + sK D = (s 2K D + sK p + K i )/ s
s
1
H HTR (s ) =
1+ s
s 2k D + sK p + K i
H (s ) =
s 2 (1 + K D ) + s (1 + K p ) + K i
202ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Output can be found for any input, as H(s) is known.


If the input VR(t) = G(t), then output ␶(s) = H(s); L{G (t)} = 1
If the input VR = u(t), then output ␶(s) = H(s)/s; L{u(t)} = 1/s
Let VR(t) = u (t); u(t) is unit step, KP = 1, KI = 5 & KD = 0

s 2 K D + sK p + K I s+5
H(s) = =
s 2 (1 + K D ) + s (1 + K p ) + K I s 2 + 2s + 5
VR(s) = 1/s

s+5 s +1
␶(s) = H(s) VR(s) = u (1/s) = (1/s) –
s + 2s + 5
2
(s + 1)2 + 4
T(t) = L-1{␶(s)} = 1- e-tcos2t
Results
In the above transfer function, there are two poles:
The first one is at s = 0
The second one, when (s + 1)2 = – 4
which means s + 1 = Root of (– 4) = – j2 or + j2 = 0+ j2 or 0 – j2
Therefore, we have poles at 0 + j0 and 0 +/ – j2 (Fig. 4.12)
1.5
Reference signal
Ki = 2

Kp = 1 Ki = 1 Kd = 1

0.5

Ki = 0.5

0 2 4 6 8 10 12 14 16 18 20

Figure 4.12 Graph showing the output signal of P, PD and PID controllers
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ203

4.7.3 Stability Analysis

A controller is a device that gives desired output based on the given input signal. The
input signal for the controller is the error signal which is derived from the measured
output and desired or set point values. Figures 4.13 and 4.14 show a typical controller
outline.

Reference + PID
Plant Output
– controller

Figure 4.13: A typical controller unit attached to the load

Controller

Summing
junction
Measured Control Output to
variable Erro action control valve

Set pont

Figure 4.14 A typical controller unit outline

Integral action is frequently used in control systems to eliminate steady state tracking
error. By adding an integrator with a gain Ki [V/(mm sec)] to the PD controller, a
Proportional-Integral-Derivative (PID) controller is obtained, as shown in figure.
Assuming that the integral gain is nonzero.
Controller classification
There are four types of controllers used in practical applications.
1. Proportional controller or P-controller
2. Proportional and integral controller or PI-controller
3. Proportional and rate controller or PD-controller
4. Proportional, integral and rate controller or PID-controller
Each mode of control has characteristic advantages and limitations. Proportional
control is also referred to as throttling control. The integral control method is also known
as reset control and rate control is known as differential control.
Stability
The major advantage of integral controllers is that they have the unique ability to
return the controlled variable back to the exact set point following a disturbance.
Disadvantages of the integral control mode are that it responds relatively slowly to an
204ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

error signal and that it can initially allow a large deviation at the instant an error is
produced. This can lead to system’s instability and cyclic operation. For this reason, the
integral control mode is not normally used alone, but is combined with another control
mode.
The main disadvantage of the proportional control mode is that a residual offset error
exists between the measured variable and the set point for all but one set of system
conditions. The main disadvantages of the integral mode is that the controller output
does not immediately direct the final control element to a new position in response to
an error signal.

4.8 ACCURATE HEATER OF A COPPER BLOCK

Figure 4.15 Block diagram of heating system for copper block


Working
1. Accurate heating is completely based on the PID control principles, here first the
desired temperature is set and then power is given to the heater.
2. As the temperature of the heater increases the power required becomes less and
is maintained at a level when the equilibrium temperature between the heater
and the surrounding is achieved.
3. In order to achieve the above system one needs to work on complete hardware
which comprises high density electronics boards, adequate firmware for display
purpose and finally the software that collects the required data and plot graphs
while working of the instrument
4. Data is transferred though Ethernet and it is connected with the ARM processor
as shown in the figure which enables us to set the temperature value by our
system directly, and also receives the data and plot it simultaneously (see Fig.
4.15).
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ205

4.9 LOW-TEMPERATURE COOLING SYSTEM FOR VARIABLE TEMPERATURE


CALIBRATION SETUP (14 TO 409 KELVIN)

Alternate
Ethernet I/F DC power
heater 2
(0 to 20 W)
AC mains
1 A current source

+ 14 to 409 K V AC power
Desired PWM Solid state
PID algorithm processor transformer
temperature PWM relay
inside 48 V AC,
14 K to 409 K – (OPT. ISO)
processor Line arizer 15 A

DAC ADC
12 bit A digital
display unit 0 to 10 V
DC
10 mA
Display current Heater
0 to 409.5 K source
P,I,D etc. 0 to 10 V +
DC Amplier

CRYO cooler

Figure 4.16 Block diagram of the cooling system

4.10 DIGITAL PID CONTROL CODE (PSEDO CODE ONLY)

unsigned long lastTime;


double Input, Output, Setpoint;
doubleerrSum, lastInput;
doublekp, ki, kd;
intSampleTime = 1000; // sample time = 1 sec
void Compute()
{
unsigned long now = millis(); // current time
inttimeChange = (now - lastTime);
if(timeChange> = SampleTime)
{
/*This is to compute all error values*/
double error = Setpoint - Input;
errSum + = error; // error sum due to integration
doubledInput = (Input - lastInput); // error subtraction due
to differentiation
Output = kp * error + ki * errSum - kd * dInput; //
Compute output of PID
206ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

lastInput = Input; //update lastinput and lasttime


lastTime = now;
}
}
voidSetTunings(double Kp, double Ki, double Kd)
{
doubleSampleTimeInSec = ((double)SampleTime)/1000;
kp = Kp;
ki = Ki * SampleTimeInSec;
kd = Kd / SampleTimeInSec;
}

voidSetSampleTime(intNewSampleTime) // This is to change sample


time
{
if (NewSampleTime> 0)
{
double ratio = (double)NewSampleTime
/ (double)SampleTime;
ki * = ratio;
kd / = ratio;
SampleTime = (unsigned long)NewSampleTime;
}
}

REFERENCES

The Wikipedia article on PID controllers is an excellent place for understanding the
basic concepts. The control guru website also contains a wealth of easy to digest
information on how to implement and tune a PID controller.
1. http://www.physics.iitm.ac.in/~sercehep2013/PID_Kasi.pdf.
2. http://mbed.org/
3. http://nptel.ac.in/courses/108105063/pdf/L-14(SS)(IAC)%20((EE)NPTEL).pdf
4. http://research.microsoft.com/enus/um/people/jstokes/
implementationofpidcontrollersapr5.pdf
5. http://grietinfo.in/projects/MAIN/EEE2013/cd-24-main%20doc%20PID%20
USING%20ARDUINO.pdf
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ207

QUESTIONS & ANSWERS (1-5)

1. Draw outputs of PID controllers for P only, PI only & PID

Figure 4.17

In the above figure, it is clearly shown in four different graphs, i.e., proportional
output 1,derivative output 2, integral output 3 and summed output 4.
2. Explain the operation of Pulse Width Modulation?
Pulse-width modulation (PWM), or pulse-duration modulation (PDM) is a modulation
technique that controls the width of the pulse, formally the pulse duration, based on
modulator signal information. Although this modulation technique can be used to encode
information for transmission, its main use is to allow the control of the power supplied
to electrical devices, especially to inertial loads such as motors. In addition, PWM is one
of the two principal algorithms used in photovoltaic solar battery chargers.
208ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

1.5
V B
1.0

B (T), V (V) 0.5

–0.5

–1.0

–1.5
0 5 10 15 20
(ms)

Figure 4.18

The average value of voltage (and current) fed to the load is controlled by turning
the switch between supply and load on and off at a fast pace. The longer the switch is
on compared to the off periods, the higher the power supplied to the load.
The PWM switching frequency has to be much higher than what would affect the
load (the device that uses the power), which is to say that the resultant waveform
perceived by the load must be as smooth as possible. Typically switching has to be done
several times a minute in an electric stove, 120 Hz in a lamp dimmer, from a few kilohertz
(kHz) to tens of kHz for a motor drive and well into the tens or hundreds of kHz in
audio amplifiers and computer power supplies.
The term duty cycle describes the proportion of ‘on’ time to the regular interval or
‘period’ of time; a low duty cycle corresponds to low power, because the power is off
for most of the time. Duty cycle is expressed in percent, 100% being fully on.

Advantage of PWM

The main advantage of PWM is that power loss in the switching devices is very low.
When a switch is off there is practically no current, and when it is on and power is
being transferred to the load, there is almost no voltage drop across the switch. Power
loss, being the product of voltage and current, is thus in both cases close to zero. PWM
also works well with digital controls, which, because of their on/off nature, can easily
set the needed duty cycle.
PWM has also been used in certain communication systems where its duty cycle has
been used to convey information over a communications channel.

Working principle

Pulse-width modulation uses a rectangular pulse wave whose pulse width is modulated
resulting in the variation of the average value of the waveform. If we consider a pulse
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ209

waveform f(t), with period T, low value ymin, a high value ymax and a duty cycle
D (Fig. 4.18), the average value of the waveform is given by:
T
1
f (t )d t .
T Ú0
y=

As f(t) is a pulse wave, its value is ymax for 0 < t < D ◊ T and ymin for D ◊ T < t < T◊
The above expression then becomes:
1Ê ˆ
DT T

y = Á Ú ymax dt + Ú ymin dt˜


TË 0 DT ¯

D ◊ T ◊ ymax +T(1 – D)ymin


=
T
D ◊ Ymax + (1 – D) Ymin.

This latter expression can be fairly simplified in many cases where ymin = 0 as
y = D ymax From this, it is obvious that the average value of the signal ( y ) is directly
dependent on the duty cycle D.
The simplest way to generate a PWM signal is the intersection method, which requires
only a sawtooth or a triangular wave form (easily generated using a simple oscillator)
and a comparator. When the value of the reference signal (the sine wave in Fig. 4.19) is
more than the modulation waveform (upper half of Fig. 4.19), the PWM signal (lower
half of Fig. 4.19) is in the high state, otherwise it is in the low state.

1
PWM Signal

1
PWM Signal

Times
Figure 4.19
210ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Short note on sawtooth wave

The sawtooth wave (or saw wave) is a kind of non-sinusoidal waveform. It is so named
based on its resemblance to the teeth of a saw.
The convention is that a sawtooth wave ramps upwards and then sharply drops.
However, in a “reverse” (or inverse) sawtooth wave, the wave ramps downwards and
then sharply rises. It can also be regarded as the extreme case of an asymmetric triangular
wave.
While a square wave is constructed from only odd harmonics, a sawtooth wave’s
sound is harsh and clear and its spectrum contains both even and odd harmonics of the
fundamental frequency. Because it contains all the integer harmonics, it is one of the
best waveforms to use for subtractive synthesis of musical sounds, particularly bowed
string instruments like violins and cellos, since the slip-stick behavior of the bow drives
the strings with a sawtooth-like motion.

0.5
Amplitude

–0.5

–1
0 0.002 0.004 0.006 0.008 0.01 0.012
Time(s)
300

200
Amplitude (dB)

100

–100

–200
0 1 2 3 4 5 6 7 8 9 10
Frequency (kHz)

Figure 4.20

3. Draw the schematic diagram of an electronic PI controller.


Block diagram of electronic PI controller:
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ211

R+ e u Y
P Plant

Controller
I
block

Circuit diagram of electronic PI controller:


C1 R2

R(s) E(s) R1 U (s) C (s)


+ –1 – Gp ( s )
– +

The proportional and integral terms is given by:

u (t ) = K p e (t ) + K i Ú e (t )d t

Here, KP and Ki are the tuning knobs adjusted to obtain the desired output.

1 C1 R2
sT1
R1
e (t)
– u(t)
E(s) U (s)
KP + +

General approach to tuning

1. Initially, there is no integral gain (T large).


2. Increase KP until get satisfactory response.
3. Start to add in integral (decreasing T) until the steady state error is removed in
satisfactory time.
4. What are the major drawbacks of analog controllers?
The answer to this question is the unavailability of electronically reconfigurable,
reliable and precise analog arrays. The controller must be reconfigurable because the
PID parameters have to be tuned according to the plant. The precision and range of the
reconfigurable system must provide sufficient flexibility to implement PID control for
a variety of plants. The non-existence of accurate simulators for FPAAs (field
programmable analog array) (including parasitic and interconnect affects) is another
problem.
212ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Short Note on FPAA

A field-programmable analog array (FPAA) is an integrated device containing configurable


analog blocks (CAB) and interconnects between these blocks. Unlike their digital cousin,
the FPGA, the devices tend to be more application driven than general purpose as they
may be current mode or voltage mode devices. For voltage mode devices, each block
usually contains an operational amplifier in combination with programmable configuration
of passive components. The blocks can, for example, act as summers or integrators.
FPAAs usually operates in one of two modes: continuous time and discrete time.
Ȋ Discrete-time devices possess a system sample clock. In a switched-capacitor
design, all blocks sample their input signals with sample and a hold circuit
composed of a semiconductor switch and a capacitor. This feeds a programmable
op amp section which can be routed to a number of other blocks. This design
requires more complex semiconductor construction. An alternative, switched-
current design, offers simpler construction and does not require the input
capacitor, but can be less accurate, and has lower fan out - it can drive only one
following block. Both discrete-time device types must compensate for switching
noise, aliasing at the system sample rate, and sample-rate limited bandwidth
during the design phase.
Ȋ Continuous-time devices work more like an array of transistors or op amps which
can operate at their full bandwidth. The components are connected in a particular
arrangement through a configurable array of switches. During circuit design, the
switch matrix’s parasitic inductance, capacitance and noise contributions must
be taken into account.
5. Given a continuous time PID controller of water heater controller with KP = 1, KD
= 5, KI = 0, find T(t) in time domain.
PID control – analysis in s-domain
HPID(s)
P

VR (s) E R (s) + VPID(s)


Refer. + I + HHTR (s)
– + VHTR(s)
t(s)
D
VTH (s)
VTH (s) t(s)
Hth (s)

Aim: To find transfer function of the whole system, that is, to find the ratio of
output (␶(s)) to input (VR(s))
␶(s) = VHTR(s) HHTR(s) = VPID(s) HHTR(s) VHTR(s) = VPID(s)
␶(s) = ER(s) HPID(s) HHTR(s) VPID(s) = HPID(s) ER(s)
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ213

PID control: Analysis in s-domain

The transfer function for whole system is:


ts H PID (s ) H HTR (s )
H(s) = =
v s ÈÎ1 + H Th (s ) H PID (s ) H HTR (s )˘˚

where the individual transfer function are: HTh(s) = 1

H PID (s ) = K p +
Ki
s
( )
+ sK D = s 2K D + sK P + K I / sH HTR (s ) =
1
1+ s

s 2 K D + sK p + K I
H(s) =
s 2 (1 + K D ) + s (1 + K P ) + K I

Output can be found for any input, as H(s) is known


If the input VR(t) = ␦(t), then output ␶(s) = H(s); L{␦(t)} = 1
If the input VR = u(t), then output ␶(s) = H(s)/s; L{u(t)} = 1/s
Let VR(t) = u(t); u(t) is unit step, KP = 1, KI = 5 & KD = 0

s 2 K D + sK P + K I s+5
H(s) = = 2
s (1 + K D ) + s (1 + K P ) + K I s + 2s + 5
2

VR(s) = 1/s

s+5 s +1
␶(s) = H(s) VR(s) = (1/s) = (1/s) –
s + 2s + 5
2
(s + 1)2 + 4
T(t) = L-1{␶(s)} = 1- e-tcos2t

PROJECT
EXPERIMENTAL SETUP FOR PID CONTROLLED WATER HEATING SYSTEM

Main parts of experimental setup

1. Power system [MOSFET]


2. Thermocouple
3. Temperature meter
4. Heat sensor
5. Digital PID controller
6. Water heater
7. Water bucket
8. LabVIEW (software) for plotting graphs
214ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 4.21 Experimental set up

Block diagram of experimental setup

The block diagram of our experimental setup is given below (see Fig. 4.22):

Set point PID controller


temperature Power
+
T1 Ethernet to system

connect KP KI KD
with pc
Input to ADC
temperature T2

to PC

Thermocouple
0–10 Volt temperature Water bucket
meter

Thermocouple

Figure 4.22 Block diagram of experimental set up


›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ215

Description of experiment

At first we have taken a bucket of water filled with almost 90 percent of water. We
insert a water heater within water at proper depth. We connect a power system (basically
made by metal oxide field effect transistor) with the heater. Our PID controller is
connected with the power system. A temperature sensor connected with PID (which is
basically a thermocouple) is made to have contact with the water of the bucket. Now
we set our desired temperature at a particular value in the PID. In the experiment we
have fixed the desired temperature at 50°C. After that we made the water heater on and
subsequently also made power system on. At first the water heater will heat the water
of the bucket using 100 percent power. So the temperature will increase rapidly. But
after some time we observe that the rate of increment in temperature slows down and
over the period of time power decreases with increasing time that we will observe in
the labVIEW calculation.

Figure 4.23 Water heated to 50°C

Now in the above picture we observe that the rate of increment of temperature is
higher initially but after 25 or 30 minutes the temperature is getting a fixed value with
a little fluctuation. We also observe that the power in the Y-axis at second graph is
decreasing with increasing time as the PID system connected with it restricts the power
supplied by the power system to get the desired the temperature. We can see from the
above picture that the power is 18.6 percent when the temperature is 49.9°C. The value
of proportional constant KP, integral constant KI, derivative constant KD are given by
12,2,0.1 respectively. In this picture we observe the value of error which is a function
of time, i.e., error (t) is given by 0.1, the temperature we are getting is not exactly 50°C.
It is 49.9°C: that is why it is showing an error (see Fig. 4.23).
216ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 4.24 Water heated to 50°C

Now after almost 40 to 45 minutes we observe that power becomes fixed at 16.3
percent and there is a little bit fluctuation temperature of water of the bucket around
50°C. The set point temperature is shown in green colour and PID controlled temperature
of water is shown in red colour. In this picture the error(t) is 0 as the temperature is
fixed at exactly 50°C. That is the beauty of PID temperature controller.
So we have achieved our desired goal to set the temperature of a water heater system
at a desired value which is taken as 50°C here through digital PID controller.
6. What is the difference between analog and digital PID?
7. Why do we need PID and what is Kp, Ki and Kd?
8. Draw the design of water heater to operate in PID mode.
9. Draw the block diagram of heating system PID for coper block and exlain its
working.
10. Write short not on FPAA?

ANSWERS (6-10)

6. GI is for easier to tune a digital PID controller, than an analog controller. Tuning
an analog controller requires multi-turn potentiometers and a lot of actual
“tweaking” of these pots. Occasionally, you need to change out capacitors in
›˜™˜›’˜—Š•ȱ —Ž›Š•ȱ Ž›’ŸŠ’ŸŽȱ ǻ Ǽȳ217

analog controller too. Analog systems sometimes require precision valued-


components which are expensive. In digital system, all you have to do is re-compile
some code with the new coefficients coated in it.
7. PID controllers can be used to regulate flow temperature, pressure level and
many other industrial process variables.
The proportional term (Kp) also known as gain, multipliers the current error value
by the proportional gain Kp. The output of the proportional term is defined as
pout = Kp * error (t)
The proportional gain defines the speed of change in the output: the larger the
gain the faster the output will be adjusted. The integral term (Ki) sums the error
value over time. This gives system the accumulated error over time, which needs
to be corrected. The integral term output is defined as Iout = KiȱȘȱŽ››˜›ȱǻȹǼŠ
The derivative terms adjust the output by the rate of change of the error. It is
defined as
Dout = Kd (d/dt) [error(t)]
8. Please refer Fig. no. 4.5.
9. Please refer Fig. 4.15 (for block diagram). Working:
(1) Accurate heating is completely bound on the PID control principles, here, first
the derived temperature is set and then power is given to the heater.
(2) As the temperature of the heater increases, the power required becomes less
and is maintained at a level when equilibrium temperature between heater
and surrounding is achieved.
(3) In order to achieve the above system, one needs to work on a complete
hardware which comprises high density electronics boards, adequate firmware
for display purposes and finally, the software that collects the required data
and plot graphs during working of the instrument.
(4) Data is transferred through Etnernet and it is connected with the ARM processor
as, shown in figure, which enables us to set the temperature value by our
system directly and also receives the data and plot it simultaneously (see Fig.
4.15).
10. A field-programmable analog array (FPAA) is an integrated device containing
analog blocks and interconnects between these blocks. The devices tend to be
application-driven than general purpose, as they may be current mode or voltage
mode devices. For voltage mode devices, each block usually contains an operational
amplifier in combination with programmable configuration of passive components.
RS-485, DATA LOGGING AND SUPERVISORY
5 CONTROL (DSC) VIA MODBUS USING LABVIEW

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋ Basics of RS485
Ȋ Basics of Modbus protocol
Ȋ Create a DSC project in LabVIEW
Ȋ Create screens using DSC
Ȋ Data logging using databases (RDBMS)
Ȋ How to create alarms
Ȋ How to define a sensor transfer function
Ȋ How to plot using TRACE
Ȋ Online and offline analysis
Ȋ Interface a practical MODBUS device

5.1 INTRODUCTION

Data is information, knowledge, and conceptions obtained by observation, investigation,


interpretation and visualization. Data are intangible and include numbers, words,
symbols, concepts, and oral verbalization. The word “data” has been upgraded into a
term “statistical data” which defined as “factual information such as measurements and
statistics, especially information organized for analysis or used to reason or make
decisions.”
The data and advanced technologies are ruling the present-day world. For example,
starting from the most simple day-to-day applications such as cell phones, televisions,
and World Wide Web (WWW) to more complex and advanced operations like to satellite
& spacecraft communications, nuclear reactor control systems, and automatic systems;
there are statistical data spread all over the broad spectrum. It would have been
impossible to acquire and control such a vast amount of statistical data without the
modern computers and advanced digital signal processing methods. A significant aspect
of concern is the efficient and controlled management of this huge amount of data.
While there is a vast and diverse range of data all around, some of low importance and
some highly critical, some secure and confidential and some unsecured, some raw and
some processed; it becomes imperative that there should be some supervisory control
system which would manage these widely varied data efficiently.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ219

The main objective of the supervisory control system would be to acquire data, extract
only the necessary blocks of information from it, process it and derive a conclusion from
it and storage system for future reference. These ideas lead to data logging and
Supervisory Control System (DSC). This chapter provides an introduction to the
LabVIEW data logging and Supervisory Control System (DSC) module.
The DSC module extends the LabVIEW graphical development environment with
additional functionality for the rapid development of distributed measurements, control,
and high-channel-count monitoring application. It also enhances the LabVIEW shared
variable using the shared variables to access and pass data among several VIs in a
LabVIEW project or access a network. A shared variable can represent a value or an I/O
point with the DSC module; you can log data automatically, and alarming, scaling, and
security to the shared variable and configure the shared variable programmatically.

5.2 RS-485 STANDARD

The RS-485 standard was developed by two trade associations: the Electronic Industries
Association (EIA) and the Telecommunications Industry Association (TIA). The EIA once
labeled all its standards with the prefix RS (Recommended Standard). Most of the
engineers use this designation (RS), but the EIA/TIA has officially replaced “RS” with
“EIA/TIA” to identify the basic origin of standards.
One of the most fundamental concepts of communication technology is the difference
between simplex and duplex. Let me explain what is simplex and duplex. Simplex is
the one-way communication, means data flows in one direction only. For example,
FM-radio station and FM-radio on your mobile phone, here data transmits from the
FM-radio station (transmitter) to FM-radio on your mobile phone, which acts as a
receiver. Since it is a one-way transmission and there is no way to confirm when or if
data received, it is not good to use in computer communication. However, simplex
communication is a very efficient way no distributing vast amount of information to a
large number of receivers.
A simplex device is not a transceiver. To overcome the limits of simplex, duplex
communications have come out, which will act as a transceiver. It can control and
confirm whether data is received/ transmitted because data flows in both the directions.
Further, the duplex communication is categorized into two kinds, based on transmission
and receiving data.
Full-duplex devices can transmit and receive the data at the same time. Mobile phones
and RS-232 are good examples of the full duplex communication system. In RS-232,
there are separate transmit and receive signal lines that allow the data flow in both
directions simultaneously. RS422 devices also operate on full duplex.
Half-duplex devices can also do both transmission and receive signal lines but not
simultaneously. Essentially, only one device can transmit at a time while all other half-
duplex devices receive. Devices operate as transceivers, but not simultaneous transmit
and receive. RS-485 operates in a half-duplex manner.
220ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Table 5.1 gives information and makes distinctions among the three protocols
(RS-232/485/422).

Table 5.1 Differences in three protocols (RS232/485/422)


RS-232 RS-422 RS-485
Cabling single ended single ended multi-drop
multi-drop
Number of Devices 1 transmit 1 receive 5 transmitters 10 32 transmitters 32
receivers receivers
Communication full duplex full duplex half half duplex
Mode duplex
Max. Distance 50 feet at 19.2 kbps 4000 feet at 100 kbps 4000 feet at 100 kbps
Max. Data Rate 19.2 kbps for 50 feet 10 Mbps for 50 feet 10 Mbps for 50 feet
Signaling Unbalanced Balanced Balanced
Mark (data 1) –5 V min. -15 V max. 2 V min. (B > A) 6 V 1.5 V min. (B > A) 5 V
max. (B > A) max. (B > A)
Space (data 0) 5 V min. 15 V max. 2 V min. (A > B) 6 V 1.5 V min. (A > B) 5 V
max. (A > B) max. (A > B)
Input Level Min. +/- 3 V 0.2 V difference 0.2 V difference
Output Current 500 mA (Note that 150 mA 250 mA
the driver ICs
normally used in PCs
are limited to 10 mA)

Note. You will see that one of the major differences between RS-232 and RS-422/RS-485
is the signaling mode. RS-232 is unbalanced while RS-422/RS-485 is balanced. An
unbalanced signal is represented by a single signal wire where a voltage level on that
one wire is used to transmit/receive binary 1 and 0: this can be considered a push signal
driver. On the other hand, a balanced signal is represented by a pair of wires where a
voltage difference is used to transmit/receive binary information: sort of a push-pull
signal driver. In short, unbalanced voltage level signal travels slower and shorter than
a balanced voltage difference signal.
RS-485 is primarily an upgrade to the RS-422 standard utilizing similar signal levels
but facilitating half-duplex, multipoint communication. The standard is less complex
than the RS-232 standard as it only specifies the electrical layer of the transmission
scheme. Hardware such as the connector is left to the user to define. The standard
specifies a balanced transmission line whose maximum line length is undefined but is
nominally 1.2 km of 24 AWG cable based on 6 dB signal attenuation. The maximum
data rate is also undefined but is specified by the relationship of signal rise time to bit
time, which is influenced by the line driver, the line length, and the line loading. In the
majority of applications, it is length of the line that is the limiting factor in data rate
due to signal dispersion.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ221

RS-485 Basics

When a network needs to transfer small blocks of information over long distances,
RS-485 is often the interface of choice. The network nodes can be PCs, microcontrollers,
or any devices capable of asynchronous serial communications. Compared to Ethernet
and other network interfaces, RS-485’s hardware and protocol requirements are simple
and economical.
The RS-485 standard is flexible enough to provide a choice of drivers, receivers, and
other components depending on the cable length, data rate, number of nodes, and the
need to conserve power. Several vendors offer RS-485 transceivers with various
combinations of features. Also, there are options for methods of terminating and biasing
the line and controlling the driver-enable inputs. In this chapter, I show you several
circuits for RS-485 networks.
There are brief suggestions relating to terminations and wiring, but there’s no
discussion of connector pinouts or software protocols (as there is for RS-232). An RS-485
network can have up to 32 unit loads, with one unit load equivalent to an input impedance
of 12k. By using high-impendence receivers, you can have as many as 256 nodes. An
RS-485 link can extend as far as 4000’ and can transfer data at up to 10 Mbps, but not
both at the same time. At 90 kbps, the maximum cable length is 4000’, at 1 Mbps it drops
to 400’, and at 10 Mbps it drops to 50’. For more nodes or long distances, you can use
repeaters that regenerate the signals and begin a new RS-485 line. Although the RS-485
standard says nothing about protocols, most RS-485 links us the familiar the asynchronous
protocols supported by the UARTs in PCs and other computers. A transmitted word
consists of a start bit followed by data bits, an optional parity bit, and a stop bit.
Two ways to add RS-485 to a PC are on an expansion card and by attaching an RS-485
converter to an existing port. Converters for RS-232 are widely available and Inside Out
Networks have developed a USB–to–RS-485 converter. Many network circuits also require
a port bit to control each transceiver’s driver-enable input. Ports designed for RS-232
communications can use the RTS output. If that’s not available, any spare output bit
will do. Most serial communications tools, including Visual Basic’s MSComm, support
RS-485 communications with RTS controlled in software. The COMM-DRV serial port
drivers from WCSC have automatic built-in RTS control. The main reason why RS-485
links can extend so far is their use of balanced, or differential, signals. Two wires (usually
a twisted pair) carry the signal voltage and its inverse. The receiver detects the difference
between the two. Because most noise that couples into the wires is common to both
wires, it cancels out. In contrast, interfaces like RS-232 use unbalanced, or single-ended,
signals. The receiver detects the voltage difference between a signal voltage and a
common ground. The ground wire tends to be noisy because it carries the return current
for all of the signals in the interface, along with whatever other noise has entered the
wire from other sources. And noise on the ground wire can cause the receiver to misread
transmitted logic levels. The datasheets for interface chips label the non-inverted RS-485
line as line A and the inverted line as line B. An RS-485 receiver must see a voltage
difference of just 200 mV between A and B. If A is at least 200 mV greater than B, the
receiver’s output is a logic high. If B is at least 200 mV greater than A, the output is a
222ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

logic low. For differences less than 200 mV, the output is undefined. At the driver, the
voltage difference must be at least 1.5 V, so the interface tolerates a fair amount of
non-common mode noise and attenuation.

General-Purpose Link

Figure 5.1

Figure 5.1 shows a general-purpose RS-485 network. Each node has a Texas Instruments
SN75176B transceiver that interfaces between RS-485 and TTL logic levels. The chip has
a two-wire RS-485 interface, a TTL driver input and receiver output, and TTL-enable
inputs for the driver and receiver. Similar chips include Linear Technology’s LTC485,
Maxim’s MAX485, and National Semiconductor’s DS3695. The circuit has two 120-W
terminating resistors connected in parallel, at or just beyond the final node at each end
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ223

of the link. One end of the link also has two 560-W biasing resistors. The terminations
reduce voltage reflections that can cause the receiver to misread logic levels. The receiver
sees reflected voltages as output switches, and the line settles from its initial current to
its final current. The termination eliminates reflections by making the initial and final
currents equal. The initial current is a function of the line’s characteristic impedance,
which is the input impedance of an infinite open line. The value varies with the wires’
diameters, the spacing between them, and the insulation type. For digital signals (which
consist mainly of frequencies greater than 100 kHz), the characteristic impedance is
mostly resistive; the inductive and capacitive components are small. A typical value for
24-AWG twisted pair is 120 W. The final current is a function of the line termination,
the receivers’ input impedance, and the line’s series impedance. In a typical RS-485 line
without a termination, the initial current is greater than the final current because the
characteristic impedance is less than the receivers’ combined input impedance. On a
line without a termination, the first reflection occurs when the initial current reaches
the receiver. The receiver’s input can absorb only a fraction of the current. The rest
reflects back to the driver. As the current reverses direction, its magnetic field collapses
and induces a voltage on the line. As a result, the receiver initially sees a greater voltage
than what was transmitted. When the reflected voltage reaches the driver, which has a
lower impedance than the line, the driver absorbs some of the reflection and bounces
the rest back to the receiver. This reflection is of opposite polarity to the first reflection
and causes the receiver to see a reduced voltage. The reflections bounce back and forth
like this for a few rounds before they die out and the line settles to its final current.
If the line terminates with a resistor equal to the line’s characteristic impedance, there
are no reflections. This general-purpose RS-485 network can have up to 32 nodes. Biasing
resistors ensure that there are no false start bits when no drivers are enabled. If the A
and B outputs balance exactly with equal, opposite currents, the two currents in the
ground wire cancel each other out and the wire carries no current at all. In real life,
components don’t balance perfectly; one driver will be a little stronger and one receiver
will have a slightly larger input impedance. Without a common ground, the circuit may
work, but the energy from the imbalance has to go somewhere and may dissipate as
electromagnetic radiation. The RS-485 specification recommends connecting a 100-W
resistor of at least 0.5 W in series between each node’s signal ground and the network’s
ground wire, as Fig. 5.1 shows. This way, if the ground potentials of two nodes vary,
the resistors limit the current in the ground wire.

Simplified Low-Power Link

Adding terminations increases a link’s power consumption. With two parallel 120-W
terminations and a differential output of 1.5 V, the current through the combined
terminations is 25 mA (disregarding the effects of biasing, attenuation, etc.). Without
terminations, the load is the parallel combination of the receivers’ input impedances
and varies with the number of receivers. The maximum 32-unit loads have a combined
parallel impedance of 375 W to ground or V+. For some shorter and slower links, you
can save power and components by not using terminating and biasing components. This
224ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

option is feasible if the line is electrically short, which means it behaves as a lumped,
rather than distributed, system. On a short line, the reflections die out long before the
receiver is ready to read the signal. A general guideline is that a line is short if the rise
time of its signals is greater than four times the signals’ oneway delay. The one-way
delay is the amount of time needed for a signal to travel from the driver to the receiver.
It’s a function of the line’s physical length and the speed of signals in the line. In copper
wire, a typical speed is two-thirds the speed of light, which works out to 8 in/ns. Cable
manufacturers often specify a value for products likely to be used in network wiring.
The rise time is specified in the driver’s datasheet. The slowest chip I’ve found is Maxim’s
MAX3080, with a minimum rise time of 667 ns. With cables of up to 100², the rise time
is more than four times the one-way delay (4 × 150 ns), so the line behaves as a short
line and doesn’t need terminating or biasing. Another advantage is that the internal
biasing pulls idle lines to nearly V+ and ground, so you get greater noise immunity.
The downside to using this chip is that the slow rise time means that it’s rated for use
only at 115,200 bps or less.

Short-Circuit Protection

The previous circuits ensured that the line was in a predictable state when idle or open.
The circuit of RS-485 also protects the network as much as possible if the signal lines
are shorted. Instead of a single pair of biasing resistors for the entire line, the circuit
has four biasing resistors at each node. The circuit uses Texas Instruments 75ALS180B
transceivers, which have full-duplex RS-485 inputs and outputs. The separate transmit
and receive pairs enable the receiver to have its own series biasing resistors. The two
RS-485 lines connect just beyond the biasing circuits.
If the signal lines short together, the 1.8-kW series resistors in combination with the
36 KW biasing resistors hold input. A more positive than B. Of course, the node can’t
communicate with the network if the line is open or shorted, but at least it remains in
an idle state (with no false start bits) until the problem is fixed. Another way to accomplish
the same thing is to use transceivers with built-in fail-safe protection for open and short
circuits. Chips that have this feature take varying approaches. Linear Technologies
LTC1482 has a carrier-detect function that brings the reciever’s output high when the
differential input voltage is too small to be a valid logic level. The chip has a carrier
detect output that indicates when the line is in an invalid state. National Semiconductor’s
DS36276 has internal circuits that bring the reciever’s output high if the line is shorted
or open. Maxim’s MAX3080-89 series provides short-circuit biasing by redefining the
threshold for logic 0. Instead of specifying all differential inputs of less than 200 mV as
undefined, these chips define a differential voltage of –50 mV or greater as a logic 0.
Voltages equal to or more negative than – 200 mV remain defined as logic 1s. The only
undefined region is from – 50 to – 200 m V. With these definitions, a shorted line (which
results in a differential input of 0 – V) is a logic 0, which results in a high output at the
receiver.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ225

Isolated Link

The entire RS-485 network has to share a ground, but the network can be galvanically
isolated from other circuits the network connects to as well as from earth ground. All
RS-485 components must be able to operate with common-mode voltages between –7
V and +12 V. Some components have higher ratings. The common mode voltage at the
receiver equals half the sum of the two signal voltages, referenced to the receiver’s signal
ground. The voltage varies with the differential signal voltages, the difference in ground
potentials between the driver and receiver, and noise on the line. Where the ground
connection is long, isolating the ground can ensure that the components don’t exceed
their ratings. Isolation also protects the circuits the network connects to if the network
circuits are damaged by high voltage. Complete isolation requires isolating the power
supplies and the network’s signals. The power supplies typically use transformer
isolation, whereas the signals use opto isolators.
A one-chip way to achieve isolation is to use Maxim’s MAX1480, which contains its
own transformer-isolated supply and optoisolated signal path.

Auto-Switching Link

One of the challenges in designing an RS-485 link is controlling the driver-enable lines.
Because all of the nodes share a data path, only one driver can be enabled at a time.
Before transmitting, a driver must be sure that the previous driver has been disabled.
Many RS-485 networks use a command/response protocol; one node sends commands
and the node being addressed returns a response. The UART in the node being addressed
detects the final stop bit in the middle of the bit width, or slightly sooner or later if the
sender’s clock doesn’t match exactly. A very fast node may be ready to send a reply
within a few microseconds after detecting the stop bit. To prevent the need for a delay
before responding, the sending node’s driver should be disabled as soon as possible
after the leading edge of its final stop bit. In most systems, the transmitting driver is
enabled on the leading edge of the start bit and remains enabled for the entire
transmission. It is disabled as soon as possible after the final stop bit. In the delays
between transmissions, biasing holds the line in an idle state. There are various ways
that the transmitting node can determine when a transmission has finished and it is
safe to disable the driver. The node may read back what it sent, or it may use a hardware
or software timer to estimate the time needed to transmit.

5.2.1 DTE & DCE

Let’s talk about DCE (data communications equipment) and DTE (data terminal
equipment) devices. The difference between DCE and DTE is largely in the Plug and
the direction of each pin (input or output). Your desktop PC is termed a DTE device
mostly but not all the time.
DCE devices use a 25-pin female connector while a DTE device uses a 25-pin male
connector. Also, complimentary signals lines like transmit and receive are “swapped”
226ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

between the two types. Thus, a straight-through cable can be used to connect a DCE
device to a DTE device. The connections are like as given in Table 2.2.

Table 5.2 25-pin connectors of DTE and DCE devices


DTE DCE
25 pin male pin-out 25 pin female pin-out
Pin 1 - Shield Ground Pin 1 - Shield Ground
Pin 2 - Transmitted Data (TD) output Pin 2 - Transmitted Data (TD) input
Pin 3 - Receive Data (RD) input Pin 3 - Receive Data (RD) output
Pin 4 - Request To Send (RTS) output Pin 4 - Request To Send (RTS) input
Pin 5 - Clear To Send (CTS) input Pin 5 - Clear To Send (CTS) output
Pin 6 - Data Set Ready (DSR) input Pin 6 - Data Set Ready (DSR) output
Pin 7 - Signal Ground Pin 7 - Signal Ground
Pin 8 - Carrier Detect (CD) input Pin 8 - Carrier Detect (CD) output
Pin 20 - Data Terminal Ready (DTR) output Pin 20 - Data Terminal Ready (DTR) input
Pin 22 - Ring Indicator (RI) input Pin 22 - Ring Indicator (RI) output

You can effectively convert DCE/DTE devices by using a NULL modem cable. The null
modem cable swaps the complimentary signals and allows a DCE device to act as a
DTE and vice versa.
The following chart depicts cabling of the DB9 connector found on an IBM-PC type
computer.

Table 5.3 DTE device 9-pin male connector


DTE
9-pin male pin-out
Pin 1 - Carrier Detect (CD) input
Pin 2 - Receive Data (RD) input
Pin 3 - Transmitted Data (TD) output
Pin 4 - Data Terminal Ready (DTR) output
Pin 5 - Signal Ground
Pin 6 - Data Set Ready (DSR) input
Pin 7 - Request To Send (RTS) output
Pin 8 - Clear To Send (CTS) input
Pin 9 - Ring Indicator (RI) input
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ227

5.3 BLOCK DIAGRAM OF DSC

Figure 5.2 Data logging and supervisory control.

From the sensors data will generate, to process the data we require hardware and
software (DSC on LabVIEW).
Hardware requirements: (1) Ethernet to RS-485 converter (EKI 1524) (2) Data
Acquisition ADAM analog & digital modules. Figure 5.3 describes the hardware
mechanism and its connections.

Figure 5.3 Hardware connections: An RS485 network

The analog inputs are connected to serial device server of model no EKI-1524. The
device has two modes of association – one is to protocol, and another one is to Ethernet.
What is the serial device server and how it will work is explained in the next topic
“Basics of Modbus.” In Fig. 5.3, (ADAM-4055/4117) are the Data acquisition modules,
is explained the Advantech Data Acquisition Module topic.
228ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

5.3.1 Basics of Modbus

Modbus is a serial communications protocol, developed by Modicon in 1979 for use


with its programmable logic controllers (PLC). Modbus has been mostly employed in
the industrial domain for many years, since, it is easy to deploy and maintain, openly
published and is royalty-free, and moves raw bits or words without placing many
restrictions on vendors and developing industrial applications are kept in mind.

5.3.2 Modbus Messages

Communication on Modbus network is, leaving a query from “master” to “slave.” The
slave which is observing the network for “queries” will pick out only the “queries”
addressed to it and will give response either by performing an action or by sending a
response to “master.” Only the “master” can initiate the “queries”.

Figure 5.4 Modbus messages to n number of slaves

In the Modbus protocol the master can address individual slaves, or, using a special
“broadcast” address, can initiate a broadcast message to all slaves (see Fig. 5.4).

5.3.3 Modbus Message Format

The Modbus protocol defines formats for the master’s query and response of the slave.
The query contains the device address, a function code defining the requested action,
any data to be sent, and an error-checking field.
The response contains fields confirming the action taken, any data to be returned,
and an error-checking field. If an error occurred during receipt of the message, or if the
slave is unable to perform the requested action, the slave will construct an error message
and send it as its response.
Each Modbus message has the same structure. Four basic elements are present in
each message. The sequence of these elements is the same for all messages, to make it
easy to parse the content of the Modbus message (see Table 5.4).
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ229

Table 5.4 Modbus message structure


Element Description
Slave address Address of the receiver
Function code Code defining type of performing an action
Data Data block, with additional information
Error check Numeric check value to test for communication errors

There can be more masters in a Modbus network. Addressing in the message header
is used to define which device should respond to a message.
Query: The example illustrates a request for a single 16-bit Modbus Register.
Slave Function Start Start Number Number Error- Error-
address code address address of points of points check check (Hi)
(Hi) (Lo) (Hi) (Lo) (Lo)

Slave Address: An 8-bit value representing the slave being addressed (1 to 247), 0 is
reserved for the broadcast address. The SPR and Integra products do not support the
broadcast address.
Function Code: An 8-bit value telling the addressed slave what action is to be
performed (3, 4, or 16 are valid for Integra).
Start Address (Hi): The top (most significant) eight bits of a 16-bit number specifying
the start address of the data being requested.
Start Address (Lo): The bottom (least significant) eight bits of a 16-bit number
specifying the start address of the data being requested.
Number of Points (Hi): The top (most significant) eight bits of a 16-bit number
specifying the number of registers being requested.
Number of Points (Lo): The bottom (least significant) eight bits of a 16-bit number
specifying the number of registers being requested.
Error Check (Lo): The bottom (least significant) eight bits of a 16-bit number
representing the error check value.
Error Check (Hi): The top (most significant) eight bits of a 16-bit number representing
the error check value.
Response: The example illustrates the normal response to a request for a single 16-bit
Register.
Slave Function Byte count Data Data Error Error Check
address code (Hi) (Lo) Check (Lo) (Hi)
Slave Address: An 8-bit value representing the address of slave, which has just
responded.
Function Code: An 8-bit value which, when a copy of the function code in the query,
indicates that the slave recognized the query and has responded (see also Exception
Response).
230ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Byte Count: An 8-bit value indicating the number of data bytes contained within this
response.
Data (Hi): The top (most significant) eight bits of a 16-bit number representing the
register(s) requested in the query.
Data (Lo): The bottom (least significant) eight bits of a 16-bit number representing
the register(s) requested in the query.
Error Check (Lo): The bottom (least significant) eight bits of a 16-bit number
representing the error check value.
Error Check (Hi): The top (most significant) eight bits of a 16-bit number representing
the error check value.

Exception Response

If an error is detected in the content of the query (excluding parity errors and Error
Check mismatch), the function code will be modified to indicate that the response is an
error response (called an exception response), and the data bytes will contain a code
that describes the error. The exception response is identified by the function code being
a copy of the query function code but with the most-significant bit set to logic ‘1’.
Slave Address: An 8-bit value representing the address of slave, which has just
responded.
Function Code: An 8-bit value which is the function code in the query OR’ed with
Hex (80), indicating the slave either does not recognize the query or could not carry out
the action requested.
Error Response Code: An 8-bit value indicating the nature of the exception detected.
Error Check (Lo): The bottom (least significant) eight bits of a 16-bit number
representing the error check value.
Error Check (Hi): The top (most significant) eight bits of a 16-bit number representing
the error check value.

5.3.4 Transmission Modes

The Modbus protocol transmission is in two different ways one is through the serial
network and the seconds through the Ethernet.
Slave address Function code Error response Error Check Error Check (Hi)
code (Lo)

Transmission via serial network (RS-232/485/422)

The Modbus protocol transmission via serial network has two standard transmission
modes; one is ASCII, and another is RTU (remote terminal unit). The mode of transmission
is usually chosen along with another serial port communication parameters (baud rate,
parity, data bits, stop bit, etc.) as part of the device configuration.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ231

ASCII transmission mode

In the ASCII Transmission Mode (American Standard Code for Information Interchange),
each character byte in a message is sent as 2 ASCII characters. This mode allows time
intervals of up to a second between characters during transmission without generating
errors.

Table 5.5 ASCII message format


Field Length Description
Start 1 Starts with (:) ASCII hex value is 0x3A
Address 2 Station address
Function 2 Indicates the function codes like to read coils/ inputs
Data N Data+ length will be filled depending on the message type
LRC 2 Checksum
END 2 Carriage return- line feed (CR/LF) pair (ASCII values of 0x0D & 0x0A)

RTU transmission mode

In RTU mode, messages start with a silent interval of at least 3.5 character times. This
is most easily implemented as a multiple of character times at the baud rate that is being
used on the network (shown as T1 – T2 – T3 – T4 in the figure below). The first field,
then transmitted is the device address.
The allowable characters transmitted for all fields are hexadecimal 0 – 9, A – F.
Networked devices monitor the network bus continuously, including during the ‘silent’
intervals. When the first field (the address field) is received, each device decodes it to
find out if it is the addressed device. Following the last transmitted character, a similar
interval of at least 3.5 character times marks the end of the message. A new message
can begin after this interval.
The entire message frame must be transmitted as a continuous stream. If a silent
interval of more than 3.5 character times occurs before completion of the frame, the
receiving device flashes the incomplete message and assumes that the next bit will be
the address field of a new message. Similarly, if a new message begins earlier than 3.5
character times following a previous message, the receiving device will consider it a
continuation of the previous message. This will set error, as the value in the final CRC
field will not be valid for the combined messages.

Table 5.6 Modbus RTU frame format


Field Length Description
Start 28 At least 3½ character times of silence (mark condition)
Address 8 Station address
Function 8 Indicates the function codes like to read coils/ inputs
232ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Data Nx8 Data + length will be filled depending on the message type
LRC 16 bits Checksum
END 28 At least 3½ Character times of silence between frames

Address field

Valid slave device addresses are in the range of 0 – 247 decimal. The individual slave
devices are assigned addresses in the range of 1 – 247. A master addresses a slave by
placing the slave address in the address field of the message. When the slave sends its
response, it places its own address in this address field of the response to let the master
know which slave is responding. Address 0 is used for the broadcast query.

Function field

Valid function field codes are in the range of 1 – 255 decimal. When a message is sent
from a master to a slave device, the function code field tells the slave what kind of
action to perform. When the slave responds to the master, it uses the function code field
to indicate either a normal (error-free) response or that some error occurred (called an
exception response). For a normal response, the slave simply echoes the original function
code. For an exception response, the slave returns a code that is equivalent to the original
function code with its most significant bit set to a logic 1. This tells the master what
kind of error has occurred, or the reason for the exception. Whether a particular function
code is applicable or not depends upon the slave device. Check specifications for each
slave device.

Data field

The data field of messages sent from a master to slave devices contains information
which the slave must use to take the action defined by the function code. The data field
may be of various lengths, or can be nonexistent (of zero length).

Error checking field

ASCII: When the ASCII mode is used for character framing the error checking field
contains two ASCII characters. The error checks characters are the result of a longitudinal
redundancy check (LRC) calculation that is performed on the message content, exclusive
of the beginning ‘colon’ and terminating CRLF characters.
RTU: When the RTU mode is used for character framing, the error checking field contains
a 16-bit value implemented as two 8-bit bytes. The error check value is the result of a
cyclical redundancy check calculation performed on the message contents.
LRC Checking: In the ASCII mode, messages include an error-checking field that is based
on a longitudinal redundancy check (LRC) method. The LRC field checks the contents
of the message, exclusive of the beginning ‘colon’ and ending CRLF pair. It is applied
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ233

regardless of any parity check method used for the individual characters of the message.
The LRC field is one byte, containing an 8-bit binary value. The LRC value is calculated
by the transmitting device, which appends the LRC to the message. The receiving device
calculates an LRC during receipt of the message and compares the calculated value
with the actual value it received in the LRC field. If the two values are not equal, error
results.
The LRC is calculated by adding together successive 8-bit bytes of the message,
discarding any carries, and then two’s complementing the result. It is performed on the
ASCII message field contents, excluding the ‘colon’ character that begins the message
and excluding the CRLF pair at the end of the message. For example, the query that
reads the resistor 30001 in slave device 1 is as follows: “:”, “0”, “1”, “0”, “4”, “0”, “0”,
“0”, “0”, “0”, “0”, “0”, “1”, “F”, “A”, CR/LF.
For the above query message, LRC is “F”, “A”.
CRC Checking: In the RTU mode, messages include an error-checking field that is
based on a CRC method. The CRC field checks the contents of the entire message. It is
applied regardless of any parity check method used for the individual characters of the
message.
The CRC field is two bytes, containing a 16-bit binary value. The CRC value is
calculated by the transmitting device, which appends the CRC to the message. The
receiving device recalculates a CRC during receipt of the message and compares the
calculated value with the actual value it received in the CRC field. If the two values are
not equal, error results.
The CRC is started by first preloading a 16-bit register to all 1’s. Then a process begins
by applying successive 8-bit bytes of the message to the current contents of the register.
Only the eight bits of data in each character are used to generate the CRC. Start and
stop bits, and the parity bit if one is used, do not apply to the CRC. During generation
of the CRC, each 8-bit character is exclusive OR’ed with the register contents. Then the
result is shifted in the direction of the least significant bit (LSB), with a zero filled in
the most significant bit (MSB) position. The LSB is extracted and examined. If the LSB
was a 1, the register is then exclusive OR’ed with a preset, fixed value. If the LSB was
a 0, no exclusive OR takes place.
This process is repeated until eight shifts have been performed. After the last (eighth)
shift, the next 8-bit byte is exclusive OR’ed with the register’s current value, and the
process repeats for eight more shifts as described above. The final contents of the register,
after all the bytes of the message have been applied, is the CRC value. For example, the
query that reads the resistor 30001 in slave device 1 is as follows: 0×01, 0×04, 0×00, 0×00,
0×00, 0×01, 0×31, 0×CA.
For the above query message, the calculated value of CRC is 0×CA31. The low-order
bit in CRC is appended first. Consequently the message order is 0×31, 0×CA.When the
CRC is appended to the message, the low-order byte of the field is appended first,
followed by the high-order byte.
234ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Transmission via Ethernet (TCP/IP)


Modbus/TCP is a communication protocol designed to allow industrial equipment such
as programmable logic controllers, computers, operator panels, motors, sensors, and
other types of physical input/output devices to communicate over a network.
Modbus/TCP was invented by Modicon/Group Schneider and is now one of the most
popular protocols embedded in the TCP/IP frames of Ethernet. Modbus/TCP embeds a
Modbus frame into a TCP frame in a simple manner. This is a connection-oriented
transaction, which means every query expects a response.
This query/response technique fits well with the master/slave nature of Modbus,
adding to the deterministic advantage that switched Ethernet offers industrial users.
The use of OPEN Modbus within the TCP frame provides a totally scalable solution
from ten nodes to ten thousand nodes without the risk of compromise that other multicast
techniques would give.
Modbus TCP/IP has become an industry de facto standard because of its openness,
simplicity, low-cost development, and minimum hardware required to support it. At
this moment, there are more than 200 Modbus TCP/IP devices available in the market.
It is used to exchange information between devices, monitor and program them. It is
also used to manage distributed I/Os, being the preferred protocol by the manufacturers
of this type of devices.
Modbus TCP/IP uses TCP/IP and Ethernet to carry the Modbus messaging structure.
Modbus/TCP requires a license but all specifications are public and open, so there is no
royalty paid for this license. Making use of TCP/IP also offers the use of embedded Web
pages to make life even more user-friendly! Simply ‘surf’ your plant intranet for the
information you need by using your web browser.

Performance from a Modbus TCP/IP system


The performance depends on the network and the hardware. If you are running Modbus
TCP/IP over the Internet, you won’t get better than typical Internet response times.
However, for communicating for debugging and maintenance purposes, this may be
perfectly adequate and save you from having to catch a plane or go to the site on a
Sunday morning! For a high-performance Intranet with high-speed Ethernet switches
to guarantee performance, the situation is completely different.

How can the existing Modbus devices communicate over Modbus TCP/IP?
Modbus TCP/IP is simply a Modbus protocol with a TCP wrapper. It is therefore
extremely simple for the existing Modbus devices to communicate over Modbus TCP/
IP. To do this a gateway device is required to convert the Modbus protocol to Modbus
TCP/IP.

Advantages of Modbus TCP/IP


Ȋ It is scalable in complexity. A device, which has only a simple purpose, need only
implement one or two message types to be compliant.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ235

Ȋ It is highly scalable in scope. A collection of devices using Modbus/TCP to


communicate can range up to 10,000 or more on a single switched Ethernet network.
Ȋ It is simple to administer and enhance. There is no need to use complex configuration
tools when adding a new station to a Modbus/TCP network.
Ȋ There is no vendor-proprietary equipment or software needed. Any computer
system or microprocessor with Internet style (TCP/IP) networking can use Modbus/
TCP.
Ȋ It is very high performance, limited typically by the ability of the computer
operating systems to communicate. Transaction rates of 1000 per second or more
are easy to achieve on a single station, and networks can be easily constructed to
achieve guaranteed response times in the millisecond range.
Ȋ It can be used to communicate with the large installed base of Modbus devices,
using conversion products, which require no configuration.

5.3.5 Function Codes

In this section, a various reading, writing and other I/O operations are tabulated.

Table 5.7 Function codes of register


Function Code Register Type
1 Read Coil
2 Read Discrete Input
3 Read Holding Registers
4 Read Input Registers
5 Write Single Coil
6 Write Single Holding Register
15 Write Multiple Coils
16 Write Multiple Holding Registers

For more details of function codes and quick reference, look at, Modbus protocol reference
guide from. System Co. Ltd.

5.4 MODBUS SERIAL DEVICE SERVER

In this section, we will discuss the Advantech Serial device server, EKI-1524 specifications.
Advantech’s Serial Device Servers, programmable device servers, and Modbus gateways
are easy to install and configure, support wired and wireless networking and provide
various operation modes to satisfy rigorous industrial automation needs. EKI-1000 Serial
Device Servers enable RS-232/422/485 serial devices to be dual-connected to Ethernet
switches for unrivaled reliability. The product line covers wired and wireless (WLAN,
GPRS, 3G) serial device server, Modbus gateway, and a programmable device server.
236ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

5.4.1 Introduction

Advantech's Serial Device Servers, programmable device servers, and Modbus gateways
are easy to install and configure, support wired and wireless networking and provide
various operation modes to satisfy rigorous industrial automation needs. EKI-1000 Serial
Device Servers enable RS232/422/485 serial devices to be dual-connected to Ethernet
switches for unrivaled reliability. Product line covers wired and wireless (WLAN, GPRS,
3G) serial device server, Modbus gateway, and programmable device server.
Two Ethernet ports allow the EKI-152X series to establish the two Ethernet connections
to two Ethernet domains or two Ethernet switches in the same domain. Through dual
Ethernet connections, the EKI-152X series greatly improves the device connectivity,
reliability, increase system stability, and simplify the redundant configuration.
By encapsulating serial data and transporting it over Ethernet, the EKI-152X series
allows virtual serial links over Ethernet and IP (TCP/IP, UDP/IP) networks. After
Advantech Serial Device Server Configuration Utility installation, standard serial
operation calls are transparently redirected to the serial device servers, guaranteeing
compatibility with legacy serial devices and enabling backward compatibility with the
existing software. EKI-152X series also supports serial tunneling, allowing two native
serial devices to communicate over a network without any hosts and programming. As
a result, you can extend to a limited distance, point-to-point, direct serial connections
within the plant, throughout the factory, the facility, the office building, or across the
global enterprise.
The EKI-152X series provides an impressive list of features and functions enabling
multiple industrial devices to be connected, controlled, configured, managed, and
updated over a network. With serial ports and two auto-sensing Ethernet ports, the
EKI-152X series can easily connect multiple serial devices to a network.
The EKI-152X series provides an impressive list of features and functions enabling
multiple industrial devices to be connected, controlled, configured, managed, and
updated over a network. With serial ports and two auto-sensing Ethernet ports, the
EKI-152X series can easily connect multiple serial devices to a network.

Types of supported devices

Ȋ Human Machine Interface (HMI)


Ȋ Programmable Controller (PLC)
Ȋ Flow meters
Ȋ Temperature / pressure monitoring equipment
Ȋ Gas leak detection device
Ȋ Scales
Ȋ Power monitoring equipment
Ȋ Data Acquisition Modules
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ237

EKI-152X series provides various TCP/UDP operations: COM port redirection (virtual
COM port), TCP server/ client and UDP mode. Serial devices can be connected by means
of multi-access modes.

5.4.2 Features

Ȋ Expand up 4096 serial ports for one Windows 2000/XP/Vista/7 host


Ȋ Provides dual 10/100 Mbps auto-sensing Ethernet ports: establish two separate
Ethernet connections
Ȋ Supports high transmission speed up to 921.6 kbps
Ȋ Supports various operation modes: COM port redirection (virtual COM port), TCP
server/client, UDP server/client mode
Ȋ Supports LED indicators: easy to diagnose
Ȋ Supports integrated configuration utility and port-mapping utility: easy to configure
and manage 4096 COM ports and self-diagnostic
Ȋ Supports multi-access features: allow maximum of five hosts to access one serial
port simultaneously
Ȋ Allows maximum 16 hosts to access TCP client and command response mode
Ȋ Easy to locate specific EKI-152X series serial device server
Ȋ Mounts on DIN rail, or panel
Ȋ Surge protection for RS422/485 line and power supply
Ȋ SNMP MIB-II for network management

5.4.3 Specifications
LAN

Ethernet: 10/100 Mbps auto sensing


Number of Ports: 2
Port Connector: RJ45
Protection: Built-in 1.5 KV magnetic isolation

Serial Interface

Interface: RS232/422/485, software selectable


Number of ports:
Ȋ EKI-1521: 1
Ȋ EKI-1522: 2
Ȋ EKI-1524: 4
Port connector: DB9 male
Baud rate: 50 bps to 921.6 kbps
238ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Parity: None, Even, Odd, Space, Mark


Data bits: 5, 6, 7, 8
Stop bits: 1, 1.5, 2
Flow control: RTS/CTS, XON/XOFF, DTR/DSR
Signals:
Ȋ RS232: TxD, RxD, CTS, RTS, DTR, DSR, DCD, RI, GND
Ȋ RS422: TxD+, TxD-, RxD+, RxD-, GND
Ȋ RS485: Data+, Data-, GND
Protection: 15 kV ESD for all signals, enhanced protection for RS422/485 lines

Software

Utility: Advantech Serial Device Server Configuration Utility


Driver support: Windows 2000/XP/Vista/7, Windows Server 2003/2008, Linux
Operation Mode:
COM port redirection (Virtual COM)
Ȋ TCP/UDP server (polling) mode
Ȋ TCP/UDP client (event handling) mode
Ȋ Pair connection mode
Configuration: Web interface, Windows utility, Telnet consoles
Protocol: ICMP, IP, TCP, UDP, BOOTP, DHCP, Auto IP, Telnet, SNMP, HTTP,
DNS, SMTP, ARP, NTP
Management: SNMP MIB-II

General

LED indicators:
Ȋ System: Power, System Status
Ȋ LAN: Speed, Link/Active
Ȋ Serial: Tx, Rx

Power

Power input: 12 to 48 VDC x 2


Power connector: Terminal block
Power Consumption:
Ȋ EKI-1521: 2W
Ȋ EKI-1522: 2.5W
Ȋ EKI-1524: 4W
Power Line Protection: 1 kV burst (EN61000-4-4), 0.5 kV surge (EN51000-45)
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ239

Environmental

Operation temperature: -10 to 60°C (14 to 140°F)


Storage temperature: -20 to 80°C (-4 to 176°F)
Operating humidity: 5 to 95% RH

Regulatory Approvals

ECM: CE, FCC Part 15 Subpart B (Class A)


Safety: UL (UL60950-1), Class I, Division 2

5.4.4 Dimensions

In this section, we will give the hardware dimensions of EKI-1524.

P1 P2 Slave

Tx Rx Tx Rx
140

1 2

Tx Rx Tx Rx

2 4

EKI-1524

95 mm
48.60 mm 103.96 mm

Figure 5.5 Front view of the EKI-1524 Figure 5.6 Side view of EKI-1524
240ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

84.30
66

8.32

37.70
24.30

42
30.50
48.60 mm 40 mm

Figure 5.7 Back view of EKI-1524 Table 5.8 Top view of EKI-1524

5.4.5 Connecting Hardware

Next, I will explain how to find a proper location for your EKI-152X series, and then
explain how to connect to the network, hook up the power cable, and connect to the
EKI-152X series serial port.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ241

Figure 5.9 Hardware connections

5.4.6 Network

EKI 1524 series has 2x RJ-45 that support connection to 10 Mbps Ethernet, or 100mbps
Fast Ethernet, and a half- or full-duplex operation. EKI 1524 can connect to other hubs
or switches through twisted pair straight through the cable (RS485) or crosswire cable
up to 100 m long.

5.4.7 Power Connection

The EKI 152X series supports dual 12 to 48 VDC power input and power-fail relay
output.

Figure 5.10 Terminal block front view for P-fail alarm contacts
242ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

You can connect an alarm indicator, buzzer or other silencing equipment through the
relay output. The relay opens if power input 1 or 2 fails (“open” means if you connect
relay output with an LED, the light would be off).

5.4.8 Serial Connection

The EKI-152X series provides one, two, or four ports DB9 (male) connectors. The
RS232/422/485 pin assignments as shown Fig. 5.11 & Table 5.8.
1 3 5
2 4

1 2 3 4 5

6 7 8 9

7 9
6 8
Figure 5.11 Block view of DB9 connector

Table 5.8 describes EKI 1524 series serial pin assignments to the different protocols [9].

Pin 1 2 3 4 5 6 7 8 9
RS232 DCD Rx Tx DTR GND DSR RTS CTS RI

RS422 Tx- - - Tx+ GND - Rx+ - Rx-


RS485 Data- - - Data+ GND - - - -

5.5 DATA ACQUISITION MODULE

5.5.1 Introduction

In this section, we describe how the data acquisition can be achieved by Advantech Data
Acquisition Modules (ADAM), especially ADAM-4055. Advantech’s data acquisition
modules and Ethernet I/O modules provide ideal industrial control and measurement
solutions for harsh environments and demanding applications. With wide operating
temperature ranges and multiple mounting methods, Advantech's ADAM series, such
as RS485-based and Ethernet I/O, can be implemented in diverse applications. The
Advantech ADAM-3000 series consists of cost-efficient, field configurable, isolated signal
conditioning modules that can be easily installed to protect instruments and signals
from the harmful effects of electrical interference.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ243

DI COM
DI 1
DI 0
D. GND

DO 6
DO 5
DO 4
DO 3

DO 1
DO 0
DO COM
DO 7

DO 2
ADAM-4055

ON/OFF
station
D0

D1 DO COM
DI COM

D. GND
DO 7
DO 6
DO 5
DO 4
DO 3
DO 2
DO 1
DO 0
DI 1
DI 0

Figure 5.12 ADAM-4055 16 channel digital I/O module

The ADAM-4055 offers an 8-channel isolated digital input and an 8-channel isolated
digital output for critical applications. The inputs accept 10~50 V voltage, and the outputs
can supply 5~40 VDC at the open collector. The ADAM-4055 is user-friendly with built
LED indicator for reading status. Figure 2.12 shows the picture of 16 channel I/O module
(see Fig. 5.12).

5.5.2 Application Wiring

In the following sections, how the connections like wiring, contact diagrams are given
(Figs. 5.13 to 5.16).
244ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

DI COM
DI 1
+5 ~ + 40 VDC
DI 0
– +
D. GND
DO 7
DO 6
DO 5
DO 4
DO 3
DO 2 Load
DO 1
DO 0
DO COM

Figure 5.13 ADAM-4055 digital output wiring

DI COM
DI 1
DI 0
D. GND
DO 7
DO 6
DO 5
DO 4
DO 3
DO 2
DO 1
DO 0
DO COM

Figure 5.14 ADAM-4055 input dry contact wiring diagram


ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ245

External Internal
DICOM

+15V

DGND
Jumper setting

Switch

DIO

Figure 5.15 ADAM-4055 digital input dry contact diagram (internal)

Logic level 1: 10 ~ 15V


Logic level 0: 3V max
External Internal
DI COM DICOM
DI 1
– + +15V
DI 0
+ –
D. GND Jumper setting
DO 7
DO 6
DGND
DO 5
DO 4
DO 3
DO 2 – DC DC –
+ +
DO 1
DO 0
DO COM DIO

Figure 5.16 ADAM-4055 digital input wet contact diagram (external and internal)
246ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

5.6 LABVIEW FOR MODBUS COMMUNICATION


5.6.1 Introduction

LabVIEW is a highly productive development environment for creating custom


applications that interact with the real-world data or signals in fields such as science
and engineering. The use of a tool like LabVIEW leads to the ultimate results of high-
quality projects can be completed in less time with a few people.
So productivity is the key benefit, but that is a broad and general statement. To
understand what this means, consider the reasons that have attracted engineers and
scientists to the product since 1986. At the end of the day, engineers and scientists have
a job to do – they have to get something done, they have to show the results of what
they did, and they need tools that help them do that. Across different industries, the
tools and components they need to succeed vary widely, and it can be a daunting
challenge to find and use all these disparate items together. LabVIEW is unique because
it makes this wide variety of tools available in a single environment, ensuring that the
compatibility is as simple as drawing wires between functions.

5.6.2 What Makes up LabVIEW?

LabVIEW itself is a software development environment that contains numerous


components, several of which are required for any type of test, measurement, or control
application.
To quote one of our software developers, “We write low-level code, so you don’t have
to.” Our global team of developers continually works on the six areas (see Fig. 5.17),
the LabVIEW user, up to focus on the bigger problems and tasks you are trying to solve.

Analysis and
Hardware
G Technical Code
Support
Programming Libraries

UI Components
Technology Models of
and
Abstraction Computation
Reporting Tools

Figure 5.17 LabVIEW contains several valuable components


ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ247

5.6.3 G Programming Language

Ȋ Intuitive, flowchart-like data flow programming model


Ȋ Shorter learning curve than traditional text-based programming
Ȋ Naturally represents data-driven applications with timing and parallelism
The G programming language is central to LabVIEW; so much so that it is often called
“LabVIEW programming.” Using it, you can quickly tie together data acquisition,
analysis, and logical operations and understand how data is being modified. From a
technical standpoint, G is a graphical data flow language in which nodes (operations
or functions) operate on the data as soon as it becomes available, rather than in the
sequential line-by-line manner that most programming languages employ. You lay out
the “flow” of data through the application graphically with wires connecting the output
of one node to the input of another (see Fig. 5.18).

Sine with
noise graph

2
Amplitude 1
control Simulate signal 0 0.0 1.0
Express VI Power spectrum
6 graph
4
Amplitude
2
DEL ∏ Noise amplitude 2
1
Desired 5 Sine with noise
0
SNR 0.0 1.0
Window
Power
Hanging

dB On (F)

TF

Averaging parameters

Averaging mode
No averaging
Weighting mode
Exponetial

Number of averages
10

Figure 5.18 This block diagram shows a self-documenting G code


248ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The practical benefit of the graphical approach is that it puts more focus on data and
the operations been performed on that data, and abstracts much of the administrative
complexity of computer programming such as memory allocation and language syntax.
New programmers typically report shorter learning curves with G than with other
programming languages because they can relate G code to flowcharts and other familiar
visual representations of processes. Seasoned programmers can also take advantage of
the productivity gains by working at a higher level of abstraction while still employing
advanced programming practices such as object-oriented design, encapsulation, and
code profiling.
LabVIEW contains a powerful optimizing compiler that examines your block diagram
and directly generates efficient machine code, avoiding the performance penalty
associated with interpreting or cross-compiled languages. The compiler can also identify
segments of code with no data dependencies (that is, no wires connecting them) and
automatically split your application into multiple threads that can run in parallel on
multi-core processors, yielding significantly faster analysis and more responsive control
compared to a single threaded, sequential application.
With the debugging tools in LabVIEW, you can slow down execution and see the
data flow through your diagram, or you can use common tools such as breakpoints and
data probes to step through your program node-by-node. The combination of working
with higher-level building blocks and improved visibility into your application’s
execution results in far less time spent tracking down bugs in your code.
Hardware support
Ȋ Support for thousands of hardware devices, including:
» Scientific instruments
» Data acquisition devices
» Sensors
» Cameras
» Motors and actuators
Ȋ Familiar programming model for all hardware devices
Ȋ Portable code that supports several deployment targets

5.6.4 Benefits of LabVIEW

As complex as you need it to be: One of the reasons LabVIEW makes you successful
is its ability to scale to meet the needs of a given application. Picking the right software
has been all too often a balancing act between ease of use and learning curve on one
side and power and flexibility on the other. Simple, fixed-function applications are easy
to use and can be configured off the shelf, but they rarely meet all of the requirements
for real-world usage. Full-fledged programming, on the other hand, is powerful and
flexible but comes at the cost of increased training and development time. LabVIEW
addresses this problem by providing several ways to accomplish similar tasks, so you
can make the trade-off between simplicity and customization yourself on a task-by-task
basis.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ249

5.7 USING MODBUS I/O SERVERS (DSC OR REAL-TIME MODULE)

Modbus is an application-level messaging protocol that provides client-server


communication between devices connected to different types of buses or networks. You
can create a Modbus, or Modbus Slave I/O server to read data from or write data to
Modbus devices. For example, you can create a Modbus Slave I/O server on a National
Instruments real-time controller and use this controller as a Modbus slave device. You
also can create a Modbus I/O server on a host computer and use this server as a Modbus
master device to communicate with a Modbus slave device. [12]
Modbus I/O servers use six-digit addresses. You can convert a five-digit address to
a six-digit address by adding a zero between the first and the second digits of the five-
digit address. For example, you can convert address 45001 to 405001.

Notations of Modbus Master and Slave I/O server data items:


Ȋ A denotes an array.
Ȋ D denotes a 32-bit unsigned integer.
Ȋ F denotes a 32-bit floating point number.
Ȋ L denotes the length of an array. The Maximum Data Points per Command values
that you specify in the Advanced Attribute Dialogue Box determine the maximum
length of the array. If the array elements are 32-bit integers or floating-point
numbers, the maximum length of the array is half the value you specify for the
corresponding Maximum Data Points per Command Value.
Ȋ S denotes a 16-bit signed integer.
Ȋ SD denotes a 32-bit signed integer.

Table 5.9 List of some data items that support the Modbus master and slave
Data Modbus Modbus Slave
Data Item Description Example
Type Read Write Read Write
000001 Boolean Yes Yes Yes Yes Accesses single-bit 000001 =
– 065535 value coils. {000001}
100001 Boolean Yes No Yes Yes Accesses single-bit 100002 =
– 165535 value discrete inputs. {100002}
300001.1 Boolean Yes No Yes Yes Accesses individual 300001.1 =
– 365535.16 value bits of input registers {the first bit
and interprets them of 300001}
as logical TRUE or
FALSE values. The
least significant bit is
1. The most
significant bit is 16.
300001 16-bit Yes No Yes Yes Accesses 16-bit input 300001 =
– 365535 unsigned registers as unsigned {300001}
integer integers ranging from
0 to 65,535.
250ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Data Modbus Modbus Slave


Data Item Description Example
Type Read Write Read Write
400001.1 Boolean Yes No Yes Yes Accesses individual 400002.16 =
– 465535.16 value bits of holding {the 16th bit
registers and of 400002}
interprets them as
logical TRUE or
FALSE values. The
least significant bit is
1. The most
significant bit is 16.
400001 16-bit Yes Yes Yes Yes Accesses 16-bit 400002 =
– 465535 unsigned holding registers as {400002}
integer unsigned integers
ranging from 0 to
65,535.
A000001L1 Array of Yes Yes Yes Yes Accesses arrays of A000001L2 =
– A065535L1 Boolean single-bit coils. {000001,
values 000002}
A100001L1 Array of Yes No Yes Yes Accesses arrays of A100005L3 =
– A165535L1 Boolean single-bit discrete {100005
values inputs. – 100007}
A300001L1 Array of Yes No Yes Yes Accesses arrays of A300001L2 =
– A365535L1 16-bit 16-bit input registers {300001,
unsigned as arrays of unsigned 300002}
integers integers.
A400001L1 Array of Yes Yes Yes Yes Accesses arrays of A400005L3 =
– A465535L1 16-bit 16-bit holding {400005
unsigned registers as arrays of – 400007}
integers unsigned integers.
AD300001L1 Array of Yes No Yes Yes Accesses arrays of AD300001L1
– AD365534L1 32-bit 32-bit unsigned ={300001,
unsigned integers. Each 32-bit 300002}
integers unsigned integer in
the array is
composed of two
adjacent 16-bit input
registers.
AD400001L1 Array of Yes Yes Yes Yes Accesses arrays of AD400002L3
– AD465534L1 32-bit 32-bit unsigned =
unsigned integers. Each 32-bit {400002
integers unsigned integer in – 400007}
the array is
composed of two
adjacent 16-bit
holding registers.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ251

5.7.1 Building a DSC Module

1. Creating a new project library


This section will help you on how to create a new LabVIEW project and project library.
The project allows you to manage shared variables, project libraries, and VIs in one
window. LabVIEW project libraries are collections of VIs, type definitions, shared
variables, palette menu files, and other files, including other project libraries.
To create a LabVIEW project follow the steps:
Step 1: Open LabVIEW, and click on Launch LabVIEW then Getting Started window
will open.

Step 2: Click on Create Project, will open the Create Project window; select Blank Project
and click on Finish; the Project Explorer window will appear as shown below.
252ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step 3: Right click My Computer in the Project Explorer window and select New” Library
from the shortcut menu.
Step 4. Select File” Save All. The Name the Project dialog box appears.
Step 5: Enter the name of the project in the File name text box.
Step 6: Click the OK button. The Name the Library dialog box appears.
Step 7: Enter Name of Project + IO Server in the File name text box.
Step 8: Click the OK button
You now have a project containing a project library. In the following exercise, you
will use the project library in the project to create a periodic I/O server.
2. Creating an I/O server
Follow the steps below:
Step 1: Right click on My Computer in the Project Explorer window and select New >>
I/O server from the shortcut menu.
Step 2: Select Modbus and click Continue, will get configure Modbus I/O Server; select
Serial Port and check all the parameters of the serial device and then click OK.

Step 3: Right click My Computer, in ProjectExplores window and select New >> VI
(Virtual Instruments), two windows will appear, one is VI window another is Block
Diagram window, which contains the graphical program.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ253
254ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step 4: Now we have to create shared variable. Right click My Computer, in Project
Explores window and select New >> Variable.
Step 5: Give the name of the variable and set the alarm and scaling all the fields, type
of the variable and click OK.

Step 6: Drag the variable drop on the VI window; it will appear in the Block Diagram
window also. Make it an indicator by selecting the variable and right click select change
to the indicator.

PROJECT: CREATE A LABVIEW PROJECT FOR THE REAL-TIME DSC


MODULE

1. Create a program for the real-time DSC module


In this section, we give an example of a real-time DSC module using the random
number generator.
Follow the steps for random number generation using the “for loop”, in the steps
given below.
1. Right click on the Block Diagram window functions window will open, select
Programming >> Structures >> for loop.
2. In order to Select Programming >> Numeric >> Random number.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ255

random1

DBL

X
100

1000
stop

STOP
i
TF

To log the data in the DSC module, we will have to select DSC module >> Trend
control >> Historical trend.
256ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Steps to be followed to log data


DSC for data logging - log a random variable data
Create a project called “ADAM4055” in LabVIEW 11.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ257

Create a new VI called “random number vi”.

Create a program to count up and down between 0 and 100.


258ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Now create a shared variable by right clicking on the wire which has to be converted
to a shared variable!

Give a name to the shared variable from Project Explorer window as given “my 0 to
100 var”. Now create a Historical Trend having XY Graph from the front panel as
shown below.

After all this setting is done, simply run the program. Open the historical data viewer
from tools >> DSC module >> view data historical as shown below. Open the file
‘Historical Data’ from My System. Then click on Add/Remove and add the shared
variable file and observe the graph.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ259

To observe New A&E view just refresh and select the file.

2. Historical data
In this section, we give how the historical data will help in different actions. Historical
data provides access to all your databases and your logged data, or data views.
260ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

What do you want to do?

View data: To view and manage your databases and data views, expand Historical Data
in the configuration tree. Your databases appear in the Data bases view when you select
Citadel 5 Universe. Your data views appear beneath Citadel 5 Universe.
Create a database: To create a new empty database, right-click Historical Data and
select Create New. Select Citadel 5 Database from the Create New wizard and click
Next. Follow the instructions to create a new database, then click Finish. Your new
database appears in the Databases view when you select Citadel 5 Universe under the
Historical Data category.
Convert a Citadel 4 database to Citadel 5 format: To convert a Citadel 4 version database
to Citadel 5 version format, right click Historical Data and select Create New. Select
Convert Citadel 4Database to Citadel 5 from the Create New wizard and click Next.
Follow the instructions to select the database you want to convert and the location of
the converted database, then click Finish.
Delete a database: To delete a database, right click the database in the Databases view
and select Detach/Delete. Select Delete in the Detach/Delete Database Dialog box and
click OK.
Create a new database: To create a new data view, right click Citadel 5 Universe and select
New” Alarms/Events View or New” Trace View. Your new data view appears in the
configuration tree under Citadel 5 Universe.
View Citadel 4 database: For more information, refer to the Historical Data Viewer Help,
which you can access from the Help ”Help Topics” Historical Data Viewer menu.
3. Trace Historical data
The main difference between the historical trend and real-time trend is that the data
can’t be saved in the historical database in the case of the real-time trend. To trace the
data Select Tools Menu >> DSC Module >> View Historical Data.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ261

To view the historical data plot goto Historical Data field >> Citadel 5 Universe, by
selecting it, we can see a Hierarchy in the side view as shown in the window.
Select Network >> siva >> siva >> Test DSC >> random (which is the shared variable
name what I had given). Then go to View Data menu.
To trace the current data, we have to run the VI in the background and then we
will get a good plot as shown below.

To view the data log, select Export to text menu and give the path of the database
in the output file text field to save it.
262ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

If we look at the trace .dat file that contains the data on which date and time it stored.
It automatically saves in .dat format, to open the file from Excel, first go to Data menu
>> From Text. It is a three-step process.

Step 1
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ263

Step 2

Step 3 Finally, after clicking the finish, Import Data window will open to importing the
data into the existing spreadsheet or new spreadsheet.
264ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The data contains the saved data on which date and time.

The highlighted content is the data. Thus, the DSC Module is a powerful tool to
logging the data.
4. Configure the Utilities
In this project, the data is from random number generator; we can replace it by Data
Acquisition Modules either analog or digital using Serial Device Server EKI-152X series.
The data transmission through this device can be through either serially connects to the
DAM via RS-485 protocol or through Ethernet. It has been explained in detail in section
1.4. For this, we need to configure the following two utilities before running in LabVIEW.
Ȋ Serial Device Server Configuration Utility
Ȋ ADAMApax.NET Utility
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ265

Before configuring these utilities, firstly we have to check whether our PC has the
COM ports or not, means the ports are not available for all OS. It is mainly compatible
with Windows XP and upto Windows 2007 only.
Check the COM port availability in PC. Right-click My Computer on the desktop;
select Properties. The following window will appear.

Select the Device Manager, there you can find an option Ports and Devices, will having
the ports, or you can verify whether your PC has the ports or not from Control Panel
>> Hardware and Sounds >> Devices and Printers >> Device Manager

5.8 CONFIGURE THE SERIAL DEVICE SERVER UTILITY

EKI-152X series serial device servers provide an easy-to-use utility to configure your
serial device server through an Ethernet connection. For secure administration, it can
also restrict the access rights for configuration to only one host PC. With this secure
function enabled, other PCs will not have permission for configuration. After the
installation program on the Advantech IEDG Series Driver Utility CD-ROM is over,the
serial device servers will be ready for use and configure.
Advantech Serial Device Server Configuration Utility is an excellent device server
management tool. You can connect and configure the local and remote Advantech serial
device servers easily. Moreover, Virtual COM port will be enabled in the same utility.
Using this utility, you can:
266ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋ Configure the network settings (you can set the IP address, Gateway address, and
Subnet mask)
Ȋ View and set the serial port parameters (configure operating mode, baud rate,
serial port settings and operating mode settings)
Ȋ Perform diagnostic tests (virtual COM port testing, port status list)
Ȋ Perform administrative functions (export and import the serial device server setting,
manage access IP, a descriptive name, upgrade firmware)
Ȋ Configure COM port redirect or (virtual COM port)

5.8.1 Discovering Serial Device Servers

(i) Auto Searching: Advantech Serial Device Server Configuration Utility will
automatically search all the EKI-1000, ADAM-4570 and EDG-4500 series device
servers on the network and show them on the Serial Device Server List Area of
the utility. The utility provides an auto-search function to show your device(s)
by simply executing the configuration utility program from the Start Menu.

(ii) Auto mapping: We can map the com ports either manually or virtually. To Auto
map Right click on the serial device name and select Auto map option.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ267

The serial ports that can be assigned to virtual COM will be shown in this window.
Select the serial ports you wish to map or click the < Select All > button and press
< Map Selected Ports > button. The selected serial ports will be mapped to virtual COM
ports in sequential order.
268ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The COM ports in the “Virtual COM Ports” listing are now available for use by
Windows application.

Right click the serial device name on the sub-tree of Device Server List area and select
the “Manual Mapping” function.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ269

ADAM series, EDG series, and EKI wireless series have only one IP address. Select
the serial port on the device server and the host COM that you want to set. Press < Map
it > to establish the virtual COM port on the host.

5.8.2 Configure the ADAMApax.NET utility

While running the utility itself it can detect the device but externally we have to select
the Tools menu >> Search for Device then the following window will appear.

While running this program, we have to keep the running Serial Device Server utility
as background.
5. How to Change the Physical address of ADAM module,e.g., ADAM-4055
We have to connect the Adam-4055 module via Adam-4520. Adam-4520 is RS232 to
RS485 converter. So from PC, create virtual com port (using moxa) and then connect to
4117 (whose address is to be changed) via 4520.
Go to Adam utility and select the port. Search port address. Double click on the port
address to change the address.
270ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

5.9 AIN, AOUT, DIN, DOUT USING MODBUS


5.9.1 Modbus and Data Logging & Supervisory Control

Modbus is a serial communications protocol. Modbus is an application-layer protocol


based on a client/server or request/reply architecture. It was published by Modicon.The
Modbus protocol follows a client/server (master/slave) architecture where a client will
request data from the server. The client can also ask the server to perform some action.
During communications on a Modbus network, the protocol determines how each
controller will know its device address, recognize a message addressed to it, determine
the kind of action to be taken, and extract any data or other information contained in
the message. If a reply is required, the controller will construct the reply message and
send it using the Modbus protocol.
The messages exchanged between the client and the server is called frames. There
are two types of Modbus frames: Protocol Data Unit (PDU) and Application Data Unit
(ADU). The PDU frames contain a function code followed by data. The function code
represents the action to perform, and the data represents the information to be used for
this action. ADU frames add a little more complexity with an additional address part.
ADU frames also provide some error checking. Both the ADU and PDU frames follow
Big-Endian encoding.
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ271

Connection of Modbus

ADAM-4055
272ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Specifications
Ȋ Number of Input Channel: 8 (4-channel/group)
Ȋ Optical Isolation: 2500 VDC
Ȋ Op to-Isolator Response Time: 25 μs
Ȋ Over-voltage Protect: 70VDC
Ȋ ESD (Electro Static Discharge): 2000 VDC
Ȋ Input Voltage:
» Dry Contact Logic level 0: Close to GND
» Logic level 1: Open
» Wet Contact Logic level 1: 10 ~ 50 V
» Logic level 0: 3 V
» Dry Contact & Wet contact Selectable
Ȋ Number of Output Channels: 8 (8-channel/group)
Ȋ Optical Isolation: 2500 VDC
Ȋ Op to-Isolator Response Time: 25 μs
Ȋ Supply Voltage: Open Collector 5 ~ 40 VDC
Ȋ Sink Current: 200 mA max/channel
Ȋ LED Indicator: On: Active Off: Non-active
Ȋ Power Consumption: 1 W
Ȋ I/O Connector Type: 13-pin plug-terminal * 2

Table: Modbus address of ADAM-4055


ADDR 0X CHANNEL ITEM ATTRIBUTE
00001 0 DI input signal R
00002 1 DI input signal R
00003 2 DI input signal R
00004 3 DI input signal R
00005 4 DI input signal R
00006 5 DI input signal R
00007 6 DI input signal R
00008 7 DI input signal R
ADDR 0X CHANNEL ITEM ATTRIBUTE
000017 0 DO input signal R/W
000018 1 DO input signal R/W
000019 2 DO input signal R/W
000020 3 DO input signal R/W
000021 4 DO input signal R/W
000022 5 DO input signal R/W
000023 6 DO input signal R/W
000024 7 DO input signal R/W
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ273

ADAM-4024
Specifications
Ȋ 12-bit resolution
Ȋ Software configurable for mA or V output in individual channels
Ȋ 4 digital inputs for latch output
Ȋ 3000 VDC D/A to Logic isolation
Ȋ Programmable output slope: 0.125–128.0 mA/sec. 0.0625 - 64 V/sec

Table: Modbus address of ADAM-4024

ADDR 0X CHANNEL ITEM ATTRIBUTE


00001 0 Emergency DI Input Flag R
00002 1 Emergency DI Input Flag R
00003 2 Emergency DI Input Flag R
00004 3 Emergency DI Input Flag R

ADAM-4117
274ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Specifications

The ADAM-4117 is a 16-bit, 8-channel analog input module that provides programmable
input ranges for all channels.
Ȋ 8 differential and independent configuration channels
Ȋ Broader operating temperature range
Ȋ Higher noise immunity: 1 kV surge protection on power inputs, 3 kV EFT, and 8
kV ESD protection
Ȋ Broader power input range: 10 ~ 48VDC
Ȋ LED display allows to monitor the status address settings
Ȋ Supports 200 VDC high common mode voltage
Ȋ Supports unipolar and bipolar input
Ȋ Supports ± 15 V input range
Ȋ Supports filter auto-turning or filter-out 50/60 Hz

Table: Modbus address of ADAM-4117

ADDR 4X CHANNEL ITEM ATTRIBUTE


00001 0 Burn-out R
00002 1 Burn-out R
00003 2 Burn-out R
00004 3 Burn-out R
00005 5 Burn-out R
00006 6 Burn-out R
00007 7 Burn-out R
0008 8 Burn-out R

ADAM-4520
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ275

Specifications

ADAM-4520 is an isolated converter for systems originally equipped with RS-232. It


transparently converts RS-232 signals into isolated RS-422 or RS-485 signals. You don’t
need to change your PC's hardware or your software.
Ȋ Automatic RS-485 data flow control
Ȋ 3000 VDC isolation protection
Ȋ Surge protection RS-485 data line
Ȋ Transmission speed up to 115.2 Kbps
Ȋ Networking up to 1200 meters (4000 feet)
Ȋ Reserved space for termination resistors
Ȋ Power and data flow indicator for troubleshooting
Ȋ Power requirement: + 10 to + 30 VDC
Complete Hardware Design

Adam address setting using ADAM.NET utility is shown below.


First, check the address of Adam devices. We have:
Ȋ address of ADAM-4055 is 3
Ȋ address of ADAM-4117 is 1
Ȋ address of ADAM-4024 is 2
276ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

ADAM UTILITY

Ȋ Connect the devices as shown in the figure.


Ȋ Connect all the pins of ADAM-4117 as shown. We have given 24 V supply to all
the ADAM devices.
Ȋ Data + and Data- pins of all the Adam devices are connected.
Ȋ ADAM-4025, which converts RS232 signals into RS485 signals. The RS232 signals
of all the ADAM devices are connected parallel.
Ȋ RS485 is connected to EKI-1526 which is a serial device server.
Ȋ Ethernet module is connected to DSC in PC.

LABVIEW DESIGN: FINAL DSC LOOK OF SAMPLE CONTROL VIA RS-485


ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ277

5.10 MODBUS INTERFACING OF HONEYWELL PID CONTROLLER

The Honeywell DC1000 family is microprocessor based controllers that combine a high
degree of functionality and reliability. With a typical accuracy of ±0.5% of span, the
DC1000 is an ideal controller for regulating temperature and other process variables in
a variety of applications. In our application, we used the Honeywell digital PID controller
model DC1040 which is available in ¼ DIN package. The front panel display of the
controller is shown in the following picture.

We interfaced this controller through Modbus onNI LabVIEW 2017 SPl(32-bit). This
particular controller supports RS-485 protocol, so we used two communication converters
to connect the unit to the PC; one ADAM RS-485 to RS-232 isolated converter and one
MOXA RS-232 to USB converter. Only one RS-485 to RS-232 converter will suffice, if
the PC supports RS-232 port.
Up to 32 controller units can be connected to a single host computer in a daisy chained
manner as shown in the following picture.

As soon as we connect the USB cable, the PC detects the corresponding COM Port
(here COM2) as “MOXA USB Serial Port” and the same COM port is used in the software
program for establishing the communication.
278ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

This controller has a number of internal settings which can be set as per the requirement
of the application. Following are the main settings which we have set in our case:
PSL (Protocol Selection): RTU ( Modbus RTU protocol)
Bits (Communication Bits): 0_81(Odd parity, Data bits = 8, Stop Bit = 1)
ID.NO (ID number of the controller): 1
BAUD (Communication baud rate): 9600 bps

5.10.1 Software Design

First of all, the Modbus library, that supports the LabVIEW version, is installed on the
PC. The MODBUS library is a free, downloadable set of Virtual Instruments (VIs) that
provide Modbus communication from any standard Ethernet or serial port. Following
are the steps to install Modbus library:
Step 1: Go to the official site of National Instruments.
Step 2: Download Nl Modbus Library (version: ni_lib_modbus_library-1.2.1.42)
Step 3: Install the file through VIPM (VI Package Manager)
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ279

Honeywell PID controller has a dedicated set of registers, having specific addresses,
associated with various control parameters. We can use the respective register address
to set or read the value of the corresponding parameter. We made a software program
to control parameters such as PV (Process Variable), SP {Set Point), P {Proportional gain),
I (Integral gain), D (Derivative gain), AT ( Auto Tuning control) and OUTL {Output
limit). Following are the respective register addresses of different parameters:
Parameter Register Address
PV 138
SP 000
P 057
I 058
D 059
AT 002
OUTL 001

5.10.2 lnbuilt Function of Modbus Library for Reading Data

Step 1: Right click on VI editor and select Create master instance.vi. It creates a serial
or TCP Modbus master instance. You can use the Modbus master instance to perform
read and write operations on Modbus slaves.
Ȋ serial type specifies the type of data transmission through serial ports.
Ȋ unit ID specifies the identification of the Modbus slave with which you want to
communicate.
Ȋ VISA resource name specifies the resource you want to open.
Ȋ baud rate specifies the baud rate of the Modbus slave with which you want to
communicate.

Ȋ error in describes error conditions that occur before this node runs.
Ȋ parity specifies the parity of the Modbus slave with which you want to communicate.
Ȋ flow control specifies the flow control of the Modbus slave with which you want
to communicate.
280ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋ serial master instance returns a serial Modbus master instance.


Ȋ error out contains error information.
Step 2: Right click on editor and select Read Holding Registers.vi. It reads value s from
contiguous holding registers. The maximum number of holding registers this VI can
read is 125.

Ȋ Modbus master in specifies the reference to the Modbus master instance.


Ȋ starting address specifies the initial address for the read operation. Valid values
are between 0 and 65, 535
Ȋ number of holding registers specifies the number of holding registers you want
to read. Valid values are within the range [1, 125] .
Ȋ error in describes error conditions that occur before this node runs.
Ȋ Modbus master out returns a duplicate of Modbus master in.
Ȋ register values returns the holding register values.
Ȋ error out contains error information.
Step 3: Right click on editor and select close.vi, which closes and destroys a Modbus
slave instance.

Ȋ Modbus slave in specifies the reference to the Modbus slave instance.


Ȋ error in describes error conditions that occur before this node runs.
Ȋ error out contains error information.

Complete function for reading Set Point (Register Address 0)


ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ281

5.10.3 Inbuilt Function of Modbus Library for Writing Data

Step l: Right click on VI editor and select Create master instance.vi


Step 2: Right click on VI editor and select Write Single Holding Register.vi. It writes
a value to a single holding register.

Ȋ Modbus master in specifies the reference to the Modbus master instance.


Ȋ address specifies the holding register address to which you want to write the
value. Valid values are between 0 and 65,535.
Ȋ holding register value specifies the holding register value you want to write.
Ȋ error in describes error conditions that occur before this node runs.
Ȋ Modbus master out returns a duplicate of Modbus master in.
Ȋ error out contains error information.
Step 3: Right click on editor and select close.vi.

Complete function to write Set Point (Register Address 0)

Results
An interactive user interface is provided through which we can easily read/set the
values of various parameters to achieve the desired results.
282ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

REFERENCES

1. Aditya N. Das, Frank L. Lewis, Dan O. Popa, “DSC in wireless sensor networks”,
Int. J. Wireless Mod. Computer, Vol6, Issue 1, pp. 13–37, August 2009.
2. http://www.ti.com/lit/an/slla070d/slla070d.pdf
3. http://www.rs-485.com/comspec.html
4. Wikipedia
5. http://irtfweb.ifa.hawaii.edu/~smokey2/software/about/sixnet/modbus/modbus_
protocol.pdf
6. http://metering.igmc.ir/static_info/RS485.pdf
7. Modbus protocol reference guide, m. System Co. Ltd.
8. Technical tutorial Introduction to Modbus.
9. User Manual EKI-152X series
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ283

10. User Manual ADAM-4000


11. Newsletter 51141, LabVIEW http://www.ni.com/newsletter/51141/en/
12. Manual LabVIEW 2012 Data Logging and Supervisory Control Module help.
13. http://www.csimn.com/CSI_pages/Modbus101.html

REVIEW QUESTIONS

1. What is data logging?


2. What is SCADA?
3. What is a Modbus protocol?
4. What is the difference between Modbus ASCII and RTU?
5. How many devices can I have on a Modbus network?
6. Where can I get a copy of the Modbus Specifications?
7. If Registers 16-bits how do I read Floating point or 32-bit?
8. What does notation like 40001:7 mean?
9. Reasons to use the LabVIEW DSC Module?
10. Compatibility with OS to run the Serial Server Device Utility EKI-1524?

ANSWERS

1. Data logging is commonly used in scientific experiments and in monitoring


systems where there is the need to collect information faster than a human can
possibly do. In cases where accuracy is essential examples of the types of
information, a data logging system can collect include temperatures, sound
frequencies, vibrations, times, light intensities, electrical currents, pressure and
changes of matter.
2. SCADA (supervisory control and data acquisition) is a system operating with
coded signals over communication channels so as to provide control of remote
equipment (using typically one communication channel per remote station).
3. Modbus is an industrial protocol standard that has been in use for many years.
Modbus ASCII and Modbus RTU are relatively simple serial protocols that use
EIA-232 or EIA-485 to transmit data packets. The protocol defines function codes
and the encoding scheme for transferring data as either single points (1-bit, coils)
or as 16-bit data registers. This basic data packet is then encapsulated according
to the protocol specifications for Modbus ASCII, RTU, or TCP.
4. The Modbus protocol defines a Protocol Data Unit (PDU) that is independent of
the underlying communication layers. Modbus RTU is the most commonly used,
and is a binary representation of the PDU with addressing before the PDU; a
CRC appended to the end. Modbus ASCII is a representation of the same PDU
284ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

using all printable characters (and generally twice as many bytes). Modbus TCP
is essentially exactly the same PDU as Modbus RTU, except the CRC is left off
of the application layer byte string and left up to the TCP layer to deal with
automatically. There are also some additional addressing bytes in the TCP
encapsulation of the RTU packet. The function codes, register numbering, and
addressing are identical regardless of protocol variant. Register types are the
same, i.e., the same data blocks are defined for the Modbus device.
5. Logically, you can address over 250 devices; however, the RS485 transceivers are
not capable of physically driving that many devices. Modbus protocol states that
the limit is 32 devices, and most RS485 transceivers will agree with this. Only if
all devices on the network have low load transceivers, you can have more than
32 devices.
6. You can get a copy of the Modbus protocol specification by visiting www.modbus.
org. There are three documents of primary interest: (1) The application layer
protocol, which defines the function codes and addressing; (2) The definition of
use over a serial line (RTU); (3) The definition of use over Ethernet (TCP). You
will be asked to accept terms of use, but there is no cost for these specifications.
7. The Modbus protocol defines a holding register as 16 bits wide; however, there
is a widely used de facto standard for reading and writing data wider than 16
bits. The most common are IEEE 754 floating point, and 32-bit integer. The
convention may also be extended to double precision floating point and 64-bit
integer data. The wide data simply consist of two consecutive “registers” treated
as a single wide register. Floating point in 32-bit IEEE 754 standard and 32-bit
integer data are widely used. Although the convention of register pairs is widely
recognized, agreement on whether the high order or low order register should
come first is not standardized. For this reason, many devices, including all Control
Solutions gateways, support a “swapped” option. This means that you simply
check the “swapped” option if the other device treats wide data in the opposite
order relative to Control Solutions default order. Control Solutions Modbus
products all defaults to placing the high order, register first, or in the lower
numbered register. This is known as “big endian”, and is consistent with Modbus
protocol, which is by definition big endian.
8. This is a commonly used notation for referencing individual bits in a register.
This particular example references register 40001, bit 7. Bits are generally
numbered starting at bit 0, which is the least significant or rightmost bit in the
field of 16 bits found in a Modbus register.
9. Top 3 reasons are:
(a) Connect LabVIEW to Existing High-Channel-Count Industrial Systems
The LabVIEW DSC Module is shipped with support for commonly used industrial
protocols, including OLE for process control (OPC), which gives an application
ȬŚŞśǰȱ ŠŠȱ ˜’—ȱ Š—ȱ ž™Ž›Ÿ’œ˜›¢ȱ ˜—›˜•ȱ ǻǼȱ Ÿ’Šȱ ˜‹žœȱ œ’—ȱ Š‹ ȳ285

the ability to communicate with virtually all PLCs and PACs. With this flexibility,
you can easily integrate LabVIEW into existing SCADA/HMI systems.
(b) Log Data to a Historical Database, Set Alarms, and Manage Events
With the LabVIEW DSC Module, you can easily log data to the built-in networked
historical database or log into your existing enterprise relational database. Without
additional programming, you can use these same configuration-based tools to set
up the logging of alarm and notification data.
(c) Use a Single Software Tool for HMI and Logic Programming
Developing control applications require expertise in several areas, including
process logic, control system design, and user interface design. The LabVIEW
DSC Module provides an alternative to the conventional development environment
with a single development environment for logic and HMI development.
10. Windows 2000/XP/Vista/7 (32-bit/64-bit)
SCADA USING WONDERWARE
6 INTOUCH

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ SCADA development in detail
Ȋȱ Connecting to InTouch SCADA

6.1 INTRODUCTION : SCADA

SCADA stands for supervisory control and data acquisition. This is a software package
used for control and monitoring of analog and digital parameters using computers. It
can acquire data from sensors.

SCADA PLC

FI FI FI FI

Figure 6.1 Block diagram of a typical SCADA system

In the above diagram, the FI is an acronym for Field Instrument. Some of the examples
of FI are valve controller, temperature meters, etc.
Some of the popular examples of SCADA are Wonder ware InTouch, GE’s Fanuc
Simplicity, Intellution’s Fix32, National Instrument’s LabView, Rockwell Automation’s
RSView32, Siemens’ WinCC Flexible, etc.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ287

6.2 WONDERWARE INTOUCH SCADA

Wonderware is a company who has produced a popular SCADA known as InTouch.


This is heavily used in industrial automation. We will be discussing InTouch to learn
the properties of SCADA in the ensuing sections.
The following are some of the main properties of SCADA:
1. Tag Name
2. Trends
3. Alarms
4. Communication with Excel in simplex and half-duplex modes
5. Recipe management
6. Security
7. Scripts
I will now explain what each means, in a few words, just not to keep the students in
dark at this point of time. Later, we will explore each in full details.
Tag name: Assigning a name to an object

TAG NAME

Analog Digital

Caution: While assigning a TAGNAME one should remember not to give a name
beginning with “a” for digital Tags -- “a” is reserved for analog tags.
The example of a Slider which is an analog tag is shown below:
288ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Trends: Trends are a graphical representation of any object or symbol. The symbol will
not have any property whereas the object will have properties. One can change a symbol
to an object by a process called “break cell”. This is also known as “mimics property”.
Trends can be of two types – Real Time and Historical Time.

Trends

Real Time Trends Historical Time Trends


Note: Real-time trends can have upto 4 Pens whereas Historical Time Trends can have
upto 8.
Alarms: Alarms are warnings. A warning is generated whenever something unwanted
is happening to a machine or system. Alarms are generated at 4 set points for Hi, LO,
Hi Hi,and LOLO.
Communication with Excel: Can be simplex or half-duplex.

Communication

Simplex Half duplex

Note: Simplex means “one time” or unidirectional, e.g. like a memory read. Half duplex
means both directions, e.g., like a memory read and write.
Recipe Management: Recipe management displays the contents. It is just like the
ingredients of a curry. We will discuss them in detail.
Security: Security comprises passwords and authentication just to allow authorized users.
Scripts: This is the programming method of InTouch. Script is a group of programming
lines.

6.2.1 Creating an Application using Application Manager

Once one has the InTouch application opened on your PC, one may execute
File > new > my InTouch application > next >my window > next to create a new window
as shown below.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ289

6.2.2 Creating a New Button

To create a button in InTouch, follow the following steps:


Step 1: Click on the Wizards icon on top of window
Step 2: Click on Buttons
Step 3: Select Set/Reset display which looks like below

Step 4: Now double-click on icon and give a Tag name “b1” which looks like below

Step 5: Now run “Run Time” to run it


Step 6: Click on “0”
290ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Step 7: click on “1”

Step 8: Now take lights from symbol factory and place Tube light on the window.
Step 9: Now click on Tube light and fill in as follows:
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ291

Step 10: Now you can switch ON and switch OFF tube light as follows:

6.2.3 Understanding the Location Property

Location property is a very useful property, which can be used to move an object
horizontally or vertically, or in both directions simultaneously. The object will be moved
from the current position where the object is rested on the window.
Step 1: Say a ball is rested initially as shown below:
292ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Step 2: Say you want to slide the ball through a bridge line as drawn below:

Step 3: Go back and place a Slider s1 on the window which has a vertical range 0-100.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ293

Step 4: Double-click on the ball.

Step 5: Select Horizontal and click on Horizontal and assign s1 as below:

This is the most critical step you need to judge clearly before you budge. In the
properties, while filling remember that you are going to slide the ball from left to right
using slider b1.So the “value at left end” means what should be the value of the slider
when the ball is at the leftmost end. (Which means that the ball is initially in stationary
position i.e. 0). This means that when the slider is 0, the ball will be in the extreme left
position. Now the “value at right end “means the value of slider when the ball is in the
right most position, i.e., 100.
Now forget the slider. Remember the ball. Come to horizontal movement box. Fill in
the moving criteria from the stationary position to left. How much maximum will the
ball move to left from current position? My answer is “0” as it is not going to move left.
To the right? How much maximum will the ball move to the right from its current
position? My answer should be “500” for moving the entire length of the bridge as the
bridge is 500 pixels lengthy.
294ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Now say I type 100 purposefully. What will happen? The ball will move only in the
fifth of the total bridge. See whether it works!

6.2.4 General Theory of using Location property

The best way to demonstrate the Location property is to follow the below steps.
Step 1: Draw a Road for the ball. You want it to move along the path of broken line
(say a ball is rolling over a road), keep the ball in its stationary position.

Now double click the ball and fill horizontal options. Start with two points as given
below (to left and right). Forget the slider entry for the time being.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ295

This means that you want 250 points to the left and 250 points to the right, independent
of the slider value.
Now you may enter the slider values. At the left end of the road, your slider value
is 0. At the right end of the road, you want that the slider value is 100.

Now “run”.

Similarly, one can do the vertical location also.


296ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Vertical location

Step 1: Draw a road for the ball you want it to move along a path of the broken line
(say a ball is rolling over a road). Keep the ball in its stationary position.

Now double click the ball and fill horizontal options. Start with two points as given
below (to up and down). Forget the slider entry for the time being.

This means you want 100 points to up and 100 points to down independent of slider
value. Now you may enter the slider values.
At up end of the road, your slider value is 0. At down end of the road, you want
slider value to be 100.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ297

Now “run”. See that the slider is running along with ball

6.2.5 Vertical-cum-Horizontal Movement Together

The requirement is as follows

Looking at the above graph we get:


Right Top – 250,100
Left Bottom – 250,100
Starting point is at slider Left Bottom – 0,0
298ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Result:

6.2.6 Practical Example on Location Property

Design a screen which will have the ball moving along the following trajectory
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ299

Step 1: Create five(5) balls in such a way that the visibility of the balls will be selected
as follows:

Properties of each ball

Ball-1: Location Horizontal

Ball-1: Visibility
300ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Ball-2: Location

Ball-2: Visibility

Ball-3: location

Ball-3: Visibility
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ301

Ball-4: location

Ball-4: Visibility

Ball-5: location

Ball-5: visibility
302ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

So, the result is as follows:

6.2.7 Orientation Property

Orientation is a concept which is used to rotate an object clockwise or anti-clockwise.


For example, if one likes to rotate the wheel of a car 360ºwith respect to its centre, then
it is possible as shown in the following steps.
Step 1: Double-click on the circle of the following window.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ303

Step 2: Double-click the orientation below.

Step 3: Fill in the CW rotation to 360°, CCW rotation to 0, the value of slider for CW
maximum with 100, and the rest all with zero.

Step 4: You may now move the slider from 0 to 100 to see the wheel rotating from 0 to
360°.
Now take another example to demonstrate the orientation of a line.
Line W=600, H=0 and slider is also at maximum 360. Set the orientation property as
follows:
304ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Step 1: Now when we move 36º, the line rotates with respect to its origin i.e. (0, 0). It
is like a seesaw. The centre of rotation offset from the centre of the object point is 0, 0.

Step 2: Now make the centre of rotation offset from the centre of the object point is 300,
0. When we move 18 degrees, the line rotates with respect to its origin i.e. (300, 0). It is
not like a seesaw. But the fixing point differs as follows. The fixing point is the right
most corner.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ305

Step 3: Now make the centre of rotation offset from the centre of the object point is
–300, 0. When we move 18º, the line rotates with respect to its origin i.e. (–300, 0). It is
not like a seesaw. But the fixing point differs as follows. The fixing point is the leftmost
corner.

The result is as follows:


306ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

6.2.8 Coordinate System of Orientation

To summarize, the coordinate system of orientation is self-explanatory from the above


diagram. Note that the Y-axis is always reversed from normal mathematical notation.

6.2.9 Object Size Property

Object size property is used to adjust the height and width of an object (say a circle)
from its center, top or bottom. Take the following example where we have a circle of
W=150, H=150 and a vertical line of height W=0, H=150.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ307

Now let us put certain conditions in Size property as given below:


Step 1:

Step 2:

Step 3: Result for slider value =60, Anchor=Bottom:


308ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Step 4: Result for slider value =60, Anchor=Top for circle, Anchor=Bottom for line:

Step 5: Result for slider value =60, Anchor=Middle for circle, Anchor=Middle for line:

Exercise 1:

Make a slider-based simulation to demonstrate the following “Conveyor”. Use visible/


invisible property for it to look like only one single ball is moving from top to bottom.
Once the ball reaches the platform by opening & closing the GATES also by expanding
its size (object size property), the conveyor should move the wheels below (by orientation
property) till the ball reached to right most. Then the ball should shrink till it reaches
the destination.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ309

6.3 TRENDS IN WONDERWARE INTOUCH


6.3.1 Real-Time Trends

Trends are the graphical interpretation of data. Real-time trends just update the current
data as the last point in X-axis so that you get to generate a small on-line buffer. This
works in the form of LIFO(Last In first Out).
Let us define a problem where we need to trend the on-line data coming from an
analog sensor every second. The memory buffer needs to be 1 minute. That means latest
1-minute data will always be on the screen. The X-axis will have 30 major divisions,
which means each adjacent major divisions will be 2 seconds apart.

To create such a trend, the graph settings are as follows.


310ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Let us write the steps followed to create this.


Step 1: Select Real-Time Trend into the form from the screen.
Step 2: Double-click the trends and get the above screen then fill in the data variable
name in one of the four pens.

6.3.2 Historical Trends


ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ311

Select the following from trends of symbol factory with Trend Zoom/Pan Panel on the
X-axis and Trend Pen Legend on Y-axis.
Step 1: Select wizards and take “trends” into the form from the screen and select “Hist
Trend/W Scooters” and drag on to the form. Double-click the graph.

Hint: enter HT & PS wherever it asks


Step 2: Double-click the trends and get the above screen
Give Hist Trend a name, say “HT.”
Give Pen Scale a name, say “PS.”
Tick Allow Runtime changes.
Click on the Values on right menus to set Y-axis grid

Enter major divisions as 30, Minor/Major=1


Rest default
312ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Click on the Time on right menus to set X-axis grid

Double-click the tag on the left and fill in the following


ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ313

Click on the Pens on right menus to set one of the eight colors of the graph.

Say OK
Click on right most down arrows like this (>> ) to update the graph

6.4 READING DATA FROM AN EXCEL WORKBOOK INTO INTOUCH


6.4.1 Introduction

It is possible to read data from a Microsoft Excel workbook into an In Touch application.
This Tech Note gives step-by-step instructions on using an access name and tags to read
points of data from a Microsoft Excel Workbook.
314ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Application Versions

InTouch 7.0 and higher versions.


Note: This communication link will only work via the DDE (dynamic data exchange)
protocol. Net DDE is not supported. To verify that DDE has been enabled on your
operating system, review Tech Note 30, from Step 3 to conclusion.

Procedure

Reading data from a Microsoft Excel Workbook is a 2-step process:


1. Creating an access name to communicate with Microsoft Excel.
2. Configuring tags with the correct item naming convention for getting data from
Microsoft Excel.

6.4.2 Creating an Access Name to Connect to Microsoft Excel

Step 1: Open your InTouch application in Window Maker. Click “Special” on the main
menu, then select “Access Names…” This will open the “Access Names” dialog box.
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ315

Step 2: Select “Add…” on the Access Names dialog box to open the “Add Access Name”
dialog.

Step 3: Configure your Access Name as follows:


1. “Access” input field: Provide a name for your Access Name. This can be any
name, but it should be something meaningful to you and/or your operators to
help identify the data source.
2. “Node Name” input field: Enter the name of the computer on which the Microsoft
Excel Workbook is located and open. If on the local system, you can leave this
field blank.
3. “Application Name” field: Enter “Excel.” Do not include the “.exe” extension.
4. “Topic Name” field: Enter the name of the Microsoft Workbook, in the following
format: [Workbookname.xls] sheet name.
For example, say you wish to read data from a sheet titled “Wednesday” within a
Microsoft Excel Workbook titled “Rotations.xls,” as shown in the image below.
316ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

In this example, you would configure your Topic Name as “[Rotations.xls]


Wednesday”.
Ȋȱ In the “Which protocol to use” area, select “DDE”.
Ȋȱ In the “When to advise server” area, select “Advise All Items”.
Example of a completed Access Name for reading data from an Excel Workbook:

6.4.3 Item-Naming Conventions for Tags Getting Data from an Excel Workbook

Now that you have an Access Name created that will connect you InTouch application
to an Excel Workbook, you can create tags to read points of data from that Workbook.
The item naming convention for tag names that are reading data from Excel is based
on the rows and columns of the specified Excel workbook.
For example, if you want to read the value found in the first row and the third column
of the workbook, you would name your item “R1C4” (for Row 1, Column 4) as depicted
in the image below:
ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ317

This tag will pull data from the following location on the Excel Workbook:

Note: For an InTouch tag to acquire data from an Excel Workbook, that Workbook must
be open in Excel on the computer system named in the Access Name “Node Name” field.

6.4.4 Tips and Tricks

1. To launch an Excel Workbook via In Touch scripting, combine the Start App and
String Char Quick Functions to first open Excel, then open a specific Workbook,
as in the example below:
Start App "C:\Program Files\Microsoft Office\Office\EXCEL.EXE " + String Char
(34) + "C:\Documents and Settings\Me\My Workbook.xls".
2. You can view entire Excel Workbooks or Word Documents in InTouch by using
an ActiveX Container. You can get instructions on using an ActiveX container
in Tech Note 117. For calling an Excel Workbook in a container, use the Microsoft
Web Browser ActiveX control and create a script that calls the “Navigate” method
to open the file, as in the example below.
#Explorer1.Navigate(“C:\Documents and Settings\Me\My Workbook.xls”);
It is also possible to create a memory message tag to hold the file path and name if
desired.
For Excel: Make sure that the file extension “.CSV” is associated with “Excel.exe”.
When the method is called, Excel will start and the .CSV file will be opened.

6.4.5 Scripts

Write scripts to run the program automatically. You can use conditional statements,
loops, and local variables in the scripting language to create complex effects in your
application.
There are mainly four types of scripts
1. Windows scripts
2. Quick scripts
318ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

3. Action scripts (used in recipe management)


4. Key scripts
Quick Script is the InTouch HMI scripting language.
The definition of different script types are:
Ȋȱ Application scripts execute either continuously while window viewer is running
or one time when window viewer is started or shut down.
Ȋȱ Window scripts execute periodically when an In Touch window is open or one
time when an InTouch window is opened or closed.
Ȋȱ Key scripts execute one time or periodically when a certain key or key combination
is pressed or released.
Ȋȱ Condition scripts execute one time or periodically when a certain condition is
fulfilled or not fulfilled.
Ȋȱ Data change scripts execute one time when the value of a certain tag or expression
changes.
Ȋȱ Action scripts execute one time or periodically when an operator clicks on an
InTouch HMI graphic object.
Ȋȱ ActiveX event scripts execute one time when an ActiveX event occurs, such clicking
the ActiveX control.

The steps to create the first script program

Step 1: Right-click on the window.


ȱ œ’—ȱ ˜—Ž› Š›Žȱ —˜žŒ‘ȳ319

Aim: To create a self-moving slider a1 Code


320ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

REFERENCE

http://www.logiccontrol.com/datasheets/1/InTouch%2010.X/Scripting%20and%20Logic.
pdf

REVIEW QUESTION

1. What is SCADA?

ANSWER

1. SCADA stands for “supervisory control and data acquisition” and refers to the
collection and management of data that can be used to develop process
management criteria. The acquisition and control of data are essential to any
SCADA process. Along with the task of acquiring the data, there also has to be
a means of controlling the data.
It is this supervisory component that helps to make sense of the acquired data
and allow for its application in a number of different ways.
A sound SCADA system will allow for quick and easy retrieval of the data as it
relates to a number of different scenarios, such as market research, quality control,
and even something as simple as marketing and sales brochure development.
PROGRAMMABLE LOGIC CONTROLLERS, HMI AND
7 VARIABLE FREQUENCY DRIVES (PLC AND VFD)

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Allen-Bradley, Siemens PLC
Ȋȱ Ladder programming of Siemens and AB
Ȋȱ Serial programming using PLC
Ȋȱ DIN, DOUT using PLC
Ȋȱ Connecting to InTouch SCADA
Ȋȱ PLC scan time
Ȋȱ PLC for Variable Frequency Drives
Ȋȱ PLC registers

7.1 PROGRAMMABLE LOGIC CONTROLLER (PLC)


7.1.1 Introduction

PLC is an acronym of programmable logic controller. These are rugged instrumentations


which are specifically built for interfacing analog inputs, analog outputs, digital inputs,
digital outputs, etc. (many more) from/to different sensors/controllers. Some of the
examples of PLC manufacturers are given below.
1. Siemens
2. Allen-Bradley(Rock well Automation)
3. Delta
4. Schneider

Automation

Automation is the delegation of human control functions for increasing productivity,


therefore, reduces manpower. It controls the machines automatically.
322ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 7.1 Schematic diagram of automation

7.1.2 Advance Process Control

Programming Terminal

Power
CPU Memory
Supply

Input Output
Module Module
PLC

Input Output
Devices Devices

PROCESS

Figure 7.2 Programmable logic (PLC) structure

Programmable logic controllers are programmed using an application software on


personal computers. A computer can be connected to the PLC through Ethernet, RS-232,
RS-485 or RS-422 cabling. The programming software allows entry and editing of the
ladder-style logic. This software provides functions for debugging and troubleshooting
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ323

the PLC software, for example, by highlighting portions of the logic to show current
status during operation or via simulation.
The software will upload and download the PLC program. Download means
transferring programs from PC to PLC. Upload means transferring program from PLC
to PC. Downloading means transferring the program into a chip, such as an EEPROM
or EPROM inside the PLC hardware (see Fig. 7.2).

7.2 BASIC LADDER PROGRAMMING


7.2.1 Ladder Logic

Features of ladder logic are given below.


Ȋȱ Primary programming language for PLCs.
Ȋȱ Visual and graphical language, unlike textual high-level, such as C, C++, Java, etc.
Ȋȱ Derived from relay logic diagrams
Ȋȱ Primitive logic operations:
OR
AND
NOT

7.2.2 OR Operation
Simple ladder logic OR operation

Ȋȱ The light should be on when either switch A is on (closed) or switch B is on


(closed). Otherwise, it should be off (Fig. 7.6).
Ȋȱ Task: Implement this behavior using
Relay circuit
PLC Ladder Logic

A B Light
OFF OFF OFF
OFF ON ON
ON OFF ON
ON ON ON
Figure 7.3 OR truth table

Relay circuit

Switches A and B are connected in parallel to relay coils AR & BR respectively. When
switch A (or switch B) is closed relay coil AR (or BR) gets energized.
324ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The Normally Open (NO) contact AR (or BR) gets closed.


Ȋȱ Power is transmitted to coil LR.
Ȋȱ Relay coil LR gets energized.
Ȋȱ The NO contact LR gets closed.
Ȋȱ Power is transmitted to the light bulb.

Relay ladder logic circuit

PLC ladder logic

V+ Com
A Light

B
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ325

Append the above to the leading two rungs of lay ladder logic diagram. Switches A
and B are connected to discrete input channels of the PLC. Light is connected to the
discrete output channel (actuator) of the PLC. When the input switch A (or switch B)
is on the light is on.

7.2.3 AND operation


Simple ladder logic AND operation

Ȋȱ The light should be on when switch A is on and switch B is on (closed). Otherwise,


it should be off (Fig. 7.4)
Ȋȱ Task: Implement this behavior using:
ǐȱ Relay circuit
ǐȱ PLC Ladder Logic

AND Truth Table

A B Light
OFF OFF OFF
OFF ON OFF
ON OFF OFF
ON ON ON

Figure 7.4 AND truth table

Relay circuit

Switches A and B are connected in series to relay coils AR & BR respectively. When
switch A is closed relay coil AR gets energized. The Normally Open (NO) contact AR
gets closed. Power flows to Normally Open (NO) contact BR, where it terminates until
BR is energized. Subsequently, when BR gets energized, LR is energized, which causes
the NO contact LR to close. Power is transmitted to the light bulb.
326ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7.2.4 A Logic Operation


Simple ladder logic operation

The light comes on only when switch A is on (closed) and switch B is off (open).
Otherwise, it should be off (Fig. 7.5).
NOT Truth Table
A B Light
OFF OFF OFF
OFF ON OFF
ON OFF ON
ON ON OFF

Figure 7.5 NOT truth table


Relay Circuit

Switches A and B are connected to relay coils AR & BR respectively. When Switch A is
closed, the relay coil AR gets energized; when Switch B is off (on) the relay coil BR is
not energized (energized), and the BR contact is normally-open (normally-closed).

PLC ladder logic


V+ Com
A B Light

7.2.5 NAND (NOT AND) Operation


Simple ladder logic NAND operation

The light does not come on only when switch A is off and switch B is off. Otherwise,
it should be off (Fig. 7.6).
Ȋȱ Task: Implement this behavior using:
ǐȱ Relay circuit
ǐȱ PLC Ladder Logic
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ327

NAND Truth Table


A B Light
OFF OFF ON
OFF ON ON
ON OFF ON
ON ON OFF

Figure 7.6 NAND truth table


Relay circuit
V+ L1
V+
A B BR
Light

Com
Ladder logic circuit

7.2.6 Digital Logic Gates

Figure 7.7 Logic gates


328ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Basic ladder logic symbol

Normally open contact: Passes power (On) if the coil driving the contact is On (closed).
Allen-Bradley calls it XIC-examine if closed.

Normally closed contact: Passes power (ON) if the coil driving the contact is off (closed).
Allen-Bradley calls it XIO-examine if open.

Output or coil: If any left-to-right path of inputs passes power, the output is energized.
Allen-Bradley calls it OTE-output energize.
( )

Not output or coil: If any left-to-right path of input passes power, the output is
de-energized.

( )

The IEC 61131-3 standards describe the complete list of ladder logic contact and coil
symbols.

7.2.7 PLC Ladder Logic Symbol

Ȋȱ The symbols are ladder logic instructions


Ȋȱ The PLC scans (executes) the symbols

= on = Closed = True = 1

= off = Open = False = 0

Ȋȱ Every PLC manufacturer uses instruction symbols


Ȋȱ Industry trend is based on IEC 61131-3
Ȋȱ Variations in symbols by manufacturers
Ȋȱ Allen-Bradley Control Logix symbols slightly different
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ329

7.2.8 Ladder Logic Diagram

Ȋȱ Power rails - pair of vertical lines


Ȋȱ Rungs - horizontal lines
Ȋȱ Contacts A, B, C, D… arranged on the rungs
Ȋȱ Note: in PLC ladder logic -- no real power flow (like in relay ladder)
Ȋȱ There must be continuous path through the contacts to energize the output
(Fig. 7.8)
Input (Condition) Output
Instructions Instructions
A B C Out 1
( )

D E

F G H Out 2
( )
I¢ K

Continuous path for logic continuity


Power ows

Figure 7.8 Ladder logic diagram

Ladder logic diagram instructions

There are two classes of ladder logic instructions.


Ȋȱ Output: Appears on the extreme RHS of the rung always – Out1, Out2
Ȋȱ Input: Any instruction that can replace a contact
Input (Condition) Output
Instructions Instructions
A B C Out 1
( )

D E

F G H Out 2
( )
I¢ K

Continuous path for logic continuity


Power ows
330ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7.2.9 Function Block Instructions

Ȋȱ Any non-contact instruction


Ȋȱ Timer instruction
Ȋȱ Counter instruction
Ȋȱ Comparison instruction

E
( )
( )
H
Input Output
Function Function
Block Block
Example 1: Draw a ladder diagram that will cause the output, pilot light PL2, to be on
when selector switch SS2 is closed, push button PB4 is closed and limit switch LS3 is
open. (Note: No I/O addresses yet.)

Thought Process

Ȋȱ Identify the output: PL2 appears on the RHS of the rung


Ȋȱ What is the behavior (type of connection to use): sequential operation of all switches
to series connection
Ȋȱ Type of contacts to implement output:

SS2 Closed PB4 Closed LS3 Open

The ladder logic diagram is given below.


SS2 PB4 LS3 PL2
( )

Example 2: Draw a ladder diagram that is equivalent to the following digital logic
diagram.
A
B
C
D + Y
E

Y is on when A is on, B is on and C is off or D is on, or E is off.


Thought process:
Identify the output: Y o coil Y appears on the RHS of the rung
What is the behavior (type of connection to use)?
Ȋȱ The inputs A, B, C for AND gate will be connected in series.
Ȋȱ The D, E inputs for OR gate will be connected in parallel with the output of AND
gate.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ331

Type of contacts to implement output (review the expected behavior again to determine
contact types):
A is on: B is on: C is off:

D is on: E is off:

The ladder logic circuit is given below.

A B C Y
( )
D

Sealing an output:

A B C Y
( )
D

Repeated output: Do not repeat normal output coils that refer to the same address.
A B C Out 1
( )

D E

Other ladder logic

F G H Out 1
( )

The coils for first and second rung refer to Out1, and the second rung overrides the
logic in the first rung.
332ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7.2.10 Timers (Allen Bradley PLC)

There are four fundamental types of timers.


1. Retentive timer
2. Non-retentive timer
3. On-delay timer
4. Off-delay timer

Retentive timer

It is a type of timer that keeps track of how much time has passed and remembers this
value even if the timer stops timing. An example of a retentive timer is a stopwatch.
The below example demonstrates the retentive on-delay timer (Fig. 7.9).
Enable
Txxx
Reset yyyyy

RTO
A Timer Example (EN)
Preset 4000
Accum. 0 (DN)

Example. EN

Example. DN

Example. TT

4
3
Example. ACC 0

0 3 6 9 10 14 17 19
Figure 7.9 Retentive on-delay timer

The most significant difference between on-delay timer which is non-retentive and
retentive is that when the input A is turned off, the accumulator value does not reset
to zero. As a result, the timer turns on much sooner, and the timer does not turn off
after it turns on. A reset instruction will be shown later that will allow the accumulator
to be reset to zero. The DN bit can be pulled down only with reset, once fired earlier.
Retentive off-delay (RTF) timers have few applications and are rarely used. Therefore,
many PLC vendors do not include them.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ333

Non-retentive timer

In a timer, the time delay always starts from zero. If a non-retentive timer is stopped
before the time delay is up, it resets to zero. (Fig. 7.10)

On-delay timer

Figure 7.10 On-delay timer

A timer waits to turn on the output after receiving an on signal from the input. An
on-delay timer will wait for a set time after a line of ladder logic has been true before
turning on, but it will turn off immediately. Consider the example of an old car. If you
turn the key in the ignition and the car does not start immediately, that is an on-delay.
An on-delay timer can be used to allow an oven to reach temperature before starting
production. The below example demonstrates the on-delay timer.
334ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The timing diagram in the figure above illustrates the operation of the TON timer
with a 4-second on-delay. A is the input to the timer, and whenever the timer input is
true, the EN enabled bit for the timer will also be true. If the accumulator value is equal
to the present value, the DN bit will be set. Otherwise, the TT bit will be set and the
accumulator value will begin increasing (TT bit means Time Timing bit: the bit that
stores the accumulated time during the time delay). The first time A is true, it is true
only for 3 seconds before turning off, after this the value resets to zero.
(Note: in a retentive time, the value would remain at 3 seconds.) The second time A
is true, it is on for more than 4 seconds. After 4 seconds the TT bit turns off, and the
DN bit turns on. But, when A is released the accumulator resets to zero, and the DN
bit is turned off.

Off-delay timer

A delay timer that immediately closes contacts when the control coil is energized then
waits for a predetermined amount of time to open them after power is removed from
the coil. An off-delay timer will turn on immediately when a line of ladder logic is true,
but it will delay before turning off (Fig. 7.11).

Figure 7.11 Off-delay timer

Consider the example of an old car. If you turn the key to stop the engine but the
engine doesn’t stop for a few seconds, it is an off-delay. An off-delay timer can keep
cooling fans on for a set time after the oven has been turned off. The off-delay timer is
explained below.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ335

This is exactly similar to the on-delay timer, but the DN bit is exactly inverted. Note
that, this timer has a time base of 0.01s, with a preset value of 3500, giving a total delay
of 3.5s. As before the EN enable for the timer matches the input. When the input A is
true, the DN bit is on. It is also on when the input A has turned off, and the accumulator
is counting. The DN bit only turns off when the input A has been off long enough so
that the accumulator value reaches the preset. This type of timer is not retentive, so
when the input A becomes true, the accumulator resets.

7.2.11 Siemens PLC Addressing and Timers


Some basic specifications of a Siemens PLC

Model No: S7 200 CPU222


Program S/W: S7 micro Win
Communication Cable: PPI (Point-to-point Interface)
No. of Inputs: 8
No. of Outputs: 6
Baud Rates: Programmable 9600 bps
Difference between rung and Network Siemens uses network in place of rung of ABB.

Addressing Scheme in Siemens PLC

Input: I0.0 to I0.7


An example is given below.

I0.0 I0.0 I0.1


Output: Q0.0 to Q0.5
An example is given below.

q0.0 q0.1 q0.2

Binary: M0.0 to M0.255

m0.0 m0.1 m0.2


336ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Timer: T37

in

pt
Timer T37
The timer has preset times.

Timer operations in Siemens

(a) On timer operation (Siemens PLC)


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ337

(b) Off timer operation (Siemns PLC)


Note: TT bit should be N/C in series instead of N/O.

Siemens Counter

I0.1
c0

R
pv

The counter needs a contact at the reset pin.


Done bit of C0 counter.
338ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7.2.12 PLC on a Chip: New Trend

“PLC on a Chip” is a programmable logic controller (PLC) on a single microprocessor


chip. Sure, it needs to be mounted on something. As with other microprocessors, a static
charge will fry it. It requires a power supply and a bus for inputs/outputs (I/O) and
some programming interface and some other external, off-chip items. But just as assured,
it is an honest and good PLC that can be embedded into devices, machines, and systems,
at an affordable price.
The goal of the chip, explains Terry Divelbiss, president of Divelbiss Corp. (Frederick
town, OH), is to “offer an alternative to OEMs manufacturing front-end equipment,
tail-end equipment, or the equipment in the middle.” He points out that there’s need
to go directly from the logic level of the sensor, machine tool, or whatever to a PLC.
An embedded PLC does exactly that. “To me, a PLC is a combination of the right
programming capability with everything else ready to go–communications, digital and
analog I/O, and high-speed counting capability,” says Divelbiss.
The PLC chip he is selling measures 21.5 mm2 (0.8465 in2). It comes in four types that
are mostly differentiated by on-board flash memory (128 KB to 512 KB) and random
access memory (8 KB to 14 KB). The chips are similar to the CPU in a desktop computer
in that they require 5 VDC. They can operate at temperatures between –40°C and 85°C
(one is ruggedized for temperatures up to 125°C). All the chips have asynchronous serial
communication (up to 11.5 kilobaud) and eight analog ports (0 to 5 VDC input, 10 bits).
Two of the chips offer up to five CAN ports. (These are proprietary CAN ports that can
communicate to CAN open). They also have some pulse-width-modulation ports: up to
eight 8-bit channels or four 16-bit channels. For digital I/O, the chips support 26 direct
I/O or 24 inputs, 15 outputs, plus 256 external I/O points. All I/O and integrated functions
are pre-assigned.
The chip’s kernel is programmed through conventional PLC ladder logic or function
block languages, versus C or some other chip-level programming language. (You program
the chip using Divelbiss' own PC-based EZ Ladder software, which conforms to the
IEC-61131 standard plus extensions.) The chip can hold up to 51 instructions per function
block. These are typical PLC instructions, including contacts, counters, timers, drum
sequencers, and functions for math, bit manipulation, closed loop control, and
communications. Function block programming provides additional decision process
capabilities, such as comparisons so that a counter, when reaching some pre-specified
value, triggers an event. In test operations, PLC on a chip can scan through 500 rungs
of ladder logic in 2.5 ms. Not surprisingly, scan times are longer in control programs
with a lot of math in the function blocks.
What you get in a small box.
You could get these same PLC capabilities through a custom control chip. That’s not
only expensive but dedicated chips and “one-offs” don't often conform to any standard.
“The ability for the OEM’s customer to make changes doesn’t exist, unless it’s a simple
menu thing,” says Divelbiss. Another option is to go the “soft PLC” route. This is where
you have PLC functionality in an industrialized personal computer. The debate over
conventional PLCs and soft PLCs is a legion.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ339

According to Divelbiss, the PLC on a Chip is much more than a smart relay and much
more than a relay replacer that basically consists of a timer and a counter. This chip,
says Divelbiss, is more like a micro PLC.
Micro PLCs are targeted for small machine control, where space for additional
electronics (read “control system”) is at a premium and the operating environment (read
“harsh”) demands reliable performance. For instance, the 16 I/O, DC-powered Allen-
Bradley MicroLogix 1000 measures 120 × 80 × 40 mm3 (4.72 × 3.15 × 1.57 in3). Execution
speed for a typical 500-instruction program is 1.56 ms (throughput 1.85 ms). For
communications, the PLC offers direct connections to programming devices or operator
interfaces, as well as options for DH-485 networking, Device Net, and Ether Net/IP.
If PLC size is the overriding factor, the next step in terms of compactness is the nano
controller. The Allen-Bradley Pico GFX-70 announced in January, for example, is aimed
at simple logic, timing, counting, and real-time clock operations. Unlike other Allen-
Bradley Pico controllers, this one includes a 70 mm (2.75 in) back lit monochrome LCD
display (a.k.a. human/machine interface, HMI) and keypad buttons for both control
programming and control monitoring. The unit measures (with keys) 86.5 × 86.5 × 43
mm3 (3.41 × 3.41 × 1.69 in3) and weighs 130 g (0.287 lb). Mounting requires two 22.5 mm
(0.886 in) holes spaced 30 mm (1.18 in) apart. The components for the power supply
and I/O snap onto the back of the display. The processor can also be mounted to a panel
or DIN rail for use without the HMI. The Pico communicates through GFX proprietary
Pico-Link, a proprietary protocol based on CAN open, which lets up to eight Pico units
be connected from up to 1000 m (3280 ft) away, providing up to 272 I/O points through
Pico expansion I/O modules. However, admits Stevens, “If you’re looking to get
information from basically the shop floor to the top floor, you're not going to want to
use a Pico. You want something like a MicroLogix, which can jump onto a major network."
One word: “embedded ness”
The cost of the PLC on a chip ranges from about $20 (low-end chip; 5000 quantity)
to just over $40 (high-end chip; in trays of 60). Modules, separate boards with features
such as connectors and critical circuits that facilitate implementation of the chips, cost
more, but they’re simpler to use. Low quantities of the 128 KB flash memory version of
the module, without the real-time clock, can go for as much as about $70. With CAN
ports, the module can cost as much as $90. Compare this to the cost of the Pico GFX-70.
These start at $525 while a standard Allen-Bradley Pico (without the HMI) can be had
for $150 in large quantities.
The comparison is not exactly apple-to-apple. The Pico PLCs are handy, small,
inexpensive, powerful packaged units. However, they satisfy an entirely different niche
on the factory floor than the PLC on a chip, which can be embedded into sensors, motor
drives, machine and engine controls, remote control and monitoring system (such as
SCADA systems)—you name it. Divelbiss envisions sprinkle these PLC chips all over a
conveyor system. This way, you can have sensor capabilities and motor control—
intelligent decision/control points—all over a materials handling system. The alternative
approach would be to wire physically individual points or local controllers to whatever
flavor of PLC out on the shop floor or that can be hung nearby.
340ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7.3 CONTROL THREE-PHASE INDUCTION MOTORS USING DELTA VFD AND


AN AB MICROLOGIX 1000 PLC A PROJECT EXAMPLE

3 Phase AC

I O
Run/Stop
Motor M0
n AB MicroLogix U
VFD
FWD/REV P 1000 T M1
Direction PLC
U P
Motor Ran
T U Indicator
Control
Board T
Direction Indicator
RS 232

PC

RSLogix s/w Induction


USB RS 232 to USB Converter
Motor

Figure 7.12 Entire system layout

7.3.1 Introduction

Various automation processes in the industry need control of AC induction motors using
AC drives. Presented here is a robust system for On/Off, varying the speed and direction
of rotation of an industrial three-phase induction motor. We use Delta AC motor drive
for the operation. A simple control panel is wired using an Allen-Bradley PLC for
demonstration and an extended Wonderware InTouch SCADA can be developed for
PC based virtual control panel. (Fig. 7.12)

Three-phase induction motor

An electrical motor is an electromechanical device, which converts electrical energy into


mechanical energy. In the case of three-phase AC operation, the most widely used motor
is the three-phase induction motor as this type of motor does not require any starting
device or we can say they are a self-starting induction motor.

What are drives?

Often in industry, the need arises for controlling the speed of a three phase induction
motor. Delta provides a user-friendly AC drive for doing the operation. With modern
power electronics and advanced microprocessor technology, Delta’s AC motor drives
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ341

are able to control efficiently motor speed, improve machine automation and save energy.
Taking advantage of its strong position in power electronics technology, Delta’s VFD
series of AC motor drives has evolved rapidly. Each drive series is designed to meet
specific application needs. AC drives accurately control speed and torque, smoothly
handle an increased load, and provide numerous custom control and configuration
operating modes. The AC motor drive product line provides a full range of motor control
technologies and is used throughout a wide range of industries, to enhance and improve
machine automation. VFD (variable frequency drive) can be used to vary speed, direction
and other parameters of a three-phase motor. We are using the two-wire method for
controlling the speed and direction of the motor (Fig. 7.13).
There are two types of drives:
(a) AC drive
(b) DC drive
AC drive is also known as VFD (variable frequency drive)
DC drive is also known as VVD (variable voltage drive)
Motors are of two types:
(a) AC + DC induction
(b) Non-induction
The AC + DC induction motor is controlled by an AC drive (VFD).

Working of a VFD

The first stage of a VFD, is the converter. The converter is comprised of six diodes,
which are similar to check valves used in plumbing systems. They allow current to flow
in only one direction; the direction shown by the arrow in the diode symbol. For example,
whenever the A-phase voltage (voltage is similar to pressure in plumbing systems) is
more positive than B or C phase voltages, then that diode will open and allow current
to flow. When the B-phase becomes more positive than the A-phase, then the B-phase
diode will open, and the A-phase diode will close. The same is true for the 3 diodes on
the negative side of the bus. Thus, we get six current “pulses” as each diode opens and
closes. This is called a “six-pulse VFD,” which is the standard configuration for current
VFDs.

3-phase
230 V AC Processing
and
Converter PC Filter Inverter
Regulating
Unit

Figure 7.13 Block diagram of a drive


342ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

We can get rid of the AC ripple on the DC bus by adding a capacitor. A capacitor
operates in a similar fashion to a reservoir or accumulator in a plumbing system. This
capacitor absorbs the AC ripple and delivers a smooth dc voltage.
The diode bridge converter that converts AC to DC is sometimes just referred to as
a converter. The converter that converts the DC back to AC is also a converter, but to
distinguish it from the diode converter, it is usually referred to as an “inverter”. It has
become common in the industry to refer to any DC-to-AC converter as an inverter.
When we close one of the top switches in the inverter, that phase of the motor is
connected to the positive DC bus and the voltage on that phase becomes positive. When
we close one of the bottom switches in the converter, that phase is connected to the
negative DC bus and becomes negative. Thus, we can make any phase on the motor
positive or negative at will and can thus generate any frequency that we want. So, we
can make any phase positive, negative, or zero (Fig. 7.14).
Notice that the output from the VFD is a “rectangular” waveform. VFDs do not
produce a sinusoidal output. This rectangular waveform would not be a good choice
for a general-purpose distribution system, but is perfectly adequate for a motor. If we
want to reduce the motor frequency, then we simply switch the inverter output transistors
more slowly. But, if we reduce the frequency, then we must also reduce the voltage to
maintain the V/Hz ratio. Pulse width modulation (PWM) does this. Imagine that we
could control the pressure in a water line by turning the valve on and off at a high rate
of speed. While this would not be practical for plumbing systems, it works very well
for VFDs. Notice that during the first half cycle, the voltage is On half the time and Off
half the time. Thus, the average voltage is half of 480V or 240V. By pulsing the output,
we can achieve any average voltage on the output of the VFD (Fig. 7.15).

AC to DC DC DC to AC
Converter Bus + 650 V DC Inverter

480 V
A
+ M
B

C

0 V DC

Figure 7.14 Circuit model of a VFD


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ343

Figure 7.15 Waveforms at different operating frequencies and average voltages

Selection of Delta VFD-M as AC drive

Delta VFD-M is a sensor less vector micro AC drive. The compact design is ideal for
small and medium horsepower applications. The M drive is designed to provide an
ultra-low-noise operation and includes several innovative technologies that reduce
interference (Fig. 7.16).
This drive can have numerous applications like packing machine; dumpling machine;
treadmill; temperature/humidity control fan for agriculture and aquaculture; mixer
for food processing; grinding machine; drilling machine; small size hydraulic lathe;
elevator; coating equipment; small size milling machine; robot arm of injection machine
(clamp); wood machine (two-side woodworking planer); edge bending machine,
elasticizer, etc.

Specifications

Ȋȱ Output frequency: 0.1 ~ 400 Hz


Ȋȱ Adjustable V/f curve and vector control
Ȋȱ Carrier frequency up to 15 kHz
344ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Auto torque boost & slip compensation


Ȋȱ Built-in PID feedback control
Ȋȱ Built-in MODBUS communication, baud rate up to 38400 bps
Ȋȱ Speed holding function
Ȋȱ Built-in sleep/revival function
Ȋȱ Support communication module (DN-02, LN-01, PD-01)

Figure 7.16 Delta VFD-M

7.3.2 Steps for Complete Motor Control

1. Check the connections of L1, L2, L3; T1, T2, T3 (used for giving input 3-phase to
VFD and connecting the motor to it) and wires coming out of M0, M1, and GND.
2. Switch on the 3-phase power supply.
3. For programming the VFD-M, follow the following instructions:
(a) Press mode
(b) On F60.0, press enter
(c) Click Mode
(d) Select the appropriate parameter with the help of up/down keys available on
the keypad.
(e) For example, for Pr0, select P00.
(f) According to the manual, set the parameters for the required mode of operation
(g) Press Enter - > End
Note: At any point, press Mode to go to the previous step.
For a motor running from external controls, we have 3 modes of operation; two are
2-wire methods, and one is a 3-wire method. Other than these, there is the default
method operable from the given digital keypad.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ345

Test run for VFD

The factory setting of the operation source is from the digital keypad (Pr.01=00). You can perform a
trial run by using the digital keypad with the following steps (see Fig. 7.17):
1. After applying power, verify that the display shows F60.0Hz. When AC motor drive is in standby
situation, STOP LED and FWD LED will light up.
2. Press Key to set frequency to 5Hz.
3. Press RUN key, RUN LED and LWD LED will light up, which indicates operation command is
forward running. And if you want to change to reverse running, you should press . And if you
want to decelerate to stop, please press STOP key.
RESET
346ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Selection mode
START

? Mode ? Mode ? Mode ? Mode ? Mode

Go Start

Note: In the selection mode, press Inter to set the parameters.

To set parameters

? Inter
? or
? Enter ? Enter
Parameter set
successfully

? Mode
Move to previous
display
Parameter set
error
Note: In the parameter setting mode, you can press Mode to return to the selection mode.

To modify data
Start

? ?
To set direction
(When operation source is digital keypad)

? or
? or

Figure 7.17 Pin out connection diagram for VFD-M

VFD-M Programming

There are two contacts, M0 and M1. Whenever M0 is closed, the VFD goes into the run
mode. If it is open, there is no rotation of the motor. M1 decides the direction of rotation.
If M1 is open, it rotates in the forward direction, and if closed, then in the reverse
direction.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ347

Parameters needed for two-wire external control mechanism

Parameter Explanation Settings Factory Setting


Pr.00 Source of 00: Master frequency determined by 00
Frequency digital keypad
Command 01: Master frequency determined by 0
to +10 V input on AVI terminal with
jumpers
02: Master frequency determined by 4
to 20mA input on ACI terminal with
jumpers
03: Master frequency determined by
RS-485 communication port
04: Master frequency determined by
potentiometer on digital keypad
Pr.01 Source of 00: Operation determined by digital 00
Operation keypad
Command 01: Operation determined by external
control terminals, keypad STOP is
effective
02: Operations determined by external
control terminals, keypad STOP is
ineffective
03: Operation determined by RS-485
communication port, keypad STOP is
effective
04: Operation determined by RS-485
communication port, keypad STOP is
ineffective
Pr.38 Multi-function 00: M0: FWD/REV, M1: REV/STOP 00
Input Terminal 01: M0: RUN/STOP, M1: REV/FWD
(M0,M1) 02: M0, M1, M2: 3 wire operation
control mode

Parameters for the above mode are set as:


Pr.00 set to 01 (for controlling master frequency via potentiometer)
Pr.01 set to 01 (external controls, via M0, M1)
Pr.38 set to 01 (M0, M1 set as run/stop and fwd/rev)
Set Pr.00 to 00 for controlling master frequency by digital keypad, and 01 for controlling
via potentiometer attached as shown in the first pin connection diagram.
Pr.38 should be set to 01, as shown in the above diagrams.
Once all these parameters are set, follow the 2-wire mode operational steps for running
the motor.
348ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

01: Two-wire operation: Only Pr. 38 can be set to “1”.

PUN/STOP
M0 “Open”, Stop, “Close”; Run

M1 “Open”: FWD, “Close”; REV


REV/FWD
GND VFD-M

Note: Mutli-function input terminal M0 does not have its own parameter designation.
M0 must be used in conjunction with M1 to operate two and three wire control.

7.3.3 Using PLC to Interface to VFD

PLCs support digital input/output very effectively. So, a PLC can also be used to control
the operation of VFD, hence to finally control the connected three-phase induction motor.
Allen-Bradley MicroLogix 1000 PLC is connected to Delta VFD-M and is programmed
using ladder programming using RS Logix.
We connected the M0 and M1 to O2 and O3 (outputs) of PLC and control O2 and
O3 using the Ladder Logic. The figure above shows a logic defined for mode 01, i.e.
Pr.38 = 01. O:0.0/2 is connected to M0. When I:0.0/2 is set on, it puts the motor in the
run mode. Now, even if I:0.0/2 is switched off, O:0.0/2 remains on due to the logic
defined. It can only be stopped by pressing I:0.0/2 again.
I:0.0/3 controls O:0.0/5, which in turn, is connected to M1, which decides the direction
of rotation of the motor.
O:0.0/3 is the LED, which turns on when the motor is in run mode.0:0.0/5 is the LED,
which turns on when the motor is running in the forward direction and turns off in the
reverse rotation.

Figure 7.18 Ladder program for control


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ349

Figure 7.19 Control board for motor control operation

Figure 7.20 Allen-Bradley PLC connection

Figure 7.21 Varying speed of induction motor via potentiometer


350ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 7.22 Three-phase induction motor

7.4 PROJECT: BUILD AN AUTOMATION SYSTEM USING ALLEN-BRADLEY


PLCS AND INTOUCH WONDERWARE SCADA
7.4.1 Introduction

Figure 7.23 A typical Wonderware InTouch graphical user interface


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ351

Industrial control systems are always very complex and cumbersome to handle. For
electronics engineers, it is becoming essential to understand computer control system
using PLC and SCADA. Present here is a very efficient and expandable robust control
system solution for industrial purposes. For the proposed system, we use an AB Allen-
Bradley MicroLogix 1400 PLC 1766, Wonderware InTouch 2012R2 SCADA and a KEP
Server ver.v5 software for communicating between PLC and SCADA. Wonderware
InTouch SCADAs are becoming increasingly popular due to its powerful, user-friendly
graphics as shown below.
The entire process can be summarized in the following steps:
1. The RSLogix family of IEC-1131-compliant ladder logic programming packages
helps you maximize performance, save project development time, and improve
productivity. This family of products has been developed to operate on Microsoft
Windows operating systems. Supporting the Allen-Bradley SLC 500 and
MicroLogix families of processors, RSLogix 500 was the first PLC programming
software to offer unbeatable productivity with an industry-leading user interface.
PLC is programmed using ladder programming in RSLogix software. Different
inputs and outputs have different addresses. Mostly the field devices, which are
to be controlled, are connected to the PLC via digital input, analog input, digital
output, and RS-232, etc. The address of each device, module, registers, etc., is
specific to each PLC manufacturer like Allen-Bradley, Siemens, Schneider,
Mitsubishi, Hitachi, Delta, etc.
2. The PLC is connected to PC via Ethernet. Since PLC and SCADA, both are from
different manufacturers; we have used an intermediate OPC link (communicator)
between them. This job is done by KEPServer, installed in the PC.
3. The PLC IP address is configured using the software tool “BOOTP Server”.
4. When the main SCADA is running, applications like KEP Server should be running
in background and PLC should be in online mode.
5. Using SCADA, a graphical user interface is built to monitor & control various
parameters like current/voltage, and to switch on/off different devices.

7.4.2 Selection of Allen-Bradley PLC Manufactured by Rockwell Automation

For a beginner, it is better to start with MicroLogix family of PLCs from Allen-Bradley.
The MicroLogix 1000 controller offers control capabilities in an affordable, compact
package. The MicroLogix 1200 provides features and options to handle an extensive
range of applications. The expandable MicroLogix 1500 controller helps you achieve
high-level control in a variety of applications. The MicroLogix 1100 and 1400 controllers
increase the application coverage with enhanced network communications at an
affordable price. RSLogix 500 programming software and RSLogix microprogramming
software, provide an instruction set that is common to the MicroLogix and SLC 500
controller families (Fig. 7.24).
352ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7.4.3 MicroLogix 1000 Programmable Logic Controller Systems

Figure 7.24 MicroLogix 1000 PLC

Product: 1761L10BWA
Description: MicroLogix 1000, 120/240V ac power, (6) 24V dc digital inputs, (4) relay
outputs

Features

Available in 10-point, 16-point or 32-point digital I/O versions


Analog versions available with 20 digital I/O points, 4 analog inputs (two voltage and
two current) and 1 analog output (configurable for either voltage or current) provides
a compact form factor, with footprints as small as 120 mm u 80 mm u 40 mm (4.72 in.
u 3.15 in u 1.57 in).
It offers fast processing with typical throughput time of 1.5 ms for a 500-instruction
program and has pre-configured 1 KB program and data memory to ease configuration.
It includes built-in EEPROM memory; hence, there is no need for battery backup or
separate memory module.
The device offers peer-to-peer messaging (up to 32 controllers on a DH-485 network)
through a 1761-NET-AIC communication interface. Communication takes place via
DeviceNet™ and EtherNet/IP™ through 1761-NET-DNI and 1761-NET-ENI
communication interfaces.
It includes a built-in high-speed counter (only on controllers with 24V DC inputs)
and lets you customize input response time and noise rejection using adjustable DC
input filters.
This device supports simple connectivity through RS-232 communication channel to
a PC for program upload, download, and monitoring
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ353

7.4.4 MicroLogix 1400 Programmable Logic Controller Systems

Figure 7.25 MicroLogix 1400 PLC

Product: 1766- L32BWA


Description: MicroLogix 1400, 12 digital fast 24V dc inputs, 8 digital normal 24V dc
inputs, 12 relays outputs, RS-232 ports, 110/240V ac power (see Fig. 7.25).
1766 MicroLogix™ 1400 Programmable Logic Controller Systems build upon critical
MicroLogix 1100 features: EtherNet/IP™, on-line editing, and a built-in LCD panel. These
controllers feature a higher I/O count, faster high-speed counter, pulse train output,
enhanced network capabilities and back light on the LCD panel. Controllers without
embedded analog I/O points provide 32 digital I/O points while analog versions offer
32 digital I/O points and 6analog I/O points. You can expand all versions with up to
seven 1762 expansion I/O modules.

Features

Ethernet port provides web-server capability, e-mail capability and protocol support for
DNP3 protocol support. Built-in LCD with backlight lets you view the controller and
I/O status. Built-in LCD provides a simple interface for messages, bit/integer monitoring,
and manipulation.
Application capabilities can be expanded through support for as many as seven 1762
MicroLogix Expansion I/O modules with 256 discrete I/O, as many as six embedded 100
kHz high-speed counters (only on controllers with DC inputs), two serial ports with
DF1, DH-485, Modbus RTU, DNP3 and ASCII protocol support.
There are 10 KB words in user program memory with 10 KB words in user data
memory, up to 128 KB for data logging and 64 KB for the recipe.

PLC Connections

One can buy a compact AB Allen-Bradley MicroLogix 1400 PLC 1766, with 8 DIO &
two built-in serial ports (Model 1766) for initial development. We used MicroLogix 1400
354ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

controllers, which are suitable for utilization in an industrial environment. Specifically,


this equipment is intended for use in clean, dry environments.
Typical PLC connections for automation of an experimental facility is shown in
Fig. 7.25. Allen-Bradley Micro Logix 1400 has various digital IN and digital output pins
operated by +24 V DC. An analog input module is added separately. Another high
current 1000A power supply device is connected via RS-232 protocol, where only three
lines viz. TX, RX, GND are used for communication via the PLC serial port. Finally, AB
PLC is connected to the PC via Ethernet port (Fig. 7.26).

7.4.5 RS-232

RS-232 is a serial protocol that converts parallel data to serial bits (pulses) and sends
across 3 wires, i.e., TX, RX, and GND. In most of the cases, the number of wires required
is just 3, but in special circumstances it is up to 9 wires (say an RS-232 modem).
Allen-Bradley 1400 series has two serial ports. The first one is through a PPI cable
with the other end is a 9-pin D-connector. This needs a null modem connector to connect
to any PC having a serial port or USB-serial adapter. The null modem connections are
shown in Fig. 7.26.

TX RX

PC RX TX RS232-PLC
DTE GND DTE

Figure 7.26 Null modem connection

ACID-Temperature

Analog
ACID Pump status ON/OFF
IN
Digital OUT

Acid pump
Digital IN

ChILLER Status
PLC Chiller
ON/OFF
BLOWER Status
Ethernet RS 232

RSLogic Intouch
SCADA TX 100 A
KepServer
High Current
RX Power Supply
GND Device
PC

Figure 7.27 Schematic diagram: PLC connections


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ355

Interfacing PLC to Computer

MAX1400 has three ports. The first one is COM1 (round connection). The second one
is COM2 (9-pin D connection 0) which is for RS-485/RS-232 communications. The third
one is an Ethernet for Ethernet/IP driver-based communications. Therefore, it is easy
for anyone to configure Ethernet as the download port and COM1 as the serial port for
RS-232 communications.
The Allen-Bradley PLC is connected to the computer via Ethernet. We need to interface
the programmable controller to configure and program.

Adding drivers

Adding any driver is required to be done from RSLogix classic software. To add any
driver you need to click on the middle icon and add RS-232 DF1 driver.

Software for Interfacing

RSLinx Classic is a software tool from Rockwell Automation Networks and Devices. It
is a comprehensive factory communication solution, providing Allen-Bradley
programmable controller access to a wide variety of Rockwell Software and Allen-Bradley
applications. These range from device programming and configuration applications such
as RSLogix.
BOOTP server is a suitable server to establish communication between PC and
Rockwell programmable controller (Fig. 7.28).

Figure 7.28 Interfacing the PLC


356ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Communicating to Hyper Terminal

How does one know that the PLC is transmitting characters out of its serial port?
You can view the pulses or protocol produced using a hyper terminal window.
You need to set the Hyper Terminal settings to 19200,N,8,1 which is same as the
settings of PLC serial DF1 driver.
Interfacing PLC via Ethernet to PC to make it available to software for configuration
and programming
Double click the MAC and enter the IP:

Figure 7.29 Setting BOOTP server properties

Figure 7.30 Pinging to check if PLC connection is established

Ladder programming

Once the AB PLC is successfully interfaced to the PC, we need to properly program it
using RSLogix provided by Rockwell Automation. For programming the PLC, we use
ladder programming. Typical PLC programs use blocks like timers TON & TOFF,
counters, digital input outputs, RS-232 communication blocks, etc. Ladder program is
similar to the wiring diagram of the circuit. We redraw the wiring diagram using two
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ357

vertical lines to represent the input power rails and stringing the rest of the circuit
between them. Subroutines are implemented as another ladder.
A typical example of a block used for RS-232 programming is AWA:

ASCII Write Append (AWA)

The AWA instruction sends a specified number of characters (e.g., 50) of the Source tag
(ST14:0) to a PLC serial port2 and appends either one or two pre-defined characters. It
is used for the RS-232 communication (Figs. 7.31 & 7.32).

AWA
ASCII Write Append EN
Channel 2
Source ST14:0 DN
Control R6:2
String Length 50< ER
Characters Sent 3
Error 00h

Figure 7.31 AWA block

SCL
Scale
Source I:1.0
0<
Rate [/10000] 33
33<
Offset 0
0<
Dest N7:0
0<

Figure 7.32 SCL block

Similarly, SCL is an instruction used to read and scale an analog input to a


corresponding physical value like temperature, pressure, etc.
In the above example, the address for analog input is I:1.0 and the converted raw
data is divided by 10000 and added to offset to implement a linear transfer function
like y = mx + c.
A number of free ladder programming tutorials are available on the net. Inside the
PLC, we have various registers like output, input, status, binary, etc. Each bit in these
registers specifies a function. Addresses of the devices are built on the basis of the names,
PLC slot number, word and bit number. Address representations differ from manufacturer
to manufacturer. (Fig. 7.33)
358ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

TON
T4:1 Timer on Delay
0000 EN
DN Timer T4:0
Time Base 0.01 DN
Preset 25<
Accum 25<
T4:0 TON
0001 Timer On Delay EN
DN Timer T4:0
Time Base 0.01 DN
Preset 25<
Accum 3<
T4:0 ISR
0002 Jump To Subroutine
DN SBR File Number 0:3

Figure 7.33 Sample ladder program

Table 7.1 shows some of the bit addresses of PLC and how they are related to field
devices.

Table 7.1 Example of BIT addresses and their functions in PLC


BIT Address Button (function)
CS:1.ACC Current cycle status
B3:0/10 Start
B3:4/1 Acid Pump
I:0/3 Fume Hood
B3:4/0 Chiller
T4:2.TT PS Status
N7:0 Acid Temp
CS:1.pre Total Cycle
B3:0/0 Verbose cmd read
B3:0/1 Cmd read2
B3:0/2 Max current
B3:0/3 18V
B3:0/4 Read Current
B3:0/5 Cmd read5
B3:0/6 0V power supply via rs232
B3:0/7 Read MV
B3:0/8 Cmdread8
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ359

A typical address of an AB PLC for output coil is built as in the figure below (Fig. 7.34).

O : 0.0/4
Bit address
O = output le
0 = word 0

0 = PLC slot 0
(xed I/O)

Figure 7.34 A typical address for AB PLC

Once you write your Ladder code for the PLC, download the Ladder code into the
PLC. Let the PLC be in RUN mode.
The following window shows how an RS-232 port can be configured for handshaking
a power supply device which has settings 9600,N, 8,1 (Fig. 7.35).

Figure 7.35 Setting RS-232 channel configuration


360ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 7.36 Downloading the ladder program into the PLC


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ361

7.4.6 Wonderware InTouch

Wonderware’s world-famous, award-winning InTouch HMI software for visualization


and industrial process control offers outstanding ease of use and simple-to-configure
graphics. For having an interactive GUI (graphical user interface) to control the outputs
of PLC, RS-232 devices via PLC, we use Wonderware InTouch SCADA. A simple GUI
can be made in Wonderware by following simple steps:
1. Open the Wonderware Development tool by double-clicking on the Desktop icon.
2. Start a new project.
3. From the palette on the right side, choose an appropriate graphical object to be
inserted.
4. Click on the screen to insert the object.
5. Double click on the object, to add a suitable Tag name and Type of object. Type
defines the usage; it may be analog or discrete.
6. Double-click on the tag to assign properties to the object. Different operations
like visibility, or blink can be controlled on the basis of scripting.
7. If the tag is I/O type (meant to read or control a device), specify the address of
the device.
8. Address of the device can be obtained from registers of the PLC, which can be
viewed in the RSLogix.
9. In the Modify Access name window, keep the Access name as KEP Server EX_SL.
KEP Server acts as a communicator between RSLogix and Wonderware InTouch.
10. In this fashion, develop the entire GUI with specific tag names and addresses of
devices and PLC variables used in ladder logic.

Access name

Each PLC uses a specific protocol to communicate with the I/O server or DA server.
InTouch then uses an access name concept to continue this communication for DDE
(dynamic data exchange). Typically, because here KEP Server is acting as a communicator
between PLC RSLogix and Wonderware InTouch, we specify Access name in InTouch
as KEP ServerEX_SL. Access names are selected in the tag name dictionary for each tag
used in the application.

Scripting

In all control systems, it is essential to provide software interlocks to prevent human


errors. So the best method would be using “Window scripts” in InTouch. Window scripts
execute periodically when an InTouch window is open or one time when an InTouch
window is opened or closed.
Here the programming is using scripts, similar to any programming language. A
typical scripting example is shown in the figure below.
362ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 7.37 Wonderware development tool

Figure 7.38 Setting tag properties


›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ363

Figure 7.39 Scripting example

7.4.7 KEPServer

Kepware’s OPC Server KEPServerEX provides an easy and reliable way to connect to
Allen-Bradley PLC to HMI, SCADA, Historian, MES, ERP, and countless custom
applications. Here, you can use a KEP Server for communicating RSLOGIX to Wonderware
InTouch using the ETHERNET/IP protocol.
Be careful while specifying the tag names in KEPServer. The tag names and their
corresponding addresses should match as mentioned in the Wonderware InTouch
development.

Figure 7.40 KEPServer application: Main screen


364ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 7.41 Setting tag names and addresses in KEPServer

Running the final application

Once your PLC code is downloaded into the PLC & run from the RSLogix, then run
the KEPServer. Open the runtime application of Wonderware InTouch software and
open your GUI file. Always make sure that KEPSersver is running in the background
while you run the Wonderware InTouch application.

Applications

Such a control system can be very useful for industrial automation, in research
laboratories and big industries. The graphical interface makes it easy for the operator
to operate the switching and controlling operations. PLCs provides a very rugged solution
to control relays and RS-232 devices.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ365

7.4.8 HMI-PLC based Automation System

In industries, very often the problem arises of how to control the devices in an easy and
efficient manner. Implemented automation systems, though highly effective, are tough
to handle.
For such problems, beautiful and user-friendly screens, for the control, can be provided
using HMI (human machine interface) devices.
PLC: As we have learnt in this chapter, PLC is a device available for robust automation
solutions. A PLC has various digital inputs and outputs. Based on the inputs, a PLC
can be programmed via computer to provide necessary outputs.

Figure: 7.42 Delta PLC

Human machine interface (HMI) – background: HMI is the device used in the industrial
domain to provide an interactive user an interface for various control operations.
The ‘user interface’ is the space where interactions between humans and machines
occur.
This interaction allows effective operation and control of the machine from the human
end, while the machine simultaneously provides the feedback that aids the operators
in the decision-making process. The graphical user interface can be developed
and modified in the PC. Later this GUI is downloaded into the HMI to make it
function.
366ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 7.43 Industrial HMI

Programming the PLC: The software required to program a PLC comes with the PLC
itself and is different for different manufacturers. However, the coding procedure (Ladder
Programming) remains almost same.
In our system, we have used a DVP-14SS211R PLC. It is Delta Electronics’ second
generation of slimline industrial PLCs. It has 14 signal combinations of input and outputs.

Specifications for Delta PLC used:

Power : 20.4 to 28.8 V DC


Digital Inputs : 8 inputs, 24 V DC sink or source
Digital Outputs : 6 relay outputs
Output Rating : 1.5 A each output
Communication Port : RS-232 and RS-485, Modbus ASCII/RTU master
or slave
Program Capacity : 8 k steps
IO Points : Up to 238 via expansion modules
Software Up/Down Counters : Any input, up to 10 kHz on a single input
Software Quadrature Inputs : 2 - X4/X5 (5 kHz) and X6/X7 (5 kHz)
Hardware Up/Down Counters : 2 - X0 and X2, both 20 kHz
Hardware Quadrature Inputs : 2 - X0/X1 and X2/X3, both 10 kHz
Hardware Pulse/PWM Outputs : None
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ367

The following steps are followed to program such a PLC:


1. Install the WPLSoft in your PC. The software is provided with the PLC. Otherwise,
it can also be downloaded from www.delta.com.
2. Open the WPLSoft software. Those who have worked on Allen Bradley PLCs, it
is similar to RSLogix.
3. Start a new project. Select the appropriate PLC type. In our case, it is SV2.
4. A blank screen appears. Select the block and double click on it.
5. A text input box appears. Enter the required command to draw the blocks. For
example, to create an open contact input, type LD X1, where X1 refers to I
corresponding input signal of the PLC. Similarly, type OUT M1 to create an
output M1, where M1 is a register bit of PLC.
6. Develop the suitable Ladder program in this manner.

Downloading the Ladder program into PLC:

Downloading
USB
PC
HMI
WPL Soft

RS 232

RS 232

PLC

Fig 4 Connection Diagram

Figure 7.44 Connection Diagram

7. PC is connected to HMI via a USB cable. HMI is connected to PLC via RS-232
cable.
8. PC detects the presence of the PLC in the sequence of connections. Once the
ladder logic is complete, the code can be downloaded into the PLC.
368ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

X0 X1
YO

Y0

X0
SET YO

X1
RST YO

Figure 7.45 A sample PLC

Program description:

Ȋȱ In the above examples, when X0 goes from OFF to ON, Y0 will stay in ON state.
When X1 goes from OFF to ON, Y1 will remain in OFF state
Ȋȱ When X0 and X1 are enabled at the same time, it will be “Stop First”, that is, Y1
and the indicator will be O.
Programming the HMI: Usually, the HMI comes in conjunction with PLC, specific to
the manufacturer. The software used to program the HMI is also provided along. It can
be programmed appropriately to design beautiful graphical interface and proper
synchronization with PLC.
For our DVP-14SS211R Delta PLC, we have DOPSoft for HMI programming. The
following steps are followed to program an HMI:
1. Install the DOPSoft on your PC.
2. Start a new project.
3. Within a single project, you can draw different screens. These different screens
can be interlinked to each other.
4. The user interface can be built on these screens with tools from the palette
provided. Various options like push button and indicators are present to give
powerful GUI options.
5. Double clicking on the screen option enables us to set its properties. In the Write
Address option, specify the same address as of the PLC, like M2 or X1 or Y1.
6. Once entire GUI is prepared, download the code into HMI.
Connecting remote PC monitor to HMI: A remote PC can be synchronized with the
HMI in such a way that the same screen of HMI is displayed on the remote PC screen.
The remote PC is connected to HMI via Ethernet. Software like ‘em remote’ are available
which can be installed on your PC. It synchronizes with the HMI via Ethernet and makes
the screen of HMI visible on the PC monitor. There are advanced versions of em remote
which make the HMI to be synchronized with mobile screen as well.
›˜›Š––Š‹•Žȱ ˜’Œȱ ˜—›˜••Ž›œǰȱ  ȱ Š—ȱ Š›’Š‹•Žȱ ›ŽšžŽ—Œ¢ȱ ›’ŸŽœȱ ǻȱ Š—ȱ Ǽȳ369

Using multiple HMIs: Multiple HMIs as shown in Fig. 7.1 can be simultaneously used
to provide a user interface for control operations (at different locations probable).
HMIs are connected in succession via RS-484 cable. RS-485 works on the MODBUS
protocol.

REFERENCES

1. http://www.allaboutcircuits.com/vol_4/chpt_6/1.html
2. http://www.nfiautomation.org/FREE_Download/Technical%20Documents/PLC/
Basics_of_PLC_Programming.pdf
3. http://www.plcmanual.com/
4. http://www.tri-plc.com/trilogiintro.htm
5. http://www.ia.omron.com/data_pdf/guide/26/plc_tg_fi.pdf

REVIEW QUESTIONS

1. What is an HMI?
2. What is an RTU?
3. Where are input and output instructions located on a PLC ladder rung?
4. Why do PLC solutions have fewer wiring changes compared to relay logic when
changes are made to control system?
5. What steps are used to respond to a shock victim?
6. Identify and name the different types of PLC models that are available for
Allen-Bradley?
7. What limits the number of virtual input and output instructions in a PLC ladder
logic program?
8. List five advantages that PLCs offer over a relay logic solution?
9. What is the primary difference between a physical relay used in relay ladder
logic and the virtual relay used in a PLC ladder logic program?

ANSWERS

1. A human-machine interface (HMI) displays the process data that a human operator
needs to control a process. An HMI is usually linked to a SCADA system’s
databases and software programs, to provide trending, diagnostic data, and
management information. Such information includes scheduled maintenance
procedures, logistic information, detailed schematics for particular field sensors,
and expert-system troubleshooting guides.
370ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

2. A remote terminal unit (RTU) is a device or system that interfaces with other
equipment.
Typically, an RTU converts electrical signals from the equipment to digital values
that represent such items as the open/closed status of a switch or valve and
measurement values for pressure, flow, voltage, and current. By converting these
electrical signals and sending the digital values to the equipment, the RTU can
initiate control sequences such as opening or closing a switch or valve and setting
the speed of a pump.
C++ FOR SOFTWARE & FIRMWARE DESIGN:
8 LAY STRONG FOUNDATION FIRST

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Object-oriented programming concepts thoroughly using C++ through simple
examples one by one.

8.1 INTRODUCTION

A program is a sequence of instructions for a computer to execute. Every program is


written in some programming language. The C++ (pronounced ‘see-plus-plus’) language
is one of the newest and most powerful programming languages available. It allows the
programmer to write efficient, structured, object-oriented programs.
C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980s
and is based on the C language. The name is a pun:‘++’ is a syntactic construct used in
C (to increment a variable), and C++ is intended as an incremental improvement of C.
Most of C is a subset of C++, so that most C programs can be compiled (i.e. converted
into a series of low-level instructions that the computer can execute directly) using a
C++ compiler.
The prime purpose of C++ programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming
languages. The core of the pure object-oriented programming is to create an object, in
code, that has certain properties and methods. While designing C++ modules, we try to
see the whole world in the form of objects. For example, a car is an object which has
certain properties such as color, the number of doors, and the like. It also has certain
methods such as accelerate, brake, and so on.
In this project, we will focus on the concepts of class, object, inheritance, friend
function, etc. As the best of learning any programming language is making program
and practice so, we will take problem go through one by one to understand the concepts.

8.2 C++ ENVIRONMENT SETUP

You need the following two software available on your computer to execute and run
any C++ program.
372ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

8.2.1 Text Editor

This will be used to type your program. Examples of few editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example,
Notepad will be used on Windows and vim or vi can be used on Windows as well as
Linux, or UNIX.
The files you create with your editor are called source files and for C++ they typically
are named with the extension .cpp, .cp, or .c.
Before starting your programming, make sure you have one text editor in place and
you have enough experience to type your C++ program.

8.2.2 C++ Compiler

This is the actual C++ compiler, which will be used to compile your source code into
the final executable program.
Most C++ compilers don’t care what extension you give your source code, but if you
don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler,

8.3 COMPILE & EXECUTE C++ PROGRAM

Let us look at how to save the file, compile and run the program. Please follow the steps
given below:
Ȋȱ Open a text editor and add the code as above.
Ȋȱ Save the file as: hello.cpp
Ȋȱ Open a command prompt and go to the directory where you saved the file.
Ȋȱ Type ‘g++ hello.cpp’ and press enter to compile your code. If there are no errors
in your code, the command prompt will take you to the next line and would
generate a.out executable file.
Ȋȱ Now, type ’ a.out’ to run your program.

8.4 SOLVED PROBLEMS

Problem 1: Write a C++ program, which takes name and marks of three subjects as
input. Display name and marks on output screen also code this to calculate average
marks of person and display on the output screen.

Solution:

#include<iostream> // Header file which contains use cout/,cin


#include<conio.h> // Header file contians getch() command
using namespace std; //with help of using namespace we can
write cout instead of std::cout
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ373

int main() // start of main function


{
char str[40]; // create variable of char type of size 40
int m1,m2,m3,avg; // create integer type variable
cout<< "enter your name "; //enter name
cin>>str;
cout<< "enter three marks";
cin>> m1 >>m2 >> m3;
avg=(m1+m2+m3)/3; // this is to find avg. of m1,m2,m3
cout<< "your name is " <<str;
cout<<endl<<"and avarage marks is " <<avg; // display avg marks
of person
getch(); // To stop output window to disappear after execution
return 0; // return int as main function is of integer type
}

Output

Problem 2: Write a C++ program, which has a class of name student. Define age, income,
expense as private data member of class. Make public member function to display the
private data also use default constructor and constructor with arguments. Extend this
program to explain operator overloading and add data member of two different objects
by operator overloading and simple addition function.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class student // declaration of class whose object is student
{
private: // private data member can be accessedwithin the
class only
int age; // private data member
int income;
374ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

int expense;
public: // public these can be accessed from outside the class
void displayoutput() // public member function to display
age,income..
{
cout<<endl<< "age= " <<age <<"income= "
<<income <<"expense= " <<expense<<endl;
}
student() // default constructor is a member function that is
//- called automatically when an object is declared
{
cout<< "default constructor executed\n";
}
student(intag,intin,int ex) // constructor with argument
{
cout<< "entered into 3 argument constructor\n" ;
age=ag;
income=in;
expense=ex;
}
void addobjects(student a, student b, student c) // member
function to add private data member of
//-different object
{
age=a.age + b.age+c.age;
income=a.income+b.income+c.income;
expense=a.expense+b.expense+c.expense;
}
student operator + (student a) // operator overloading
{ // + is defined to add data member of student
student temp; // temp of type student is created
temp.age=age+a.age ;
temp.income=income+a.income;
temp.expense=expense+a.expense;
return(temp); // this will return temp after addition
//-of data member
}
student operator - (student a) // operator overloading for
subtraction
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ375

//- of data member of student


{
student temp;
temp.age=age-a.age ;
temp.income=income-a.income;
temp.expense=expense-a.expense;
return(temp);
}
};
int main() // main function
{
student a(50,1,1); //variable a of student type is generated
with initialization of
//-age=50,income=1,expense=1
student b(40,2,2),c(30,3,3); // b,c are also created
studentabc;
abc.addobjects(a,b,c); // calling member function addobject which
add
//-private data member of a,b and c variables
abc.displayoutput(); // this is called to display
abc=a+b+c; // another way of adding data member (operator
overloadin)
abc=a+a-b;
abc.displayoutput();
getch();
return 0;
}

Output
376ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Problem 3: Write a C++ program which has a class of name family. Define age, income,
expense as private data member of class. Make public member function to display the
private data also use default constructor and constructor with arguments. Use ‘this’
operator in the addition function. Extend this program to explain pointer to an object
and access a public function using this pointer.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class family
{
private:
int age;
int income;
int expense;
public:
void addall(family a,family b)
{
age=a.age + b.age;
income=a.income+b.income;
expense=a.expense+b.expense;
}
void showallvariables()
{
cout<<endl<< "age "<<age <<"income "<<income <<"expense
"<<expense <<endl;
}
family(inta,inti,int e) // constructor with arguments
{
age=a; // storing value of a as age
income=i;
expense=e;
}
family() // default constructor
{
}
family operator + (family second) // operator overloading
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ377

{
family temp;
temp.age=this->age+second.age; // another way of adding via this
pointer
//‘this’ pointer is a constant pointer that holds the memory
address of the current object
temp.income=this->income+second.income;
temp.expense=this->expense+second.expense;
return temp;
}
};
int main() // start of main function
{
family father(100,200,300); // object is generated with data
member age, income, expense
family mother(50,200,300);
family fathermother;
fathermother.addall(father,mother); // member function is called
for addition
fathermother.showallvariables(); // member function to display
fathermother=father+mother; // addition by operator overloading
fathermother.showallvariables(); // member function is called to
display
family *ptr; // ptr,pointer to an object is generated
ptr = &fathermother; // get address of fathermother
ptr->showallvariables(); // pointerptr point to member function
to display values
getch();
return 0;
}

Output
378ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Problem 4: Write a C++ program, which uses a function to add two numbers where
arguments of the function are passed by reference.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
int add(const int&b, int&c) // arguments are passed by reference
{ // b can't be change as it is const int type
return (b+c);
}
int add2(int *b, int *c)
{
return( *b + *c);
}
int main()
{
int a=1; // a is initialize by
int b=2;
int c1,c2;
c1=add(a,b);
c2=add2(&a,&b);
cout<<endl<<"c1= "<<c1;
cout<<endl<<"c2= "<<c2;
getch();
return 0;
}

Output
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ379

Problem 5: Write a C++ program, which has a class of name my class. Define name,
age, income as private data member of class. Make public member function to display
the private data. Also use the default constructor and constructor with arguments. Define
a C function pointer which also shows how a function inside a class is declared to a
pointer.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class myclass
{ private:
char *name;
staticint age;
int income;
public:
static void displayvalues()
{
cout<< "age = " <<age<<endl;
}
myclass() //default constructor
{
}
myclass(char *n , int a, int i) // constructor with argument
{
name=n;
income=i;
age=a;
}
};
voidfunc()
{
cout<< "hello\n";
}
int myclass:: age; //static variables inside class is referenced
outside -
void displayvalues(); //the class globally to be accessed by
outside functions
int main()
380ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

{
void (*funcptr)()=&func; // This is how a simple c function
pointer is declared
void (*class fnptr)()= &myclass::displayvalues; // This is how
a function inside
//-a class is declared to a ptr
myclass m("JOBY",100,100);
myclass *ptr=new myclass();//This is how a type myclass is
assigned to a class pointer
ptr=&m; // object of class myclass is assiged to ptr
myclass&p=m; //This is also another method of object m assigned
to a pointer
ptr ->displayvalues(); // executing a function of object m thru
ptr
m.displayvalues(); // direct execution of function thru object
m of myclass
myclass::displayvalues(); //This is another way of executing fn
as it is static
(*funcptr)(); // executing a function through simple c fn pointer
p.displayvalues(); // execting fn of object p
(*class fnptr)(); // executing fn. Display values through class fnptr
getch();
return 0;
}

Output

Problem 6: Write a C++ program having following requirements:


1. Defining member function outside class
2. Defining a variable ‘marks’ as public
3. Accessing marks through an object
4. Accessing member function and member variable through pointers
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ381

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class student
{
private:
int age;
char *name;
public:
int marks;
student(); //Default constructor
student (char *,int); // Constructor with argument
void displayall(); // function declaration
static void staticfn();
};
student::student() // defining the member function outside
the class
{
}
student::student(char *n,int a)
{
age=a;
name=n;
}
void hello()
{
cout<<endl<< "c hello"<<endl;
}
void student::displayall()
{
cout<< "name = "<<name;
cout<< " age=" <<age;
cout<< " marks= "<<marks;
}
void student::staticfn()
{
382ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

cout<< "hello static call ";


}
int main()
{
student a("mohit", 15);
a.marks=50;
cout<< "a.marks =" <<a.marks<<"\n";
// accessing pointer to object
student *fnptr= new student(); // pointer to object student
is generated
fnptr=&a; // get address of a
fnptr->displayall(); //
cout<<endl<<fnptr->marks<<"\n";
//below lines will demonstrate the calling memberfnc++ style
void (student::*memberfnptr)();
memberfnptr=&student::displayall;
(a.*memberfnptr)();
// below lines will demonstrate calling a public variable through
pointers
int (student::*marksptr)= & student::marks;
cout<<endl<<"marks through ptr=" << a.*marksptr<<"\n";
cout<< "....................................see the follwing
call\n ";
(fnptr->*memberfnptr)();
student::staticfn();
getch();
return 0;
}

Output
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ383

Problem 7: Write a C++ program, which has a class of name student. Define age, marks
as private data member of class. Make public member function to display the private
data. Also use the default constructor and constructor with arguments. Use pass by
reference in operator overloading of +.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class student
{
private:
int age;
int marks;
public:
student operator = (student &s)
{
age=s.age;
marks=s.marks;
return *this;
}
student& operator + (student &b) //pass by reference is
used in operator overloading
{
student temp;
temp.age=age+b.age;
temp.marks=marks+b.marks;
return temp;
}
void display()
{
cout<<endl<< "age = "<<age;
cout<<endl<< "marks = "<<marks<<endl;
}
student()
{
}
student(inta,int m)
384ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

{
age=a;
marks=m;
}
};
int& read()
{
int a=10;
return a;
}
int main()
{
student selvi(30,100); //object selvi is initialize with 30,100
student joby(23,100);
selvi.display(); //member function display is called to display
joby.display();
selvi=joby; //coping joby’s data to selvi’s data
selvi.display();
student selvijoby;
selvijoby=selvi+joby;
selvijoby.display();
int c;
c=read();
cout<< "c=" <<c<<endl ;
getch();
return 0;
}

Output
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ385

Problem 8: Write a C++ program, which has a class of name base class. Define age as
private data member of class and marks as public member of class. Make public member
function to display the private data. Also use the default constructor and constructor
with arguments. Make another class of name derived class which inherit public to base
class. Access the base class function from the object of derived class and from the object
of base class.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class baseclass
{
private:
int age;
public:
int marks;
baseclass();
voidprinthello()
{
cout<<endl<< "print hello from base class printhello function";
}
void display()
{
cout<<endl<< "age =" <<age << " marks= " <<marks <<endl;
}
};
baseclass::baseclass() //
defining default constructor outside the class
{
cout<<endl<< "printed from constructor of baseclass";
}
class derivedclass:publicbaseclass
{
public:
private:
};
386ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

int main()
{
derivedclassobj; // object of derived class is generated
obj.printhello(); //derived object accessing public member
function of baseclass
obj.marks=10;
obj.display();
int (baseclass::*ptr); // this 6 lines show that marks is part
of base class and derived class
ptr=&baseclass::marks;
cout<<endl<< obj.*ptr;
int (derivedclass::*ptr1);
ptr1=&derivedclass::marks;
cout<<endl<< obj.*ptr1;
cout<< ".................";
// the following program shows that the fnprinthello is part of
both class
void (derivedclass::*fnptr)();
fnptr = &derivedclass::printhello;
(obj.*fnptr)();
void (baseclass::*fnptr1)();
fnptr1 = &baseclass::printhello;
(obj.*fnptr1)();
getch();
return 0;
}

Output
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ387

Problem 9: Write a C++ program and make three classes – base class, drived class and
drived drived class – to explain inheritance also introduce the concept of destructor.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class baseclass
{
protected:
int age;
public:
int marks;
baseclass();
baseclass(int a)
{
cout<< "baseclass intconstructor executed";
age=a;
}
void printhello()
{
cout<<endl<< "print hello from baseclass printhello function";
}
void display()
{
cout<<endl<< "age =" <<age << " marks= " <<marks <<endl;
}
~baseclass() // baseclass destructor created
{
cout<< "baseclass destructor executed";
}
};
baseclass::baseclass()
{
cout<<endl<< "printed from default constructor of baseclass";
}
class derivedclass:publicbaseclass
{
388ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

public:
derivedclass() // default constructor of derived class
{
cout<<endl<< "printed form default constructor of derived class\n";
}
derivedclass(inta,intaddedtype)
{
cout<<addedtype;
cout<< "\nderived class int constructor executed";
}
~derivedclass() // destructor of derivedclass
{
cout<< "derived class destructor executed";
}
private:
};
class derivedderivedclass:publicderivedclass
{
public:
void print()
{
cout<<age;
}
};
int main()
{
derivedclass obj2(20,21); // object is initialize of derivedclass
getch();
return 0;
}

Output
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ389

Problem 10: Write a C++ program having two classes – father and son – where
the sons publically inherited to father class.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class father
{
private:
int age;
public:
father()
{
cout<<endl<< " I executed father constructor";
}
father(int a)
{
age=a;
}
int salary;
voidfatherfn()
{
cout<<endl<< " I executed father function";
}
~father()
{
cout<<endl<< " I executed from father destructor";
}
voiddisplayage()
{
cout<<endl<< "fathers initialized age =" <<age;
}
};
class child:public father
{
private:
int age;
390ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

public:
child()
{
cout<<endl<< " I executed from child constructor";
}
voidchildfn()
{
cout<< " I executed from child fn";
}
~child()
{
cout<<endl<< " I executed from child destructor";
}
child(int a):father(a)
{
age=a;
}
};
int main()
{
father j(30);
child c(20);
j.displayage();
c.displayage();
getch();
return 0;
}
Problem 11: Write a C++ program make three classes – base class, drive d class and
drived class – to explain inheritance. Also introduce the concept of destructor.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class father
{
private:
int age;
public:
father(int a)
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ391

{
age=a;
}
father()
{
cout<<endl<< " I execute from father constructor";
}
voiddisplayage()
{
cout<<endl<< "age displayed from father class= " <<age;
}
};
class child:public father
{
private:
char *name;
public:
child(char *n)
{
name=n;
cout<<endl<<name;
}
};
int main()
{
child f= "joby"; //first constructor of class father execute
f.displayage();
getch();
return 0;
}

Output
392ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Problem 12: Write a C++ program, which has a class of name father. Define age as
private data member of class. Make public member function to display the private data
also use default constructor and constructor with arguments. Make another class with
name son. Make son as protected to father. Show how public and protected data of son
become protected data of father.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class father
{
private:
int age;
protected:
void privatefn()
{
cout<< "private function"<<endl;
}
public:
void displayage()
{
cout<<endl<< "age = "<<age;
}
father(int a)
{
age=a;
}
father()
{
cout<<endl<< " I am in father def. constructor";
}
voidexecuteprivatefn()
{
father::privatefn();
}
};
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ393

class son:protected father


{
private:
public:
son(int a):father(a) // to excess father constructor
{
}
void executefromson()
{
father::privatefn();
}
void displayage()
{
father::displayage(); // to use definition as in father
}
};
int main()
{
son a(40);
a.displayage();
a.executefromson();
getch();
return 0;
}

Output

Problem 13: Write a C++ program, which has three classes with name grandfather, father
and son such that son is protected to father and father is protected to grandfather. Define
some private data member of class. Make public member function to display the private
data. Also use the default constructor and constructor with arguments.
394ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Solution:

#include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;
class grandfather
{
private:
int age;
protected:
void displayage()
{
cout<< "\nage printed from grandfather protected fn ="<<age;
}
public:
grandfather(int a)
{
age=a;
}
void showmeage()
{
grandfather::displayage();
}
};
class father:protected grandfather
{
private:
char name[30];
public:
father(inta,char *n):grandfather(a)
{
strcpy(name,n); //this will copy string in name
}
void showmeage()
{
grandfather::displayage();
cout<< "\nname = "<<name;
}
};
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ395

class son:protected father


{
private:
protected:
public:
son(int a, char *n ):father(a,n)
{
}
void showage()
{
father::showmeage() ;
}
};
int main()
{
grandfather a(60);
//a.displayage(); see it dosnt work as protected
a.showmeage(); // this works
father b(50,"joby");
b.father::showmeage(); //works as protected fn passed as private
son j(30,"alan");
j.son::showage();
getch();
return 0;
}

Output
396ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Problem 14:. Write a C++ program which contains two classes – grandfather and father.
Make father as publically inherited to grandfather. Also define some protected member
function in grandfather and access the function from outside.

Solution:

#include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;
class grandfather
{
private:
int age;
protected:
void displayage()
{
cout<< " \nage displayed from grandfather class = "<<age;
}
public:
grandfather(int a)
{
age=a;
}
voidshowage()
{
grandfather::displayage();
}
};
class father:public grandfather
{ private:
char name[20];
public:
father(int a ,char *n):grandfather(a)
{
strcpy(name,n);
}
voidshowage()
{
grandfather::displayage();
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ397

cout<< "\nname= " <<name;


}
};
int main()
{
grandfather j(60);
j.showage();
father f(30,"name");
f.grandfather::showage();
getch();
return 0;
}

Output

Problem 15: Write a C++ program which contains two classes – father and son. Make
son as publically inherited to father. Make a virtual function print() and access it through
pointer and through the object of son.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class father
{
private:
public:
virtual void print() //defining virtual function print()
{
cout<< "\nprint from inside father class";
}
};
398ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

class son:public father


{
private:
int age;
char *name;
public:
void print()
{
cout<< "\nprint from inside son class";
}
};
int main()
{
son s;
class father *fatherptr; // pointer is generated of type father
fatherptr=&s; //get address of son
fatherptr->print(); // accessing print() function from son
s.father::print(); // this is to access definition of print
function in father class
getch();
return 0;
}

Output

Problem 16: Write a C++ program, which contains three classes – father, son1 and son2.
Make both son1 and son2 as publically inherited to father. Make a virtual function print()
and access it through pointer and through the object of son1 and son2.

Solution:

#include <iostream>
#include <conio.h>
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ399

using namespace std;


class father
{
public:
virtual void print()
{
cout<<endl<< "\nprint from father class";
} };
class son1:public father
{
public:
void print()
{
cout<<endl<< "\nprint from son1 class";
}
};
class son2:public father
{
public:
void print()
{
cout<<endl<<"\nprint from son2 class";
}
};
int main()
{
son2 a;
a.print();
son1 b;
b.print();
class father *fatherptr;
fatherptr=&a; // getting address of a
fatherptr->print(); //excessing the print() function of class
son2
father f;
f.print(); //excessing the virtual function
getch();
return 0;
}
400ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Output

Problem 17: Write a C++ program, which contains two classes – father 1 and son. Make
son as publically inherited to father. Make a virtual function print (). Find the size of
class father 1 and son. In father, define public data of int type ba and virtual function
print (). In son, define public member function named print().

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class father1
{
public:
intba; // 4 byte
virtual void print()=0; // 4 byte
void a()
{
}
};
class son:public father1
{
public:
void print() //0 byte
{
cout<<endl<< "print from son\n";
}
};
int main()
{
son s;
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ401

s.print();
cout<<sizeof(son)<<endl; // this shows the size of class son in
byte
cout<<sizeof(father1); // this show the size of class father1
in byte
getch();
return 0;
}

Output

Problem 18: Write a C++ program containing a class, and name it student. Make an
in-line function, in public, of student for fast processing. Access this function from
outside of the class.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class student
{
private:
public:
inline void printme()
{
cout<< "print me\n";
}
};
int main()
{
int i;
student j;
402ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

for (i=0;i<10;i++)
j.printme();
getch();
return 0;
}

Output

Problem 19: Write a C++ program having two classes – subject and student. Also make
an in-line function in it. Generate a new class object of subject from within the student
class.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;

class subjects
{
private:
public:
voiddisplaymark()
{
cout<< "maths mark is " ;
}
};
class student // class student defination
{
private:
public:
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ403

inline void printme() // inline function for fast processing


{
cout<< "print me";
}
subjectsmaths; // object maths is added of class subject
};
int main()
{
student j;
j.maths.displaymark(); //
getch();
return 0;
}

Output

Problem 20: Write a C++ program to explain the concept of friend function. Make a
class of student having private data member a as integer data type. Access the private
data with the help of friend function.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;
class student
{
private :
int a;
public:
int b;
student(int a1)
{
a=a1;
}
404ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

friend void print(student s); // this function is used to


access private and protected data
friendint main();
};
void print(student s) // to access private data from
function outside the class
{
cout<<s.a<<"\n"; //output the a value
}
int main()
{
student b(40);
print(b);
cout<<b.a;
getch();
return 0;
}

Output

Problem 21: Write a program which generates a txt file. First write in the file and then
read from the file.

Solution:

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class file
{
private:
FILE *fp;
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ405

public:
file(char *name,char *type)
{
fp=fopen(name,type);
if (fp==NULL)
{
cout<< "Error opening";
exit(1);
}
}
~file()
{
fclose(fp);
}
FILE *getfp()
{
returnfp;
}
};
int main()
{
char filename[50];
charfiletype;
charch;
cout<< "Enter file name ";
cin>> filename;
cout<< "Enter file type ";
cin>>filetype;
file f(filename,&filetype);
do
{
cout<<ch;
ch=fgetc(f.getfp());
}
while (ch != EOF );
getch();
return 0;
}
406ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Problem 22: Write a program which generates a txt file. First write in the file and then
read from the file.

Solution.

#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
class file
{
private:
FILE *fp;
charch;
public:
file(char *name,char *mode)
{
fp=fopen(name,mode);
if (fp==NULL)
{
cout<< " Cannot open file" << name;
exit(1);
}
}
~file()
{
fclose(fp);
}
FILE *getfilepointer()
{
returnfp;
}
intfgetch()
{
ch=fgetc(fp);
returnch;
}
};
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ407

int main()
{
float k=1.5000007;
char filename[67],ch;
cout<< " ENTER FILE NAME ";
cin>> filename;
cout<< " ENTER FILE type ";
cin>>ch ;
cout.setf(ios::right);
cout.setf(ios::hex);
cout<<k;
cout<< "ENTER A CHAR";
cin.get(ch);
cin.putback(ch);
getch();
return 0;
}
Program 23: Write a program which generates a txt file. First write in the file and then
read from the file.

Solution:

#include <iostream>
#include <conio.h>
#include <fstream.h>
using namespace std;
int main()
{
char i='A';
int j=100;
float k=0.456;
ofstreamoutfile("joby.dat");
outfile<< i <<j <<k;
outfile.close();
ifstream in("joby.dat");
in>>i>>j>>k;
cout<< i<<endl<< j<<endl<<k;
getch();
return 0;
}
408ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

REFERENCES

1. http://www.doc.ic.ac.uk/~wjk/C++Intro
2. http://www.tutorialspoint.com/cplusplus
3. Schaum’s Programming with C++ by John R. Habbard, McGraw-Hill, 1996.
4. http://equestionanswers.com

REVIEW QUESTIONS

1. What is a constructor?
2. What is a destructor?
3. Can a destructor be overloaded?
4. What is the difference between a C structure and a C++ class?
5. What is ‘this’ pointer?
6. Can a virtual function call from a constructor/destructor work properly?
7. What is the size of a class having one or more virtual functions?

ANSWERS

1. A constructor is a class function with the same name as the class itself. It cannot
have a return type and may accept parameters. It is a callback or event for the
compiler (to call the constructor after memory allocation of the object is complete
via new operator).The responsibility of constructor function is to set initial values
for each object member to some default values before the object can be used.
2. A destructor is a special function member of a class that is automatically called
when an object about to be deleted by delete operator. It always has the same
name as the class preceded by a ‘tilde’ ~ symbol and has no return type. It is
used to free allocated memory used by an object. It takes no arguments.
3. A destructor can never be overloaded. An overloaded destructor would mean
that the destructor has taken arguments. Since a destructor does not take
arguments, it can never be overloaded.
4. C structures cannot have member function while C++ class always has. C structures
must have at least one data member in it to compile. C++ class can be empty. It
is possible to have a C++ class without member variables and member functions.
Static member variables are not allowed in C structures. C++ can have static
members.
5. The member functions of every object have access to a pointer named this, which
points to the object itself. When we call a member function, it comes into existence
with the values of this set to the address of the object for which it was called.
This pointer is the default hidden and implicit argument of any non-static member
function. Using a ‘this’ pointer any member function can find out the address of
ƸƸȱ ˜›ȱ ˜ Š›Žȱ ǭȱ ’›– Š›Žȱ Žœ’—DZȱ Š¢ȱ ›˜—ȱ ˜ž—Š’˜—ȱ ’›œȱ ȳ409

the object of which it is a member. It can also be used to access the data in the
object it points to.
6. Class vptr pointer is assigned to vtable after the constructor is called. Also,vptr
pointer is de-assigned from vtable before calling the destructor. Thus, virtual
function calling mechanism does not work in constructor and destructor of the
derived class.
7. The size of () class with no virtual function inside it, is equal to the sum of all
sizes of the member variable. For a class with one or more virtual functions the
sizeof() class is the sizeof() class plus the sizeof(void *). This extra size is for the
hidden member called vptr which is a pointer, points to vtable.
FIRMWARE PROGRAMMING USING
9 ARM MBED MICROCONTROLLER &
CLOUD COMPILER

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Why ARM mbed
Ȋȱ Hardware Development Kit (HDK) from mbed
Ȋȱ Software Development Kit (SDK) from ARM
Ȋȱ ARM mbed worldwide developer community
Ȋȱ Free online development tools
Ȋȱ LPC1768 based ARM mbed board
Ȋȱ To design an mbed microcontroller based interrupt learning system

9.1 WHY ARM MBED? USING LPC1768 FOR EMBEDDED SYSTEM


APPLICATIONS

ARM is a company which develops the embedded systems (systems having a software
embedded into a computer hardware) architecture NXP LPC1768, 2368 are ARM chips.
The company is also creating modern full stack operating systems, designed for ARM
cortex-M based MCUs, mbed (TM) which is an operating system for internet of things
(IOT) devices. IOT devices connect your daily-use things to the Internet. The OS includes
connectivity, security and device management functionality required by the IOT device.
(Refer: www.mbed.org)

9.2 INTRODUCTION

The mbed platform provides free software libraries, hardware designs, and online tools
for professional rapid prototyping of products based on ARM microcontrollers. The
platform includes a standards-based C/C++ software development kit (SDK), a
microcontroller hardware development kit (HDK) and supported development boards,
an online compiler, and online developer collaboration tools. They are also making the
future device called IOT device, the basic idea is to connect your all daily-use things
which contain processors with your e-mail that helps you in controlling these devices
even from a distance. The hardware and firmware development of IOT devices is given
in this chapter. Given below are some details of what you will get for basing your next
ARM microcontroller powered product on the mbed platform.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ411

9.3 HARDWARE DEVELOPMENT KIT (HDK)

The mbed HDK provides full microcontroller sub-system design files and firmware for
building development boards and custom products that benefit from the native support
of the mbed SDK. The HDK specifies all support components and circuits including the
mbed onboard interface design that provides simple USB drag-n-drop programming,
and CMSIS-DAP debug interface for the target microcontroller. Development boards
that are already based on the HDK are the quickest way to get started with the mbed
platform.

9.4 SOFTWARE DEVELOPMENT KIT (SDK)

The mbed SDK is an open source C/C++ microcontroller software platform relied upon
by tens of thousands of developers to build projects fast. The mbed SDK has been
designed to provide enough hardware abstraction to be intuitive and concise, yet
powerful enough to build complex projects. It is built on the low-level ARM CMSIS
APIs, allowing you to code down to the metal if needed.

9.5 WORLDWIDE DEVELOPER COMMUNITY

Using mbed means a huge shared context with other developers, and that means when
you have a question, there is less preamble, less explanation and less ‘time-reproducing’
issues, and more ‘time-getting’ answers. We are proud that this has helped us grow an
active and friendly community of skilled developers that are collectively helping to get
prototypes made even faster. But where it really gets interesting is the code. Our
developers are sharing thousands of open source repositories and building an extensive
cookbook of recipes that you can reuse to build your products. We have also made
contributing back easy. You can publish a library to mbed.org with a few clicks in the
IDE, and let others build on your hard work.

9.6 FREE ONLINE DEVELOPMENT TOOLS

The mbed compiler is a powerful online IDE that is free for use with hardware
implementing the mbed HDK, and tightly integrated with the mbed SDK and the
developer’s website. Under the hood, it relies on the industry standard ARM professional
C/C++ compiler, pre-configured and tested to generate a fast, efficient code without fuss.
Login anywhere to get instant access to your development environment, on Windows,
Mac or Linux. You can even work using tablets! While the mbed compiler provides you
your own private workspace, it is also fully integrated with the mbed.org (developer’s
website) so that you can easily import libraries and examples. If you choose to, publishing
your own code and collaborating with other mbed users are just a few clicks away. The
mbed compiler also supports full export to different toolchains, in the case your project
demands it as you go for production.
412ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

9.7 LPC1768 BASED ARM MBED BOARD: HARDWARE AND COMPILER


LIBRARY SUPPORT
9.7.1 LPC1768 features & terminologies

Ȋȱ 512 KB of on-chip FLASH


Ȋȱ 64 KB of on-chip SRAM (in 2 banks)
Ȋȱ 10/100 Ethernet MAC with external PHY interface
Ȋȱ USB Host/Device OTG controller and PHY. USB 2, full-speed
Ȋȱ I2S Digital Audio Interface
Ȋȱ 3 I2C interfaces
Ȋȱ 2 SSP interfaces
Ȋȱ 1 SPI interface
Ȋȱ 2 CAN interfaces
Ȋȱ 8-channel, 12-bit on-chip ADC
Ȋȱ 10-bit on-chip DAC
Ȋȱ PWM generation
Ȋȱ Quadrature Encoder Interface

GND OV 3.3-V Regulated Out VOUT


VIN 4.5 V - 14.0 V In 5.0-V USB Out VU
VB IF–
nR IF+
5 mosi RD–
6 miso SPI RD+
Ethernet
7 sck TD–
8 TD+
9 tx sda D–
Serial Serial USB
10 rx scl D+
11 mosi rd 30
Can
12 miso SPI td 29
13 tx sck sda tx 28
Serial FC Serial
14 rx scl rx 27
15 26
16 25
17 24
Analogin PwmOut
18 AnalogOut 23
19 22
20 21
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ413

Ȋȱ 4 GP Timers
Ȋȱ Ultra-low-power real-time-clock
Ȋȱ Up to 70 GPIO pins

Analog I/O

Analogin - Read the voltage applied to an analog input pin.


Analogout - Set the voltage of an analog output pin.

Digital I/O

DigitalIn - Configure and control a digital input pin.


DigitalOut - Configure and control a digital output pin.
Ȋȱ DigitalInOut - Bi-directional digital pins.
Ȋȱ Busin - Flexible way to read multiple DigitalIn pins as one value.
Ȋȱ BusOut - Flexible way to write multiple DigitalOut pins as one value.
Ȋȱ BusInOut - Flexible way to read/write multiple DigitalInOut pins as one value.
Ȋȱ PortIn - Fast way to read multiple DigitalIn pins as one value.
Ȋȱ PortOut - Fast way to write multiple DigitalOut pins as one value.
Ȋȱ PortInOut - Fast way to read/write multiple DigitalInOut pins as one value.
Ȋȱ PwmOut - Pulse-width modulated output.
Ȋȱ InterruptIn - Trigger an event when a digital input pin changes.

Timers

Ȋȱ Timer - Create, start, stop and read a timer.


Ȋȱ Timeout - Call a function after a specified delay.
Ȋȱ Ticker - Repeatedly call a function.
Ȋȱ Wait - Wait for a specified time.
Ȋȱ Time - Get and set the real-time clock.

Digital Interfaces

Ȋȱ Serial - Serial/UART bus.


Ȋȱ SPI - SPI bus master.
Ȋȱ SPISlave - SPI bus slave.
Ȋȱ I2C - I2C bus master.
Ȋȱ I2CSlave - I2C bus slave.
Ȋȱ CAN - Controller-area network bus.
414ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Real-time Operating System

Ȋȱ mbed RTOS

File System

Ȋȱ LocalFileSystem - Using the mbed disk as storage from within a program


Ȋȱ SDFileSystem - Using the mbed disk as storage from within a program

USB

Ȋȱ USBDevice - Using mbed as a USB device.


Ȋȱ USBMouse - Emulate a USB mouse with absolute or relative positioning.
Ȋȱ USBKeyboard - Emulate a USB keyboard, sending normal and media control keys.
Ȋȱ USBMouseKeyboard - Emulate a USB keyboard and a USB mouse with absolute
or relative positioning.
Ȋȱ USBHID - Communicate over a raw USBHID interface, perfect for driverless
communication with a custom PC program.
Ȋȱ USBMIDI - Send and receive MIDI messages to control and be controlled by PC
music sequencers, etc.
Ȋȱ USSerial - Create a virtual serial port over the USB port. Great to easily communicate
with a computer.
Ȋȱ USBAudio - Create a USB Audio device able to receive an audio stream from a
computer over USB.
Ȋȱ USBMSD - Generic class which implements the Mass Storage Device protocol to
access all kinds of block storage chips.
Ȋȱ USBHost - Using mbed to act as USB host.
Ȋȱ USBHostMouse - Receive events from a USB mouse.
Ȋȱ USBHostKeyboard - Read key code-modifier from a USB keyboard.
Ȋȱ USBHostMSD - Read-write a USB flash disk.
Ȋȱ USBHostSerial - Communicate with a virtual serial port.
Ȋȱ USBHostHub - You can plug several USB devices to an mbed using a USB hub.

Networking

Ȋȱ Ethernet - Ethernet network.


Ȋȱ Ethernet Interface.
Ȋȱ TCP/UDP socket API.
Ȋȱ TCP/IP protocols and APIs.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ415

9.7.2 Simple Hardware and Software: Reason to like mbed

Hardware setup: Here is the setup for connecting RFID sensor data to the Internet:

First, plug your mbed into the breadboard. Connect the ground (GND) pin with the
breadboard’s ground line and the USB power pin ((VU) to the power line.

RFID reader, Connect from Breadboard to Internet

Ȋȱ Connect the 5 V (Pin 11) and RST (Pin 2) pins to the power line.
Ȋȱ Connect the GND (Pin 1) and FS (Pin 7) pins to the ground line.
Ȋȱ Finally, connect the D0 (Pin 9) pin to the P14 pin of the mbed (which is a serial
input pin).

Ethernet socket

Ȋȱ Connect the socket’s Pin 3 to the mbed’s RD- pin


Ȋȱ Connect the socket’s Pin 1 to the mbed’s RD+ pin
Ȋȱ Connect the socket’s Pin 4 to the mbed’s TD- pin
Ȋȱ Connect the socket’s Pin 6 to the mbed’s TD+ pin

Then plug a network cable into the socket, and connect your mbed to your computer!
416ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

9.8 MBED AND PROGRAMMING INTERRUPTS


9.8.1 Introduction

This section is for beginners in the embedded world of microcontrollers. It may also
benefit more experienced programmers who are coming from the safety net of writing
code to run under an operating system like Windows, MAC OSX, Linux, FreeBSD and
so on.
It introduces the reader to the concept of ‘program context’, similar in many ways to
threads and processes. However, a context is much simpler but, judging from the number
of forum posts I see, often misunderstood. So, let’s move on step by step and get a good
grasp of what’s happening as we grow this example into a full-blown debacle of ‘how
not to do it’ (ending of course with examples of best practice to avoid these pitfalls). I’d
also like to say at this point that it may be a long section but by the time you get to the
end some of those evil printf()s will become saints again.

9.8.2 In the beginning

Let’s start with a new project in mbed compiler window. When you create a new project,
the mbed cloud compiler conveniently gives a main.cpp that’s already set and primed
to trip you up and give you a bad day. Here’s what it looks like:

Code:
#include “mbed.h”
DigitalOut myled(LED1);
int main() {
while(1) {
myled = 1;
wait(0.2);
myled = 0;
wait(0.2);
}
}
Tripping you up and having a bad day is a bit harsh. The one thing this main.cpp
does is twofold. Having just opened your parcel and popped all the bubbles from the
wrapper there’s nothing better than seeing your new toy perform. And along with the
simplicity of the main.cpp the hit is twofold, seeing it work and understanding how it
worked. It doesn’t get much simpler.
And as analogies go, there’s nothing worse than watching your children rip open
their Christmas presents only to look up and see your spouse mouthing the words “Did
you remember to buy the batteries?” If you did, fun is had by all, if you didn’t, you
know where the shed is.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ417

Instant gratification is great, and main.cpp does just that. So, without a do, let’s move
on and make a small modification to main.cpp, delete what you have and cut and paste
the following into it:

Code:

#include “mbed.h”
DigitalOut led1(LED1);
int main() {
while(1) {
led1 = 1;
wait(0.05);
led1 = 0;
wait(0.95);
}
}
There are two changes here. The first is we renamed myled to led1. I don’t know about
you, but all those LEDs are mine (or yours if you bought them!), I just like to know
which is which. The second change is how the led1 is flashed. We switch it on, wait
0.05 second, switch it off and wait 0.95 second then repeat, forever. The idea here is
while(1) {...} should be around 1 second long and the led1 flashes briefly to mark the
start of that second. Go ahead and compile/run it just to make sure all is working well.
What you should see is led1 flashing briefly once per second.
It’s at this point I’m going to introduce a simple diagram that represents what’s
happening right now with your mbed. Now I know it’s not a proper system context
diagram but none the less I’m going to call it a Context Diagram. Here it is:

So, it’s like a little graph. On the horizontal axis, we have time, in seconds, each time
led1 flashes. I haven’t given the vertical axis a name yet: more on that later. But the bar
at the bottom represents a context. In this case, it’s ‘user context’ and that’s code that
executes inside your while(1) {...} loop (including any functions and sub-functions that
you call from that loop). Also, the diagram only shows the first 9 seconds. All the code
I’m going to do is designed to mess things up within these 9 seconds. I’m going to
exaggerate things deliberately to make sure of that!
This is all about interrupts and making a mess of it: so let’s add our first interrupt
and, err, and make a mess of it. Here’s the code, delete your main.cpp contents and
paste this in.
418ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Code:

#include “mbed.h”
Timeout to1;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
void cb1(void) {
led2 = 1;
wait(3);
led2 = 0;
}
int main() {
to1.attach(&cb1, 2);
while(1) {
led1 = 1;
wait(0.05);
led1 = 0;
wait(0.95);
}
}
If you’ve just compiled and run that sample, you’ll have noticed that 2 seconds after
reset, Timeout to1 was triggered and the callback function cb1() was executed. This
function switched on led2, waited for 3 seconds, switched it off again and returned.
That bit should be fairly obvious. But what’s not so obvious is what happened to led1
while led2 was on. Go on, press reset again and watch led1. What happens?
Yes, it doesn’t flash! Now, let’s return to our context diagram and ‘spell it out’ with
a picture.

In the diagram above, I have grayed out the ‘square bullets’ at t = 2, 3 and 4 to show
that led1 didn’t flash. As you can see, when Timeout to1 triggered and cb1() was called,
your program’s context switch from user context to interrupt context. And along with
it, all the CPUs execution time was spent handling the Interrupt Service Routine (ISR).
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ419

As a result, your while(1) loop was suspended and didn’t execute. That’s why led1
stopped flashing.
Now, you might have just done all this and sitting there, thinking “well, it’s obvious”.
But the point is, it’s not as obvious as it may first appear. Sure it is here, but that’s
because I put a whacking wait(3) in the callback. The point I’m trying to make is,
spending too much time inside callbacks, which are usually in interrupt context, will
end up ruining your day. To some the penny about why printf() suddenly breaks your
program may well be dropping. We’ll come back to this later. Let’s move on and make
an even bigger mess just to really get home the nature of interrupts.
We’re now going to add a second interrupt callback called to2 and give it its own
LED and its own callback handler, cb2(). Here’s the code, as usual, wipe the contents
of your main.cpp and paste this in.

main.cpp

#include “mbed.h”
Timeout to1;
Timeout to2;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
void cb1(void) {
led2 = 1;
wait(3);
led2 = 0;
}
void cb2(void) {
led3 = 1;
wait(3);
led3 = 0;
}
int main() {
to1.attach(&cb1, 2);
to2.attach(&cb2, 3);
while(1) {
led1 = 1;
wait(0.05);
led1 = 0;
wait(0.95);
}
}
420ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Again we see things happening with the LEDs. As usual, while in interrupt context
led1 stopped flashing as before and it stopped for 6 seconds this time. But notice
something else here. Our new Timeout to2 was set to trigger three seconds after the
reset. That was one second after to1 triggered. So why didn’t led3 come on one second
after by led2? What actually happened is led2 came on for 3 seconds and then, when
it went off, led3 came on for 3 seconds! Let’s take a look at our new context diagram
and see what’s going on.

What should be obvious from this now is that interrupts don’t interrupt currently
executing interrupts. They ‘stack’. As can be seen from the diagram above, although to2
triggered at t = 3, execution of cb2() didn’t begin until t = 5 after cb1() completes and
returns.
So, after all, this exaggeration, it’s time to turn our attention to the real end programs
you write. This first and most obvious rule is:
Rule 1: Don’t use wait() in callbacks.
wait() is really there to use during the initialization phase of your program, the part
before entering the while(1) loop. There are other times it’s useful, but restrict them to
user context. Just don’t use wait() in an ISR. (Note, there does exist wait_us(), the wait
for a specified number of microseconds. This isn’t nearly as bad. Just use sensibly though
and avoid wait() and wait_ms()).
But now it’s time for rule number 2 and the less obvious one. Use printf() in a callback
at your peril. Why? It’s the Swiss army knife of debugging I hear you shout. Well, let’s
just disassemble printf(const char *format ...):
1. printf() doesn’t have a magic buffer. It has to malloc() one.
2. It has to guess at what size buffer to use, often twice the size of format, so that’s
a strlen() thrown in to get the length of format.
3. If it overruns that 2× buffer it has to remalloc(), memcpy() and continue.
4. Once it has something to send in steps the real killer hidden within printf(), it’s
putc(). printf() must loop over the buffer and putc() each character.
5. And with every malloc(), there’s a free() just to top it off.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ421

As said above, putc() is the hidden killer lurking to trip the unsuspecting developer.
Let’s take a look at what putc() does.
1. Is UART THRE register empty (read LSR to find out)
2. No? Wait until it is.
3. Yes, put the character/byte into THRE.
4. Go back to 1 above until all characters are sent.
Now, out of the box Serial, the baud rate is 9600 baud. So the above loop takes
approximately 1 ms for each loop, that’s each character in printf()’s malloc()’ed buffer.
It doesn’t take long to realize that the more you ask of printf() inside a callback, the
longer it takes for that callback to return and the longer you block the system.
Quite often a new programmer will find that it’s alright, initially. Their debugging
pops out on their terminal. But as their project grows and the system is expecting to do
more and more stuff, eventually you reach a tipping point where you are simply spending
too much time waiting inside a callback. As shown earlier, interrupts stack. So when
you return from a lengthy callback [thanks to printf()] you may well find yourself going
straight back into it again because another callback has been made with another printf()
in it too.
Which brings us to rule number 2.
Rule 2: Avoid printf() in callbacks. If you do use them for debugging a quick variable,
remember to remove that. And if your entire program relies on a printf() in a callback
by design rather than as a quick debug, think about redesigning your program to use
better IO techniques.

9.8.3 Mitigating the issues

So it’s time to look at ways of removing these unsightly warts from callbacks. As with
any programming language or system, there’s more than one way to do things. I’m just
going to show one example of my preferred way of dealing with this issue.
This technique is all about trying to keep yourself in user context for the longest
period possible and only leaving it for very brief ‘exceptions’.
In the above example, so far what I was trying to do is given below (this is my
specification).
1. led1: flash brief one per second, EVERY second.
2. led2: On at t = 2 and off at t = 5
3. led3: On at t = 3 and off at t = 6
Let’s look at how I would approach this problem, here’s the code.

Main.cpp

#include “mbed.h”
Timeout to1;
Timeout to2;
422ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

DigitalOut led1(LED1);
DigitalOut to1_led(LED2);
DigitalOut to2_led(LED3);
bool to1triggered = false;
bool to2triggered = false;
void cb1(void) {
to1triggered = true;
}

void to1handle(void) {
if (to1_led == 0) {
to1_led = 1;
to1.detach();
to1.attach(&cb1, 3);
}
else {
to1_led = 0;
to1.detach();
}
}
void cb2(void) {
to2triggered = true;
}
void to2handle(void) {
if (to2_led == 0) {
to2_led = 1;
to2.detach();
to2.attach(&cb2, 3);
}
else {
to2_led = 0;
to2.detach();
}
}
int main() {
to1.attach(&cb1, 2);
to2.attach(&cb2, 3);
while(1) {
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ423

if (to1triggered) {
to1triggered = false;
to1handle();
}

if (to2triggered) {
to2triggered = false;
to2handle();
}

led1 = 1;
wait(0.05);
led1 = 0;
wait(0.95);
}
}
Paste that into your compiler and run it. You’ll see it does work. Keen-eyed observers
will, however, have noticed the huge bug in this program. We’ll return to that shortly.
I left it like as it is, and did not want to add too much in one go.
So, what’s new here? Mainly the introduction of two global bool variabes to1triggered
and to2triggered. The main point of these is that when a callback is made we set these
to true. We don’t do anything else. That’s fast, very fast. Compared to the 9 seconds of
user context we have, these callbacks are pretty much instant requiring just a few
microseconds at most.
Now, in our user context while(1) loop we test these bools. They are effectively acting
as flags to your main program to tell it that an event occurred that must be handled.
So we do: we have functions dedicated to handling them. Notice that each of these
reschedules a new future callback based on whether the LED is on or not. If the LED
is off, switch it on and reschedule a new timeout to switch it off later.
Let’s have a look at the context diagram for this program:
424ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

This diagram isn’t to scale. If it were you wouldn’t be able to see to1/cb1 and to2/cb2,
a pixel width of your screen is far too wide to represent the real time spent in the
callbacks. Likewise, if we scaled to the width they are shown the t = 9 would be by the
bus stop somewhere down the road, far too wide for your monitor!
The important point here is the amount of available time you have in user context.
You could be using it for more useful things like calculating PI or searching for
extraterrestrial life with SETI. The point is, it’s your time. Those LEDs will happily get
on with their task while you get on with other tasks.
So, let’s come back to that bug I mentioned earlier. It’s here.

Code:
led1 = 1;
wait(0.05);
led1 = 0;
wait(0.95);
The only reason this program works is that I was careful to line up the event times
with each other. Change the values of those wait()s and it’ll all fall apart. So the answer
is, yes! More timers. Have you noticed the mbed library says you can have as many as
you want? Useful! Shortly I’ll show you how to fix this. But first, as always, a word of
advice. This sort of technique is useful for event-driven systems. If your event handlers
themselves start to get too long, then you can run into trouble. For example, if you call
a function to go find another decimal place of PI chances are to1triggered and to2triggered
won’t be getting tested for true anytime soon. So think on when designing your program
where you’ll be spending time, where you need to service events, etc.
Now, let’s move on to the final example. This example handles the specification for
the LEDs we outlined earlier and lets you calculate PI without a care. Both will live in
harmony. What’s more, we extend led2 and led3 so that they repeat their sequence
rather than just coming on once and never again.

Main.cpp
#include “mbed.h”
Ticker tled1on;
Timeout tled1off;
Timeout to1;
Timeout to2;
DigitalOut led1(LED1);
DigitalOut to1_led(LED2);
DigitalOut to2_led(LED3);
void cb1(void) {
if (to1_led == 0) {
to1_led = 1;
}
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ425

else {
to1_led = 0;
}
// Reschedule a new event.
to1.detach();
to1.attach(&cb1, 3);
}
void cb2(void) {
if (to2_led == 0) {
to2_led = 1;
}
else {
to2_led = 0;
}
// Reschedule a new event.
to2.detach();
to2.attach(&cb2, 3);
}
void tled1off_cb(void) {
led1 = 0;
}
void tled1on_cb(void) {
led1 = 1;
tled1off.detach();
tled1off.attach(&tled1off_cb, 0.05);
}

int main() {
led1 = 1;
tled1off.attach(&tled1on_cb, 0.05);
tled1on.attach(&tled1on_cb, 1);
to1.attach(&cb1, 2);
to2.attach(&cb2, 3);
while(1) {
// Calculate PI here as we have so much time :)
// It’s like riding a bike with no hands, who’s
// steering?! :)
}
}
426ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

There is one point to note. The LPC17xx manual refers to ‘modes’ and there are two
of them, Thread Mode and Handler Mode. The Thread Mode is user context and Handler
Mode is interrupt context. I just prefer the notion of ‘executing in a context’. So if you
are reading the manual, then you’ll know what thread and handler modes are.
And lastly, not covered here is interrupt priorities. The LPC1768 does allow for
interrupts to take priority which does, in fact, allow one interrupt to preempt a currently
executing ISR rather than stack amongst other tricks.

9.9 EXPERIMENTS/PROJECTS USING ARM MBED 1768 40-PIN DIP

Following is a list of simple examples (Firmware in C++) which will make all your
fundamentals clear about embedded development. I hope you can make a business
case out of it at the end of the day.

9.9.1 Experiment 1: Test Digital Output

LED1, LED2, LED3, LED4 are on the board.


Step 1. Connect LED2 to the port of digital out.
Step 2. Now write a program to know the value of digital output pin.
Program:
#include “mbed.h”
// This is a program by JA
Serial pc (USBTX, USBRX); // tx, rx
Digital Out myled1 (LED2);
int main( ) {
Unsigned int my data=0;
while(1) {
myled1 = 1;
wait(.3);
myled1 = 0;
wait(.3);
mydata++;
pc.printf(“%u \n”,mydata);
pc.printf(“the pin is %d\n”,myled1.read());
}
}
Thus, the above program shows the the value of digital output pin. Think! How can
u make LED1 glowing? At what instant of time (gap of time) it will glow? What will
be the output of the above program?
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ427

9.9.2 Experiment 2: Test Digital Input


Step 1. Connect LED1 to Pin 6
Step 2. Now write a program to read the value of a pin number.
#include “mbed.h”
series pc(USBTX,USBRX);//tx,rx
DigitalIn enable(p5);
DigitalOut led(LED1);
int main() {
while(1) {
if(enable) {
led = !led;
}
wait(0.25);
pc.printf(“LED1 enabled”,LED1.Read)
}
}
The above program is used to read the digital i/p of a pin. Think!! What all pins are
used as DigitalIn? Why LED1 is glowing? Can you write a program using Pin 5 and
Pin 6 both connected as DigitalIN and DigitalOUT? Then what will be the output?
#include “mbed.h”
// this is a program by JA
Serial pc(USBTX, USBRX); // tx, rx
DigitalOut myoutput(p5);
DigitalIn myinput(p6);
int main() {
while(1) {
wait(1);
myoutput = 1 ;
if (myinput == 1)
pc.printf(“input is 1”);
else
pc.printf(“in put is 0”);
wait(1);
myoutput = 0 ;
if (myinput == 1)
pc.printf(“in put is 1”);
else
pc.printf(“in put is 0”);
}
}

}
428ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

9.9.3 Experiment 3: Test Analog Input

Step 1. Connect a voltage of 1 V to Pin 20 of ADC.


Step 2. Now write a program to read this value
#include “mbed.h”
Serial pc(USBTX, USBRX); // tx, rx
AnalogIn ain(p20);
DigitalOut led(LED1);
int main() {
while (1){
wait(2);
pc.printf(“volatge read is %f\n”, ain.read()*3.3);
if(ain > 0.3) {
led = 1;
} else {
led = 0;
}
}
}
The above program displays the voltage on a serial terminal. Think!! Why is it reading
3.3 V when Pin 20 and Pin 40 are connected? Can you make the LED1 glowing? How?

9.9.4 Experiment 4: Test Analog Output

Step 1. Connect a voltage of 1 V to Pin 20 of ADC.


Step 2. Now write a program to read this value.
#include “mbed.h”
Serial pc(USBTX, USBRX); // tx, rx
AnalogOut signal(p18);
int main() {
while(1) {
for(float i=0.0; i<1.0; i+=0.1) {
signal = i;
wait(1);
pc.printf(“DAC output is %f\n”,i);
}
}
}
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ429

The above program displays the voltage on a serial terminal. Think!! How many bits
DAC is this? Why is this voltage increasing by 0.1 V? Can you modify the above program
to read back analog input from the analog output as below?
#include “mbed.h”
Serial pc(USBTX, USBRX); // tx, rx
AnalogIn ain(p20);
DigitalOut led(LED1);
AnalogOut signal(p18);
int main() {
while(1) {
for(float i=0.0; i<1.0; i+=0.1) {
signal = i;
wait(1);
pc.printf(“DAC output is %f\n”,i);
pc.printf(“volatge read is %f\n”, ain.read());
if(ain > 0.3)
led = 1;
else
led = 0;
}
}
}

Output

9.9.5 Experiment 5: DigitalInOut

Step 1. Connect an LED to Pin 5.


Step 2. Now write the following program to write and read this value.
#include “mbed.h”
Serial pc(USBTX, USBRX); // tx, rx
430ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

DigitalInOut pin(p5);
int main() {
while(1)
{
pin.output(); // make pin5 as output pin
pin = 1; // make pin5 high
pc.printf(“ The p5 pin status = %d”,pin.read());
wait(.500);
pin.input(); // change configuration of pin5 as input
wait(.500);
pc.printf(“ The p5 pin status = %d”,pin.read());
}
}
Think! Why is this LED glowing?

9.9.6 Experiment 6: BUSOUT

Step 1. Identify LED1, LED2, LED3, LED4.


Step 2. Now write the following program to write and read this value.
#include “mbed.h”
BusOut myleds(LED1, LED2, LED3, LED4);
int main() {
while(1) {
for(int i=0; i<16; i++) {
myleds = i;
wait(0.25);
}
}
}
Think! In which manner are the LEDs glowing?

9.9.7 Experiment 7: PWM

Step 1. Identify LED1, LED2, LED3, LED4.


Step 2. Now write the following program to write and read this value.
#include “mbed.h”
PwmOut led(LED1);
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ431

int main() {
while(1) {
for(float p = 0.0f; p < 1.0f; p += 0.1f) {
led = p;
wait(0.1);
}
}
}
Think!!Why is this LED brightness varying? Try this also, what do you expect the result?
#include “mbed.h”
PwmOut led(LED1);
PwmOut led2(LED2);
PwmOut led3(LED3);
PwmOut led4(LED4);
int main() {
while(1) {
for(float p = 0.0f; p < 1.0f; p += 0.01f) {
led = p;
led2 = p;
led3 = p;
led4 = p;
wait(0.1);
}
}
}

9.9.8 Experiment 8: SERIAL

This program will print next character against the character what you typed in from
keyboard, using send to USB converter.
#include “mbed.h”
Serial pc(USBTX, USBRX); // tx, rx
int main() {
pc.printf(“Hello World!”);
while(1) {
pc.putc(pc.getc() + 1);
}
}
Think! How is the character on the screen different?
432ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

9.10 PROGRAM ANALOG INPUT AND OUTPUT USING 32-BIT ARM


MBED MICROCONTROLLER LPC1768
9.10.1 Quantization of Analog Data

Most of the microcontrollers come with in-built analog section to interface with time
varying analog signals. Analog value is converted to equivalent numbers (quantization),
for example, from microphone or temperature sensor to digital data. Finally, these
microcontrollers are capable of converting digital signals back to analog form, for
example, if driving a loudspeaker or dc motor

9.10.2 Concepts of Analog-to-Digital Conversion

An analog-to-digital convertor (ADC) is an electronic circuit whose digital output is


proportional to its analog input. Effectively it “measures” the input voltage, and gives
a binary output number proportional to its size .The input range of the ADC is usually
determined by the value of a voltage reference, Voltage reference is usually created by
a separate reference chip or circuitry.

ADC conversion

The ADC conversion is started by a digital input pulse, called here start of conversion
(SOC )
It takes finite time for any ADC to convert after SOC, and the ADC signals with the
end of conversion( EOC) line when the conversion is complete
The resulting data can then be enabled onto a data bus using the output enable(OE)
line.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ433

The following figure shows the `staircase’ conversion transfer curve visible in a 3-bit
ADC.

Resolution and quantisation

By converting an analog signal to digital, we are effectively approximating it, as any


one digital output value has to represent a very small range of analog input voltages,
i.e. the width of any of the steps on the “staircase” n. If we want to convert an analog
signal that has a range 0-3.3 V to an 8-bit digital signal, then there are 256 (i.e., 28)
distinct output values. Each step has a width of 3.3/256 = 12.89 mV, and the worst case
quantisation error is 6.45 mV. The mbed uses a 12-bit ADC. This leads to a step width
of 3.3/212, or 0.8 mV; the worst case quantisation error is therefore 0.4 mV.

Sampling frequency

When converting an analog signal to digital, we repeatedly take a ‘sample’ and quantise
this to the accuracy defined by the resolution of our ADC. The more samples taken,
the more accurate the digital data will be. Samples are normally taken at fixed periods
(i.e., every 0.2ms) and define the rate of sampling by the sampling frequency (the number
of samples taken per second). The sample frequency needs to be chosen with respect
to the rate of which the sampled data is changing. If the sample frequency is too low
then rapid changes in the analog signal may not be obvious in the resulting digital data.
For this reason the Nyquist sampling criterion states that the sampling frequency must
be at least double that of the highest frequency of interest.
434ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Digital sampling of an analog signal


V

time

samples

Analog inputs on the mbed


The mbed has up to six analog inputs, on pins 15 to 20

Analog-to-digital conversion on the mbed:


The library functions are shown in the table below
AnalogIn An analog input, used for reading the voltage on a pin
Functions Usage
AnalogIn Create an AnalogIn, connected to the specified pin
read Read the input voltage, represented as a float in the range [0.0, 1.0]
read_u16 Read the input voltage, represented as an unsigned short in the range [0x0, 0xFFFF]
operator float operator float, an operator shorthand for read()
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ435

Reading and logging data from analog inputs


Ȋȱ Experiment 1: Attach a potentiometer output to mbed pin 20.
» Start a new mbed project on free MBED online compiler and enter the code
below.
» This code will continuously display the analog input value when used with
a host PC terminal application.The PC terminal application can be tested by
installing windows serial drivers for mbed.
//Reads input through the ADC, and transfers to PC terminal
#include " mbed.h "
Serial pc(USBTX, USBRX);
AnalogIn Ain(p20);
float ADCdata ;
int main() {
pc.printf ( "ADC Data Values... \ n \ r");
while (1) {
ADCdata = Ain;
pc.printf ( "%f \ n \ r",ADCdata ) ;
wait (0.5);
}
}

Gnd Vout
Vin Vu
10k Vb IF–
nR IF+
5 RD–
mbed Microcontroller

6 RD+
7 TD–
8 TD+
9 D–
10 D+
11 30
12 29
13 28
14 27
15 26
16 25
17 24
18 23
19 22
20 21
(power is taken from USB connection)

Reading data from analog inputs

Ȋȱ Experiment 2: Using the four onboardmbed LEDs, write a program that will use
a potentiometer input on pin 20 to continuously control how many LEDs are on.
Use the following chart to define the LED control:
436ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Analog input value x LED1 LED2 LED3 LED4


x <= 0.2 0 0 0 0
0.2 < x <= 0.4 1 0 0 0
0.4 < x <= 0.6 1 1 0 0
0.6 < x <= 0.8 1 1 1 0
0.8 < x <= 1.0 1 1 1 1

Concepts of digital-to-analogconversion or DAC

We can represent the digital-to-analog convertor (DAC) as a block diagram with a digital
input, D, and an analog output, vo. The output range of the DAC, vr, is the difference
between the maximum and minimum output voltages, i.e.,
vr = vmax – vmin
The particular output range is usually defined by a fixed voltage reference supplied
to the DAC. Digital control lines allow a microcontroller to set up and communicate
with the DAC.

Conversion
Voltage Reference For each digital
+ value input to the
DAC, there is a
corresponding
Digital to + analog output
D Analog V0 value given by
Converter –
(n-bit Digital
input) (Analog
D
Output) v0 = v
2n r

The mbed’s LPC1768 chip has a 10-bit DAC (i.e., n=10). The mbed uses its own 3.3 V
power supply as voltage reference.There will therefore be 2n steps in the mbed DAC
output characteristic, i.e., 1024 . The step size, or resolution, is therefore be 3.3/1024, i.e.
3.2 mV per bit
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ437

Digital-to-analog conversion on the mbed:


The mbed has a single analog output on pin 18
The library functions are shown in the table below.
AnalogOut An analog output, used for setting the voltage on a pin
Functions Usage
AnalogOut Create an AnalogOut connected to the specified pin
write Set the output voltage, specified as a percentage (float)
write_u16 Set the output voltage, represented as an unsigned short in the range [0x0, 0xFFFF]
read Return the current output voltage setting, measured as a percentage (float)
operator= An operator shorthand for write()
operator An operator shorthand for read()
float()

Analog output with the mbed:


The mbed analog output on pin 18 is configured by the following declaration:
AnalogOut Aout (p 18 ) ;
By default, the analog object takes a floating point number between 0.0 and 1.0 and
outputs this to pin 18 . The actual output voltage on pin 18 is between 0V and 3.3V, so
the floating point number, that is, output as a voltage is scaled by a factor of 3.3
Ȋȱ Experiment 3: compile the program shown below and, using an oscilloscope,
familiarise analog output.
#include " mbed.h "
int main() {
AnalogOut Aout ( p18);
while(1) {
Aout =0.25 ; // 0.25*3.3V = 0.825V
wait(1);
Aout =0.5 ; // 0.5*3.3V = 1.65V
wait(1);
Aout =0.75 ; // 0.75*3.3V = 2.475V
wait(1);
}
}
output
Ȋȱ Experiment 4: Now make a sawtooth wave and view it on an oscilloscope. Create
a new program and enter the following
//S awtooth waveform on DAC output to view on oscillosc ope
#include "m bed.h"
AnalogOut Aout( p 18);
438ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

float i ;
int main() {
while(1)
{
for (i = 0; i<1;i= i+0.1)
{
Aout= i ;
wait(0.001);
}
}
}

9.11 PROGRAM DIGITAL INPUT AND OUTPUT USING


ARM MBED – 32-BIT MICROCONTROLLER

Digital inputs are zeros or ones read through an input port.


Digital output is a zero or one generated from an output port.
The mbed uses a power rail of 3.3 volts - 0 volt indicating ‘off’ and 3.3 volts indicates
‘on’.
A number of terms are used interchangeably to describe on and off in digital systems:
0V 3.3V
Open Closed
Off On
Low High
Clear Set
logic 0 logic 1
False True
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ439

Note: terms ‘logic 0’ and ‘logic 1’ may be simply referred to as ‘0’ and ‘1’.
On the mbed, the four on-board LEDs are digital outputs which have been specially
configured to operate with no extra wires or connections needed.
The mbed also has 26 digital IO pins (pins 5-30) which can be configured as inputs
or outputs.

The available library functions are shown in the table below.


DigitalOut A digital output, used for setting the state of a pin
Functions Usage
DigitalOut Create a DigitalOut connected to the specified pin
write Set the output, specified as 0 or 1 (int)
read Return the output setting, represented as 0 or 1 (int)
operator= A shorthand for write
operator int() A shorthand for read

The digital IO pins are configured by defining them at the start of the program code.
Each digital IO is given a name and associated pin, for example:
DigitalOut myname1(p5);
DigitalOut myname2(p6);
DigitalOut myname3(p7);
etc…
The DigitalOut interface can be used to set the state of the output pin, and also read
back the current output state.
Set the DigitalOut to 0 to turn it off, or 1 to turn it on.
Using LEDs on the mbed pins:
Connect the mbed to a breadboard and attach a red LED to pin 5 and a green LED
to pin 6.
440ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Remember to attach the positive side of the led (the side with the longer leg) to the
mbed. The negative side should be connected to ground.

The mbed has a common ground on pin 1.


Ȋȱ Experiment 1: Create a new program for the external LED project. Modify the
default main.cpp code to become the following:
#include " mbed.h "
DigitalOut redled ( p5);
DigitalOut greenled ( p6);
int main() {
while(1) {
redled = 1 ;
greenled = 0 ;
wait(0.2);
redled = 0 ;
greenled = 1 ;
wait(0.2);
}
}
Compile, download and run the code on the mbed.
Look at the example program and identify the key C programming elements as
follows:
Ȋȱ The mbed.h library file is linked to by the `#include’ statement.
Ȋȱ DigitalOut objects are defined with a name and a chosen mbed pin.
Ȋȱ The main program function exists inside `int main() { ... program... }‘.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ441

Ȋȱ An infinite loop is implemented by the while(1) statement, so that the program


continuously loops forever, allowing the led to flash continuously.
Ȋȱ Digital outputs are controlled simply by setting the relevant objects equal to 0 or
1.
Ȋȱ The mbed wait() function is used for timing control.
Digital inputs on the mbed :
Digital inputs values can be read.
As with digital outputs, the same 26 pins (pins 5-30) can be configured as digital
inputs, as follows:
DigitalIn myname1(p5);
DigitalIn myname2(p6);
DigitalIn myname3(p7);
The DigitalIn Interface determines the current logical state of the chosen input pin,
e.g., logic ‘0’ or logic ‘1’.
Zero volts on a digital input pin returns a logical 0, whereas 3.3 volts returns a logic 1.
Digital inputs on the mbed:
The available library functions are shown in the table below.
DigitalIn A digital input, used for reading the state of a pin
Functions Usage
DigitalIn Create a DigitalIn connected to the specified pin
read Read the input, represented as 0 or 1 (int)
mode Set the input pin mode
operator A shorthand for read
int()

Connecting switches to the mbed:


A simple mechanical switch to set a digital input pin either high (‘1’) or low (‘0’) by
connecting it to switch between the 3.3V and GND rails.
442ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

To the setup included in the previous example, add a mechanical switch output to
Pin 7.
Connect the switch inputs to 0V (GND, pin1) and 3.3V (Vout, Pin 40).
Ȋȱ Experiment 2: Create a new program for the LED switch project. Modify the default
main.cpp code as shown.
When two forward slash symbols (//) are used, the compiler ignores any proceeding
text, so we can use this to write useful comments.
#include "mbed.h"
DigitalOut redled(p5);
DigitalOut greenled(p6);
DigitalIn switchinput(p7);
int main() {
while(1) {
if (switchinput==1)
{ greenled = 0; //green led is off
redled = 1; // flash red led
wait(0.2);
redled = 0;
wait(0.2); }
else if (switchinput==0)
{ redled = 0; //red led is off
greenled = 1; // flash green led
wait(0.2);
greenled = 0;
wait(0.2);
}
}
}

Compile, download and run the code on the mbed.


Look at the code, the if (switchinput==1) statement allows the code to operate in two
different ways, dependent on the value of the digital input (i.e. the mechanical switch
position).
If the switch gives a value of 1, the green LED is set to zero (off) and the red LED is
programmed to flash. If the digital input is low (0), we see the roles of the LEDs reversed.
Microcontroller memory and programming using 32-bit ARM MBED
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ443

9.12 MEMORY FUNCTION TYPES

Microprocessors use memory for holding the program code (program memory) and the
working data (data memory) in an embedded system.
When the processor is powered up the program data needs to be there and ready.
Non-volatile memory is generally required for program memory. There is often no need
to retain data when the product is switched off, therefore volatile memory is traditionally
preferred for data memory .With C/C++ we can open files, read and write data and also
scan through files to specific locations, even searching for particular types of data. We
can store data in files (as chars) or we can store words and strings (as character arrays).
We can save data files to a specific area of flash memory installed on the mbed. This
memory is a page-erase data flash IC which is external to the LPC1768 microprocessor.
When interfacing the mbed data memory, we use the standard C/C++ commands as
defined by the C Standard Input and Output Library (stdio.h).

Function Format Summary Action


fopen FILE * fopen( const char * filename, opens the file of name filename
const char * mode);
fclose intfclose( FILE * stream ); closes a file
fgetc intfgetc( FILE * stream ); gets a character from a stream
fgets char * fgets( char * str, intnum, FILE * gets a string from a stream
stream );
fputc intfputc( int character, FILE * stream ); writes a character to a stream
fputs intfputs( const char * str, FILE * stream writes a string to a stream
);
fseek intfseek( FILE * stream, long int offset, moves file pointer to specified
int origin ); location

A summary of useful stdio functions for implementing file access on the mbed.
str - An array containing the null-terminated sequence of characters to be written.
stream - Pointer to a FILE object that identifies the stream where the string is to be
written.
The compiler must be told where to store data files. This can be done by using the
mbed ‘LocalFileSystem’ declaration:
LocalFileSystem local("local");
This allows programs to read and write files on the same disk drive that is used to
program the mbed microcontroller.
Once created, the standard C file access functions are used to open, read and write
files.
We can open a file with the following command:
FILE* pFile = fopen ( "/local/ datafile.txt","w ");
This assigns a pointer with a shorthand name (pFile) to the file at the specific location
given in the fopen statement.
444ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

We also tell the compiler whether we want read or write access to the file. This is
done by the “w” syntax. If we put “r” this would make the file open as read only.
Note also that if the file doesn’t already exist, the fopen command will automatically
create the file in the specified location.
When we have finished using a file for reading or writing it is good practice to close
the file, for example:
fclose ( pFile ) ;

Writing data to a file

If we are looking to store numerical data we can do this in a simple way by storing
individual 8-bit data values (chars). The fputc command allows this, as follows:
char write_var =0 x0F;
fputc ( write_var , pFile ) ;
This stores the variable write_var to the data file.

Reading data from a file

We can read data from a file to a variable as follows:


read_var = fgetc ( pFile ) ;
Using the stdio.h commands it is also possible to read and write words and strings
and search or move through files looking for particular data elements.
Ȋȱ Experiment 1: Compile a program that creates a data file and writes the value 0x23
to that file. The file is saved on the mbed. The program then opens and reads back
the data value and displays it to the screen in a terminal application.
Ȋȱ Open the created file datafile.txt in a word processor, you should see a hash
character (#) in the top left corner (the ASCII character for 0x23 is the hash character).
#include "mbed.h"
Serial pc(USBTX,USBRX); // setup terminal link LocalFileSystem
local("local"); // define local file system intwrite_var;
intread_var; // create data variables
int main ()
{
FILE* File1 = fopen("/local/datafile.txt","w"); // open file
write_var=0x23; // example data
fputc(write_var, File1); // put char (data value) into file
fclose(File1); //
close file
FILE* File2 = fopen ("/local/datafile.txt","r"); // open
file for reading read_var = fgetc(File2);
// read first data value fclose(File2);
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ445

// close file pc.printf("input value = %i \n",read_var);


// display read data value
}
Ȋȱ Experiment 2: Compile a program that creates a file and writes text data to that
file. The file is saved on the mbed. The program then opens and reads back the
text data and displays it to the screen in a terminal application.
#include "mbed.h"
Serial pc( USBTX,USBRX); // setup terminal link LocalFileSystem
local("local"); // define local file system char write_string[64];
// character array up to 64 characters char read_string[64];
// create character arrays(strings) int main ()
{
FILE* File1 = fopen("/local/textfile.txt","w"); // open file
access fputs("lots and lots of words and letters", File1);
// put text into file fclose(File1);
// close file
FILE* File2 = fopen ("/local/textfile.txt","r"); // open
file for reading fgets(read_string,256,File2); // read
first data value
fclose(File2); // close file
pc.printf("text data: %s \n",read_string); // display
read data string }
Ȋȱ Open the file textfile.txt, you should see the correct text data.

Using formatted data

Ȋȱ The fprintf command is used to format data when working with files.
Ȋȱ fprintf has very similar syntax to printf, except that the filename pointer is also
required.
Ȋȱ An example of fprintf is to log specific events to a data file and include variable
data values such as time, sensor input data and output control settings.
Ȋȱ Experiment 3 uses the fprintf statement in an interrupt controlled toggle switch
project. Each time the toggle switch pushbutton is pressed, the LED changes state.
Also on each toggle event the file log.txt is updated to include the time elapsed
since the previous toggle button press and the current LED state.
Ȋȱ Experiment3 also implements a simple debounce timer to avoid multiple interrupts
and file write operations.
Ȋȱ Experiment 3: Compile a program that uses fprintf statement in an interrupt
controlled toggle switch project. On each toggle event and LED switches state and
the file log.txt is updated to include the time elapsed since the previous toggle
button press and the current LED state.
446ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

#include "mbed.h"
InterruptIn button(p30); // Interrupt on digital input p30
DigitalOut led1(LED1); // digital out to onboard LED1
Timer debounce; // define debounce timer
LocalFileSystem local("local"); // define local file system
void toggle(void); // function prototype int main()
{
debounce.start(); // start debounce timer button.
rise(&toggle); // attach the toggle function to the
rising edge
}
void toggle() { // perform toggle if debounce time has elapsed
if (debounce.read_ms()>200) {
led1=!led1; // toggle LED
FILE* Logfile = fopen ("/local/log.txt","a"); // open
file for appending
fprintf(Logfile,"time=%.3fs: setting led=%d\n\r",debounce.
read(),led1.read());
fclose(Logfile); // close file
debounce.reset(); // reset debounce timer }
}

9.13 DEVELOPING ADVANCED EMBEDDED SYSTEMS USING 32-BIT ARM MBED

When working on large, multifunctional projects it is particularly important to consider


the design and structure of the software. It is not possible to program all functionality
into a single loop! The techniques used in large multifunctional projects also bring
benefits to individuals who work on a number of similar design projects and regularly
reuse code.
Ȋȱ Good practice for embedded system design includes:
» Code that is readable, structured and documented
» Code that can be tested in a modular form
» Reuses existing code utilities to keep development time short
» Support multiple engineers working on a single project
» Allow for future upgrades to be implemented
Ȋȱ There are a number of C/C++ programming techniques which enable these design
requirements to be considered.

Functions and subroutines

Ȋȱ A function (sometimes called a subroutine) is a portion of code within a larger


program.
Ȋȱ A function performs a specific task and is relatively independent of the main code.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ447

Functions and subroutines

Working with 7-segment displays


Ȋȱ A 7-segment display is actually just 8 LEDs in a single package. We can therefore
connect each LED pin to an mbed pin to display a chosen number.
Ȋȱ For example, the code here uses a digital output for each LED segment and switches
the correct LEDs on and off to display the number 3.
#include " mbed.h "
DigitalOut A(p5);
DigitalOut B(p6);
DigitalOut C(p7);
DigitalOut D(p8);
DigitalOut E(p9);
DigitalOut F(p10);
DigitalOut G(p11);
DigitalOut DP(p12);
int main() {
A=1;
B=1;
C=1;
D=1;
E=0;
F=0;
G=1;
DP=0;
}
448ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Gnd Vout
Vin Vu
Vb IF–
pins 3,8 nR IF+
pin 7, seg.a 5 RD–
6 RD+

mbed Microcontroller
pin 6, seg.b
pin 4, seg.c 7 TD–
to 7-segment 8 TD+
pin 2, seg.d
display
pin 1, seg.e 9 D–
pin 9, seg.f 10 D+
pin 10, seg.g 11 30
pin 5, seg.dp 12 29
13 28
14 27
15 26
16 25
17 24
18 23
19 22
20 21

Working with 7-segment displays


Ȋȱ You may see that this code can get a bit intensive; it is a very simple operation but:
» we have defined a large number of digital outputs, and
» we have to set each output to a very specific value in order to display a single
number.
There is an issue with scalability here:
» What if we want to change the number regularly? Or output a number based
on the result of a calculation?
» What if we need more digits, i.e., decimal places or numbers with tens,
hundreds, thousands etc? }
If we want our LED display to continuously count from 0-9, our code might look
something like this.
Ȋȱ Exercise 1: connect a 7segment display to the mbed and verify
// program code for Exercise 1
#include "mbed.h"
DigitalOut A(p5); // segment A
DigitalOut B(p6); // segment B
DigitalOut C(p7); // segment C
DigitalOut D(p8); // segment D
DigitalOut E(p9); // segment E
DigitalOut F(p10); // segment F
DigitalOut G(p11); // segment G
DigitalOut DP(p12); // segment DP
intmain() {
while (1) { // infinite loop
A=1; B=1; C=1; D=1; E=1; F=1; G=0; DP=0; // set LEDs '0'
wait(0.2);
A=0; B=1; C=1; D=0; E=0; F=0; G=0; DP=0; // set LEDs '1'
wait(0.2);
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ449

A=1; B=1; C=0; D=1; E=1; F=0; G=1; DP=0; // set LEDs '2'
wait(0.2);
A=1; B=1; C=1; D=1; E=0; F=0; G=1; DP=0; // set LEDs '3'
wait(0.2);
A=0; B=1; C=1; D=0; E=0; F=1; G=1; DP=0; // set LEDs '4'
wait(0.2);
A=1; B=0; C=1; D=1; E=0; F=1; G=1; DP=0; // set LEDs '5'
wait(0.2);
A=1; B=0; C=1; D=1; E=1; F=1; G=1; DP=0; // set LEDs '6'
wait(0.2);
A=1; B=1; C=1; D=0; E=0; F=0; G=0; DP=0; // set LEDs '7'
wait(0.2);
A=1; B=1; C=1; D=1; E=1; F=1; G=1; DP=0; // set LEDs '8'
wait(0.2);
A=1; B=1; C=1; D=1; E=0; F=1; G=1; DP=0; // set LEDs '9'
wait(0.2);
}
}
Ȋȱ Before moving on to functions, we can simplify our code using a BusOut object.
Ȋȱ The BusOut object allows a number of digital outputs to be configured and
manipulated together.
Ȋȱ We can therefore define a BusOut object for our 7-segment display and send the
desired data byte value in order to display a chosen number.
Ȋȱ Exercise 2: Verify that the code here performs the same functionality as that in the
previous exercise.
Ȋȱ There are some issues with this current method for coding the 7segment display:
» If we wanted to add a second 7segment display and count from 099, we would
clearly have a problem – we’d need to write lots of extra code!
» There is also very little flexibility with this coding method – if we want to
change the functionality slightly (for example, to display every third number
or to change the timing).
» We have to make quite a lot of changes.
» There is a better way to program this type of functionality; using functions.
// program code for Exercise 2
#include "mbed.h"
BusOut Seg1(p5,p6,p7,p8,p9,p10,p11,p12); // ABCDEFGDP
intmain() {
while (1) { // infinite loop
Seg1=0x3F; // 00111111 binary LEDs to '0'
wait(0.2);
Seg1=0x06; // 00000110 binary LEDs to '1'
wait(0.2);
Seg1=0x5B; // 01011011 binary LEDs to '2'
450ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

wait(0.2);
Seg1=0x4F; // 01001111 binary LEDs to '3'
wait(0.2);
Seg1=0x66; // 01100110 binary LEDs to '4'
wait(0.2);
Seg1=0x6D; // 01101101 binary LEDs to '5'
wait(0.2);
Seg1=0x7D; // 01111101 binary LEDs to '6'
wait(0.2);
Seg1=0x07; // 00000111 binary LEDs to '7'
wait(0.2);
Seg1=0x7F; // 01111111 binary LEDs to '8'
wait(0.2);
Seg1=0x6F; // 01101111 binary LEDs to '9'
wait(0.2);
}
}

C function syntax
Ȋȱ The correct C function syntax is as follows:
Return_type function_name ( variable_type_1 variable_name_1, variable_type_2
variable_name_2 ,…)
{
... C code here
... C code here
}
ȊȱAs with variables, all functions must be declared at the start of a program.
ȊȱThe declaration statements for functions are called prototypes.
ȊȱThe correct format for a function prototype is the same as in the function itself,
as follows:
Return_type function_name ( variable_type_1 variable_name_1,
variable_type_2 variable_name_2 ,…)

Designing a C function
Ȋȱ It is beneficial for us to design a C function that inputs a count variable and returns
the 8-bit value for the corresponding 7-segment display, for example:
char SegConvert(char SegValue) { // function 'SegConvert'
char SegByte=0x00;
switch (SegValue) { //DPGFEDCBA
case 0 :SegByte = 0x3F;break; // 00111111 binary
case 1 :SegByte = 0x06;break; // 00000110 binary
case 2 :SegByte = 0x5B;break; // 01011011 binary
case 3 :SegByte = 0x4F;break; // 01001111 binary
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ451

case 4 :SegByte = 0x66;break; // 01100110 binary


case 5 :SegByte = 0x6D;break; // 01101101 binary
case 6 :SegByte = 0x7D;break; // 01111101 binary
case 7 :SegByte = 0x07;break; // 00000111 binary
case 8 :SegByte = 0x7F;break; // 01111111 binary
case 9 :SegByte = 0x6F;break; // 01101111 binary
}
return SegByte;
}
Ȋȱ Note that this function uses a C ‘switch/case’ statement which performs like an
‘if’ operation with a number of possible conditions.

Implementing a C function
Ȋȱ Exercise 3: Verify that the following program, using the SegConvert function,
performs the same functionality as in Exercises 1 and 2.
#include "mbed.h"
BusOut Seg1(p5,p6,p7,p8,p9,p10,p11,p12);// A,B,C,D,E,F,G,DP
char SegConvert(char SegValue); // function prototype
intmain() { // main program
while (1) { // infinite loop
for (char i=0;i<10;i++) {
Seg1=SegConvert(i);
wait(0.2);
}
}
}
char SegConvert(char SegValue) { // function 'SegConvert'
char SegByte=0x00;
switch (SegValue) { //DPGFEDCBA
case 0 :SegByte = 0x3F;break; // 00111111 binary
case 1 :SegByte = 0x06;break; // 00000110 binary
case 2 :SegByte = 0x5B;break; // 01011011 binary
case 3 :SegByte = 0x4F;break; // 01001111 binary
case 4 :SegByte = 0x66;break; // 01100110 binary
case 5 :SegByte = 0x6D;break; // 01101101 binary
case 6 :SegByte = 0x7D;break; // 01111101 binary
case 7 :SegByte = 0x07;break; // 00000111 binary
case 8 :SegByte = 0x7F;break; // 01111111 binary
case 9 :SegByte = 0x6F;break; // 01101111 binary
}
return SegByte;
}
452ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Summary of C functions

Ȋȱ Functions can be used to:


» Process and manipulate data; we can input data values to a function, which
returns manipulated data back to the main program. For example, code
mathematical algorithms, look up tables and data conversions, as well as
control features which may operate on a number of different and parallel data
streams
» Allow clean, efficient and manageable code designing.
» Allow multiple engineers to develop software features independently, and
hence enable the practice of modular coding.
Ȋȱ Functions can also be reused, which means that engineers don’t have to rewrite
common code every time they start a new project.
Ȋȱ Notice that in every program we also have a main() function, which is where our
main program code is defined.

9.14 PROGRAM BYTES OF PARALLEL DATA USING 32-BIT ARM MBED

Buses can be parallel, carrying data on multiple wires, or serial, carrying data sequentially
on a single wire. Conventional PCI, Parallel ATA and PCMCIA are examples of parallel
buses. Examples of serial interfaces include Ethernet, FireWire, USB, I2C, and SPI. The
BusOut interface is used to create a number of parallel DigitalOut pins that can be
written as one numeric value.TheBusOut interface can be used to set the state of the
output pins, and also read back the current output state.
On the mbed, the four on-board LEDs can be used to create a BusOut interface and
have been specially configured to operate with no need for extra wires or connections.

The mbed also has 26 digital IO pins (pins 5-30) which can be configured as a digital
bus for use with the BusOut and BusIn interfaces.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ453

The BusOut library functions are shown in the table below


BusOut A digital output bus, used for setting the state of a collection of pins
BusOut Create a BusOut object, connected to the specified pins
write Write the value to the output bus
read Read the value currently output on the bus
operator= A shorthand for write
operator int() A shorthand for read

We can use digital outputs to switch the on-board LEDs in a specific order.
For example, we can use the code shown to produce a light that moves horizontally
across the 4 on-board LEDs.
The code is very simple, but it could become quite complex if we require more outputs,
or to perform more on/off configurations of the LED
#include " mbed.h "
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
int main() {
while(1) {
led1 = 1;
led2 = 0;
led3 = 0;
led4 = 0;
wait(0.25);
led1 = 0;
led2 = 1;
led3 = 0;
led4 = 0;
wait(0.25);
led1 = 0;
led2 = 0;
led3 = 1;
led4 = 0;
wait(0.25);
led1 = 0;
led2 = 0;
led3 = 0;
led4 = 1;
wait(0.25);
}
}
454ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Exercise 1: Using digital outputs, create a program to produce a “Knightrider”


LED sweep effect with the on-board LEDs.
#include "mbed.h"
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
intmain() {
while(1) { led1 = 1; led2 = 0; led3 = 0; led4 = 0;
wait(0.25); led1 = 0; led2 = 1; led3 = 0; led4 = 0;
wait(0.25); led1 = 0; led2 = 0; led3 = 1; led4 = 0;
wait(0.25); led1 = 0; led2 = 0; led3 = 0; led4 = 1;
wait(0.25); led1 = 0; led2 = 0; led3 = 1; led4 = 0;
wait(0.25); led1 = 0; led2 = 1; led3 = 0; led4 = 0;
wait(0.25);
}
}
Ȋȱ Exercise 2: Using the BusOut object, create a program to produce a “Knightrider”
sweep effect with the on-board LEDs.
Ȋȱ Verify that this program behaves the same way as the previous exercise.
#include " mbed.h "
BusOut myleds ( LED4, LED3, LED2, LED1);
char x=1;
int main() {
while(1) {
for( int i=0; i<3; i++) { // x = a << b then x = a*2^b;
x = x <<1; // x=1,2,4,8 or x=0001,0010,0100,1000
myleds = x; // sweep left
wait(0.2);
}
for( int i=0; i<3; i++) { // x = a >> b then x = a/2^b;
x = x >>1; // x=8,4,2,1 or x=1000,0100,0010,0001
myleds = x; // sweep right
wait(0.2);
}
}
}
Ȋȱ Note: Shift operators, << and >>, are used to multiply and divide by two.
Ȋȱ We will use the 2x16 character Powertip PC1602F LCD, though a number of similar
LCD displays can be found with the same hardware configuration and functionality.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ455

Ȋȱ The following must be achieved in order to interface the LCD:


» Hardware integration: we will need to connect the LCD to the correct mbed
pins.
» Modular coding: as there are many processes that need to be completed, it
makes sense to define LCD functions in modular files.
» Initialising the LCD: a specific sequence of control signals must be sent to the
LCD in order to initialise it.
» Outputting data: we will need to understand how the LCD converts control
data into legible display data.
Ȋȱ The PC1602F display is a 2x16 character display with an on board data controller
chip and an integrated backlight.
Ȋȱ The LCD display has 16 connections as shown above.
Ȋȱ The Powertip PC1602F datasheet is available from here:
http://www.rapidonline.com/netalogue/specs/57-0911.pdf

Pin Number Pin Name Function


1 VSS Power supply (GND)
2. VDD Power Supply (5V)
3 V0 Contrast adjust
4 RS Register select signal
5 R/W Data read/write
6 E Enable signal
7 DB0 Data bus line bit 0
8 DB1 Data bus line bit 0
9 DB2 Data bus line bit 0
10 DB3 Data bus line bit 0
11 DB4 Data bus line bit 0
12 DB5 Data bus line bit 0
13 DB6 Data bus line bit 0
14 DB7 Data bus line bit 0
15 A Power supply for LED back light (5V)
16 K Power supply for LED back light (GND)
456ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Operation and interfacing of LCD is summarised as follows:


» The display is initialised by sending control instructions to the relevant
configuration registers in the LCD. This is done by setting RS, R/W and E all
low, then sending the correct data through bits DB0-DB7.
» We will use the LCD in 4-bit mode which means that we only need to use
the final 4-bits of the data bus (DB4-DB7). This means we can control the LCD
with only 7 digital lines, rather than 11 lines which are required for 8-bit
mode.
» After each data byte has been sent, the Enable bit must be toggled on then
off again, this tells the LCD that data is ready and should be processed.
» Once the LCD has been initialised, display data can be sent by setting the RS
bit. Again, after each byte of display data has been sent, the Enable bit should
be toggled to process the data.
Ȋȱ We obviously need a digital mbed pin to attach to each of the LCD data pins. We
need 4 digital outputs to send the 4-bit instruction and display data and 3 digital
outputs to manipulate the RS, R/W and E control flags.
Ȋȱ We can connect the PC1602F to the mbed using the following interface configuration:

Mbed pin number LCD pin Number LCD Pin Name Power Connections
1 1 VSS 0V
39 2 VDD 5V
1 3 V0 0V
19 4 RS
1 5 R/W 0V
20 6 E
21 11 DB4
22 12 DB5
23 13 DB6
24 14 DB7
39 15 A 5V
1 16 K 0V

Ȋȱ Note: in general, we only use the LCD in write mode, so we tie R/W permanently
to ground (mbed pin 1).
Ȋȱ Note that the PC1602F has a non-conventional pin layout which reads from left
to right:
14 13 12 11 10 9 8 7 6 5 4 3 2 1 16 15
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 E R/W RS V0 VDD VSS A K

The hardware setup is as shown.


’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ457

Ȋȱ We will use three files for the LCD application:


» A main code file (main.cpp) which can call functions defined in the LCD
feature file.
» An LCD feature file (LCD.cpp) which will include all the functions for
initialising and sending data to the LCD.
» An LCD header file (LCD.h) which will be used to declare data and function
prototypes.
Ȋȱ We will declare the following functions in our LCD header file toggle_enable to
toggle the enable bit LCD_init that initialises the LCD display_to_LCD which will
display characters on the LCD
Ȋȱ Our LCD.h file should therefore be as follows:
// LCD.h file
# ifndef LCD_H
#define LCD_H
#include " mbed.h "
void display_to_LCD ( char value); //function to display characters
on the LCD
void toggle_enable ( void); //function to toggle the enable bit
void LCD_init void); //function to ( initialise the LCD
# endif
Ȋȱ In LCD.cpp:
» We define the digital IO classes for the mbed. We need one digital output for
each of RS and E and we will use the mbedBusOut class for the 4-bit data.
» We send a number of 4-bit data packets to the LCD in order to initialise it
and to display alphanumeric characters on the display.
458ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

» After each data packet has been sent, the LCD requires the Enable bit to be
toggled (i.e., sent high and then low with a pause in between). This is done
by the toggle_enable function.
// define mbed objects
DigitalOut RS(p19);
DigitalOut E(p20);
BusOutdata(p21, p22, p23, p24);
/**** toggle enable function
void toggle_enable ( void ){
E=1;
wait(0.001);
E=0;
wait(0.001);
}
Ȋȱ A specific initialisation procedure must be followed in order for the PC1602F
display to operate correctly. Please refer to the PC1602F datasheet for more specific
configuration details.
Ȋȱ We will code the initialisation routine using the LCD_init function:
» In order to initialise we first need to wait for a short period (approximately
20ms), set the RS and E lines to zero and then send a number of configuration
messages to set up the LCD functionality.
» To set the LCD function mode we send a binary value of 0010 1000 (0x28 hex)
to the LCD data pins, define 4-bit mode, 2 line display and 5x7 dot characters.
// Display Mode
data= 0 x 0 ;
toggle_enable () ;
data= 0 xF ;
toggle_enable () ;
» Note that as we are using 4-bit mode, we need to send two pieces of 4-bit
data for each instruction; effectively setting one 8-bit register by sending two
4-bit packets of data.
// Function Mode
data= 0 x 2 ;
toggle_enable () ;
data= 0 x 8 ;
toggle_enable () ;
Ȋȱ The LCD display mode control register must also be set during initialisation.
Ȋȱ Here we need to send a command to switch the display on, and to determine the
cursor function. Value 0x0F will switch the display on with a blinking cursor.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ459

Ȋȱ Before data can be written to the display, the display must first be cleared and
the cursor must be reset to the first character in the first row. This is done by the
clear display command with a value 0x01.
Ȋȱ Display data is sent to the LCD screen by the display_to_LCD function. This
function performs the following task:
// Clear display
data= 0 x 0 ;
toggle_enable () ;
data= 0 x 1 ;
toggle_enable () ;
» Setting the RS flag to 1 (data setting).
» Sending a data byte describing the ascii character to be displayed.
» Toggle the enable flag.
» The character displayed to the LCD is described by an 8-bit hexadecimal ascii
value. The complete ascii table is included with the LCD datasheet.
/**** display ****/
void display_to_LCD ( char value ){
RS=1;
//***** display character
data=value>>4; // upper 4 bits
toggle_enable () ;
data= value&0x0F ; // lower 4 bits
toggle_enable () ;
}
Ȋȱ If we wish to display the word “HELLO”, for example, the hexadecimal ascii
values required are as follows: 0x48, 0x45, 0x4C, 0x4C and 0x4F.
Ȋȱ Other ascii values can be found in the table below:

LSB
0×0 0×1 0×2 0×3 0×4 0×5 0×6 0×7 0×8 0×9 0×A 0×B 0×C 0×D 0×E 0×F
0×0
0×1
0×2 ! " # $ & ' ( ) * + , – . /
0×3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
MSB
0×4 @ A B C D E F G H I J K L M N O
0×5 P Q R S T U V W X Y Z [ \ ] ^ —
0×6 ` a b c d e f g h i j k l m n o
0×7 p q r s t u v w x y z { | } ~
460ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Digital IO and LCD functions are therefore defined in LCD.cpp as below.


// LCD.cpp file
#include “ LCD.h "
DigitalOut RS( p19 ) ;
DigitalOut E(p20);
BusOut data(p21, p22, p23, p24);
void toggle_enable ( void ){
E=1;
wait(0.001);
E=0;
wait(0.001);
}
//initialise LCD function
void LCD_init ( void ){
wait(0.02);
RS=0;
E=0;
//function mode
data= 0 x 2 ;
toggle_enable () ;
data= 0 x 8 ;
toggle_enable () ;
// continued...
//... LCD.cpp continued...
//display mode
data= 0 x 0 ;
toggle_enable () ;
data= 0 xF ;
toggle_enable () ;
//clear display
data= 0 x 0 ;
toggle_enable () ;
data= 0 x 1 ;
toggle_enable () ;
}
//display function
void display_to_LCD ( char value ){
RS=1;
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ461

data=value>>4;
toggle_enable () ;
data= value&0x0F ;
toggle_enable () ;
}
Ȋȱ Exercise 3: Connect the LCD to an mbed and construct a new program with the
files main.cpp, LCD.cpp and LCD.h, as described earlier.
Add the following code to your main.cpp file and compile and run on the mbed:
#include “ LCD.h "
int main() {
LCD_init () ;
display_to_LCD ( 0 x 48 ) ; // ‘H’
display_to_LCD ( 0 x 45 ) ; // ‘E’
display_to_LCD ( 0 x4C ) ; // ‘L’
display_to_LCD ( 0 x4C ) ; // ‘L’
display_to_LCD ( 0 x4F ) ; // ‘O’
}
Verify that the word ‘HELLO’ is correctly displayed with a flashing cursor.
Ȋȱ The mbedTextLCD library is more advanced than the simple functions we have
created.
» The TextLCD library performs the laborious LCD setup routine for us.
» The TextLCD definition also tells the LCD object which pins are used for
which functions.
Ȋȱ The pin definition is defined in the following manner:
TextLCDlcd(intrs, int e, int d0, int d1, int d2, int d3);
Ȋȱ We need to ensure that our pins are defined in the same order. For our hardware
setup this will be:
TextLCD lcd ( p19 , p20 , p21 , p22 , p23 , p24 ) ;
Ȋȱ We use printf statements to display characters on the LCD screen.
Ȋȱ Exercise 4: Compile a “Hello World” example using the mbed library, which makes
use of an alphanumeric LCD much simpler and quicker to program.
#include " mbed.h "
#include " TextLCD.h "
TextLCD lcd ( p19 , p20, p21, p22, p23, p24); // rs,e,d0,d1,d2,d3
int main() {
lcd.printf ( "Hello World!");
}
Ȋȱ Import the mbedTextLCD.h library file to your project (right click and select ‘import
library’).
462ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ This library is effectively a file full of specific LCD functions already written for
you. Use the following link for the library file: http://mbed.org/users/simon/
libraries/TextLCD/livod0.
Ȋȱ The cursor can be moved to a chosen position to allow you to choose where to
display data, for example:
lcd.locate (3 ,1);
Ȋȱ The display is laid out as 2 rows (0-1) of 16 columns (0-15). The locate function
defines the column first followed by the row.
» The above example moves the cursor to the 4th column and 2nd line.
» Any printf statements after the locate command will be printed at the new
cursor location.
Ȋȱ We can also clear the screen with the following command:
lcd.cls () ;
Ȋȱ We display data on the screen using the standard printf statement too. If we want
to display the value of an integer to the screen, we need to:
» declare the variable
» give the variable a value
» display the variable to the screen by using the printf statement,
x = 1028
lcd.printf ( "% i",x ) ;
Ȋȱ Note that the “%i” command is used to indicate that an integer is to be output,
and the integer name follows.
Ȋȱ Exercise 5: display a continuous count variable on the LCD display by implementing
the following code:
#include " mbed.h “
#include " TextLCD.h “
TextLCD lcd ( p19 , p20 , p21 , p22 , p23 , p24 ) ; // rs ,
e, d0 , d1 , d2 , d3
int x=0;
int main() {
lcd.printf ( "LCD Counter");
while (1) {
lcd.locate (5 ,1);
lcd.printf ( "% i",x ) ;
wait(1);
x++;
}
}
Ȋȱ Don’t forget to import the TextLCD library!
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ463

Ȋȱ Increase the speed of the counter and investigate how the cursor position changes
as the count value increases.
Ȋȱ Exercise 6: Display the analog value to the screen.
» You will need to use a potentiometer to provide an analog input.
» The analog input variable has a floating point value between 0 and 1, where
0 is 0V and 1 represents 3.3V.
» We will multiply the analog input value by 100 to make it a percentage between
0-100%.
» An infinite loop is used so that the screen continuously updates automatically.
To do this it is necessary to clear the screen and add a delay to set the update
frequency.
Gnd Vout
Vin Vu
10k Vb IF–
nR IF+
5 RD–
6 mbed Microcontroller RD+
7 TD–
8 TD+
9 D–
10 D+
11 30
12 29
13 28
14 27
15 26
16 25
17 24
18 23
19 22
20 21
(power is taken from USB connection)

Ȋȱ Add the following to your main.cpp. Your code should now compile and run:
#include " mbed.h "
#include " TextLCD.h "
TextLCD lcd ( p19 , p20, p21, p22, p23, p24); // rs,e,d0 ,
d1,d2,d3
AnalogIn Ain( p17 ) ;
int percentage;
int main() {
while(1){
percentage=Ain*100;
lcd.printf ( "% i",percentage ) ;
wait(0.002);
lcd.cls () ;
}
}
The analog value should change as you move the position of the potentiometer.
464ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

9.15 PROGRAMMING PWM USING 32-BIT ARM MBED

In PWM, the period of any pulse output is normally kept constant, and the pulse width
or “on” time is varied
The duty cycle is the proportion of time that the pulse is ‘on’ or ‘high’, and is expressed
as a percentage:
duty cycle = 100% * (pulse on time) / (pulse period)

“on” time, ton

Average value

iod,T

Whatever duty cycle a PWM stream has, there is an average value, as indicated by
the dotted line
If the on time is small, the average value is low; if the on time is large, the average
value is high
By controlling the duty cycle, we can control this average value

“on” time, ton

Average value

iod,T

The average value can be extracted from the PWM stream with a low-pass filter
As long as PWM frequency and values of R and C are appropriately chosen, Vout
becomes an analog output
In practice, this sort of filtering is not always required; many physical systems have
response characteristics which, in reality, act like low pass filters

Vin R Vout

C
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ465

The PwmOut interface is used to control the frequency and mark-space ratio of a digital
pulse train
The mbed has up to six PWM outputs, on pins 21 to 26, although these PwmOuts all
share the same period timer

The library functions are shown in the table below.


PwmOut A pulse-width modulation digital output
Functions Usage
PwmOut Create a PwmOut connected to the specified pin
write Set the output duty-cycle, specified as a normalised float (0.0 – 1.0)
read Return the current output duty-cycle setting, measured as a
normalised float (0.0 – 1.0)
period period_msperiod_us Set the PWM period, specified in seconds (float), milli-seconds
(int) or microseconds (int), keeping the duty cycle same.
pulsewidthpulsewidth_ Set the PWM pulsewidth, specified in seconds (float),
mspulsewidth_us milliseconds (int) or microseconds (int), keeping the period the
same.
operator= A operator shorthand for write()
operator float() An operator shorthand for read()

Ȋȱ Exercise 1: Create a PWM signal which we can see on an oscilloscope. The following
code will generate a 100 Hz pulse with 50% duty cycle
#include " mbed.h "
PwmOut PWM1(p21);
466ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

int main() {
PWM1.period(0.010); // set PWM period to 10 ms
PWM1=0.5; // set duty cycle to 50%
}
Ȋȱ Exercise 2: Change the duty cycle to some different value, say 0.2 (20%) and 0.8
(80%) and check the correct display is seen on the ‘scope’, as shown below

Ȋȱ Exercise 3: This example code uses a pulse width modulation signal to increase
and decrease the brightness of the Onboard LED.
The program requires the use of a host terminal application to communicate the
brightness value to the mbed, in this example by using the ‘u’ and ‘d’ keys.
// host terminal LED dimmer control
# include " mbed.h "
Serial pc(USBTX, USBRX); // tx , rx
PwmOut led(LED1);
float brightness=0.0;
int main() {
pc.printf ( “Control of LED dimmer by host terminal \ n \ r");
pc.printf ( "Press 'u‘ = brighter , 'd‘ = dimmer \ n \ r ");
while(1) {
char c = pc.getc () ;
wait(0.001);
if((c == 'u') && (brightness < 0.1)) {
brightness += 0.001;
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ467

led = brightness;
}
if((c == 'd') && (brightness > 0.0)) {
brightness - = 0.001;
led = brightness;
}
pc.printf ( "%c %1.3f \ n \ r",c,brightness ) ;
}
}

9.16 PROGRAM 32-BIT ARM MBED USING I2C

The name I2C is shorthand for Standard Inter-Integrated Circuit bus


I2C is a serial data protocol which operates with a master/slave relationship
I2C only uses two physical wires, this means that data only travels in one direction
at a time.
The I2C protocol is a two-wire serial bus:

The I2C communication signals are serial data (SDA) and serial clock (SCL).
Ȋȱ These two signals make it possible to support serial communication of 8-bit data
bytes, 7-bit device addresses as well as control bits.
Ȋȱ Using just two wires makes it cheap and simple to implement in hardware
I2C has a built-in addressing scheme, which simplifies the task of linking multiple
devices together.
Ȋȱ In general, the device that initiates communication is termed the ‘master’. A device
being addressed by the master is called a ‘slave’.
Ȋȱ Each I2C-compatible slave device has a predefined device address. The slaves are
therefore responsible for monitoring the bus and responding only to data and
commands associated with their own address.
Ȋȱ This addressing method, however, limits the number of identical slave devices
that can exist on a single I2C bus, as each device must have a unique address.
For some devices, only a few of the address bits are user configurable. The data
transfer is made up of the Master signalling a Start Condition, followed by one or two
bytes containing address and control information.
468ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The Start condition is defined by a high to low transition of SDA when SCL is high.
A low to high transition of SDA while SCL is high defines a Stop condition
One SCL clock pulse is generated for each SDA data bit, and data may only change
when the clock is low.

SDA

SCL

Start Stop

The byte following the Start condition is made up of seven address bits, and one data
direction bit (Read/Write)
All data transferred is in units of one byte, with no limit on the number of bytes
transferred in one message.
Each byte must be followed by a 1-bit acknowledge from the receiver, during which
time the transmitter relinquishes SDA control.

SDA

SCL

Data Valid
Data
may change

SCL

SDA

Start Address R/W Ack Data Ack Stop


’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ469

The mbed I2C library functions are shown in the table below:
I2C An I2C Master, used for communicating with I2C slave devices
Functions Usage
I2C Create an I2C Master interface, connected to the specified pins
frequency Set the frequency of the I2C interface
read Read from an I2C slave
read Read a single byte from the I2C bus
write Write to an I2C slave
write Write single byte out on the I2CC bus
start Creates a start condition on the I2C bus
stop Creates a stop condition on the I2C bus

The I2C Interface can be used on mbed pins p9/p10 and p28/p27.
Note also that the SDA and SCL data signals each need to be ‘pulled up’ to 3.3V,
with a resistor value which can be optimised for the exact circuit configuration; in this
œŽž™ȱ ŽȱŒ‘˜˜œŽȱŘǯŘȱ”Ǎȱ›Žœ’œ˜›ǯȱ

Evaluating the TMP102 I2C temperature sensor


Configuration and data register details are given in the TMP102 data sheet http://
focus.ti.com/lit/ds/sbos397b/sbos397b.pdf
To configure the temperature sensor we need to:
Ȋȱ Use arrays of 8-bit values for the data variables, because the I2C bus can only
communicate data in one bytes.
470ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Set the configuration register; we first need to send a data byte of 0x01 to specify
that the Pointer Register is set to ‘Configuration Register’.
Ȋȱ Send two bytes of data to perform the configuration. A simple configuration value
to initialise the TMP102 to normal mode operation is 0x60A0.
Ȋȱ To read the data register we need to set the pointer value to 0x00.
Ȋȱ To print the data we need to convert the data from a 16-bit data reading to an
actual temperature value. The conversion required is to shift the data right by 4
bits (it’s actually only 12-bit data held in two 8-bit registers) and to multiply by
the 1-bit resolution which is 0.0625 degrees C per LSB.
Interfacing the TMP102 with the mbed
Ȋȱ The temperature sensor TMP102 can be connected to the mbed as shown:

Signal TMP102 Pin Mbed Pin Notes


Vcc (3.3 V) 1 40
Gnd (0 V) 4 1
SDA 2 9 ŘǯŘȱ”Ǎȱ™ž••Ȭž™ȱ˜ȱřǯřȱȱ
SCL 3 10 ŘǯŘȱ”Ǎȱ™ž••Ȭž™ȱ˜ȱřǯřȱ

Ȋȱ Exercise 1: Connect the temperature sensor to an I2C bus. Verify that the correct
data can be read by continuous display updates of temperature to the screen.
» Test that the temperature increases when you press your finger against the
sensor. You can even try placing the sensor on something warm, for example
a pocket hand warmer, in order to check that it reads temperature correctly.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ471

The following program will configure the TMP102 sensor, read data, convert data to
degrees Celsius and then display values to the screen every second:
#include "mbed.h“
I2C tempsensor(p9, p10); //sda, sc1 Serial
pc(USBTX, USBRX); //tx, rx
constintaddr = 0x90;
char config_t[3];
char temp_read[2];
float temp;
intmain() {
config_t[0] = 0x01; //set pointer reg to 'config register'
config_t[1] = 0x60; // config data byte1
config_t[2] = 0xA0; // config data byte2
tempsensor.write(addr, config_t, 3);
config_t[0] = 0x00; //set pointer reg to 'data register'
tempsensor.write(addr, config_t, 1); //send to pointer 'read
temp'
while(1) {
wait(1);
tempsensor.read(addr, temp_read, 2); //read the two-byte temp
data
temp = 0.0625 * (((temp_read[0] << 8) + temp_read[1]) >> 4);
//convert data
pc.printf("Temp = %.2f degC\n\r", temp);
}
}
Ȋȱ Configuration and data register details are given in the SRF08 data sheet.
Ȋȱ The following information summarises the configuration and data read procedures
for the SRF08:
» The rangefinder I2C address is 0xE0.
» The pointer value for the command register is 0x00.
» A data value of 0x51 to the command register initialises the range finder to
operate and return data in cm.
» A pointer value of 0x02 prepares for 16-bit data (i.e. two bytes) to be read.
The SRF08 ultrasonic range finder is an I2C device which measures distance and
proximity of items
The SRF08 can be connected to the mbed as shown:
472ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

+3.3V

IC7
+5V +5V
Gnd Vout

+5V
Vin Vu
+5V Vb IF–
nR IF+

1K8
5 RD–

1K8
R2
R1
6 RD+
7 TD–

mbed Microcontroller
VCC 8 TD+
VCC
SDA SDA 9 D–
SCL SCL 10 D+
NC NC 11 30
GND GND 12 29
13 28
14 27
15 26
16 25
17 24
USRF1 18 23
19 22
20 21

Ȋȱ Exercise 2: Configure the SRF08 ultrasonic rangefinder to update distance data to


the screen. The following code will perform this operation:
#include "mbed.h"
I2C rangefinder(p9, p10); //sda, sc1
Serial pc(USBTX, USBRX); //tx, rx
constintaddr = 0xE0;
char config_r[2];
char range_read[2];
float range;
intmain()
{ while (1)
{ config_r[0] = 0x00; //set pointer reg to ‘cmd register'
config_r[1] = 0x51; // config data byte1
rangefinder.write(addr, config_r, 2);
wait(0.07);
config_r[0] = 0x02; //set pointer reg to 'data register'
rangefinder.write(addr, config_r, 1); //send to pointer 'read
range'
rangefinder.read(addr, range_read, 2); //read the two-byte range
data
range = ((range_read[0] << 8) + range_read[1]);
pc.printf("Range = %.2f cm\n\r", range); //print range on
screen
wait(0.05);
}
}
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ473

9.17 INTRODUCING SPI PROGRAMMING WITH 32-BIT MICROCONTROLLER


ARM MBED

The SPI protocol uses four signals: clock (SCLK), master data output, slave data input
(MOSI), master data input, slave data output (MISO), and slave chip select (CS)
When multiple slave devices exist, the master must output a unique CS signal for
each slave.
SCLK
MIOSI Peripheral
MISO Device 1
CS1
CS2
CS3 Peripheral
Microcontroller Device 2

Peripheral
Device 3

SPI is suited to transfer data streams, for example, data communication between
microprocessors or data transfer from an analog-to-digital converter.
It can achieve higher data rates than I2C, as it doesn’t send address or control
information, and doesn't include an acknowledge bit for every byte.
SPI data communication is ideal for use in digital signal processing applications,
where data is regularly exchanged between the master and the slave.
A SPI data transfer is initiated by the master device as follows:
Ȋȱ The master first configures the SPI clock (SCLK) to be a frequency supported by
the recipient slave device (up to 70 MHz).
Ȋȱ The master sets the chip select signal (CS) of the intended recipient slave to 0 V.
Ȋȱ The master then starts the clock pulses on SCLK to indicate that data is to be
transferred.
Ȋȱ The master simultaneously sends data as consecutive bits on MOSI.
Ȋȱ The number of bits in each data frame can be configured, but is usually between
4 and 16 bits.
Ȋȱ The slave returns data in the same manner on MISO.
The master must also configure the clock’s polarity (CPOL) and phase (CPHA) as
follows:
CPOL
0 Clock active high (off =0) SCLK

1 Clock active low (off=1) SCLK

CPHA
0 Clock out of phase with SCLK
data (CPOL = 0) MOSI/MISO

1 Clock in phase with data SCLK


(CPOL = 0) MOSI/MISO
474ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

We, therefore, have four SPI modes as follows:


Mode CPOL CPHA
0 0 0
1 0 1
2 1 0
3 1 1

In general, SPI devices are designed to operate in one of the four modes and this is
described in the device.
The mbed SPI library functions are shown in the table below:
SPI A SPI Master, used for communicating with SPI slave devices functions
Functions Usage
SPI Create a SPI master connected to the specified pins format
format Configure the data transmission mode and data length
frequency Set the SPI bus clock frequency
write Write to the SPI slave and return the response

Note: this table is for the SPI master library. There is also an SPI slave library which
is used for communicating with an SPI Master device. The SPI Slave library is not
covered here.
The SPI Interface can be used on pins p5/p6/p7 and p11/p12/p13
Default settings of the SPI interface on the mbed:
Ȋȱ Default clock frequency of 1 MHz
Ȋȱ Default data length of 8 bits
Ȋȱ Default mode of 0
Configuration and data register details are given in the ADXL345 datasheet
http://www.analog.com/static/imported-files/data_sheets/ADXL345.pdf
The accelerometer is actually analog in nature, measuring acceleration on 3 axes.
This kind of accelerometer has an internal capacitor mounted in the plane of each
axis. Acceleration causes the capacitor plates to move, hence changing the output voltage
proportionally to the acceleration or force.
The ADXL345 accelerometer converts the analog voltage fluctuations to digital and
outputs this over a digital communication protocol.
The ADXL345 can be configured to communicate in SPI and I2C modes.
To configure the accelerometer for SPI communication:
Ȋȱ Set the SPI frequency to 1-5 MHz and SPI Mode 3
Ȋȱ Set the Data Format by writing to register 0x31; a data byte of 0x0B will configure
the accelerometer data to be in the range ±16g and to a resolution of 0.004g/LSB
(1g is the value of acceleration due to earth’s gravity, i.e. 9.81 m/s2)
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ475

Ȋȱ Set the device into ‘measure’ mode by sending a data value 0x08 to the Power
Control register (address 0x2D)

When writing to the ADXL345 we must follow the following procedure


Ȋȱ Set CS low
Ȋȱ Send register address byte
Ȋȱ Send data byte
Ȋȱ Set CS high
To read 3-axis data back from the ADXL345:
Ȋȱ Set the read/write bit high (bit 7 of the address byte).
Ȋȱ Set the multibyte-data flag high (bit 6 of the address byte).
Ȋȱ Set CS low
Ȋȱ Send the configured address byte for register 0x32.
Ȋȱ Read 6 bytes of data back from the ADXL345 by writing 6 dummy bytes of 0x00.
Ȋȱ Set CS high.
The 6 returned data bytes contain the most significant and least significant bytes for
each of the three measurement axes (x, y and z). We therefore need to convert the data
to floating point ‘g’ values by combining the relevant data bytes and multiplying by the
configured data resolution.
476ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The ADXL345 can be connected to the mbed as shown:


SCL
MOSI
MISO
INT2
INT1
CS
x VCC
y GND

ADXL345 signal name mbed pin


Vcc 40
Gnd 1
SCL 13
MOSI 11
MISO 12
CS 14

Ȋȱ Exercise 1: Configure the ADXL345 accelerometer to continuous output 3-axis data


to the terminal screen.
» Set up the SPI accelerometer as described earlier.
» Initiate a data read by setting CS high and writing the configured address
value.
» Use a 6 element ‘char’ buffer to read the raw data back from the accelerometer.
» Combine the relevant most significant and least significant bytes into three
twos- complement, 16-bit integer values (to keep things simple, you can make
use of the 16int_t data type for this to function correctly).
» Convert the 16-bit data to the floating point by multiplying each axis reading
by the configured data resolution.
» Output and display data to a host terminal application.
// solution for SPI Exercise 1
#include "mbed.h“
SPI acc(p11,p12,p13); // setup SPI interface on pins 11,12,13
DigitalOut cs(p14); // use pin 14 as chip select
Serial pc(USBTX, USBRX); // setup USB interface to host
terminal
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ477

char buffer[6]; // raw data array type char


signed short data[3]; // acc data is signed 16 bit from -32,768
to +32,767
float x, y, z; // floating point data
int main()
{
cs=1;
acc.format(8,3); // 8 bit data, Mode 3
acc.frequency(2000000); // 2MHz clock rate
cs=0;
acc.write(0x31); // data format register
acc.write(0x0B); // format +/-16g, 0.004g/LSB
cs=1;
cs=0;
acc.write(0x2D); // power ctrl register acc.write(0x08);
// measure mode cs=1;
while (1) { // infinite loop
wait(0.2);
cs=0;
acc.write(0x80|0x40|0x32); // RW bit high, MB bit high,
plus address for (int i = 0;i<=5;i++) {
buffer[i]=acc.write(0x00); // read back 6 data bytes
}
cs=1;
data[0] = buffer[1]<<8 | buffer[0]; // combine MSB and
LSB data[1] = buffer[3]<<8 | buffer[2]; data[2] =
buffer[5]<<8 | buffer[4];
x=0.004*data[0];
y=0.004*data[1];
z=0.004*data[2]; // convert to floating point
pc.printf("x = %+1.2fg\t y = %+1.2fg\t z = %+1.2fg\n\r",
x, y,z); //print to screen
}
}
Ȋȱ Exercise 2: Experiment with advanced configuration parameters for the ADXL345.
» For example, the following configuration code will set the data rate to measure
at 3200 Hz:
cs =0 ;
acc.write (0 x2C); // data rate register
acc.write (0 x0F); // set to 3200Hz
cs =1 ;
478ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

» Similarly, the following configuration will set the measurement range to ±2g:
cs =0 ; // active low
acc.write (0 x31); // data format register
acc.write (0 x08); // format +/ - 2 g, 0.004g/LSB
cs =1 ;
» A number of other features including tap detection, freefall detection and
threshold exceedance interrupts can also be configured with the ADXL345

9.18 INTERFACING THE NOKIA 6610 LCD DISPLAY WITH THE MBED

Ȋȱ The mobile screen has 10 pins and can be connected to the mbed as shown

+3.3V BL + (5 – 7V)
GND RST
CS
SIO/MOSI
CLK
Nokia 6610

Nokia 6610 Pin mbed Pin


+3.3V 40
GND 1
BL+ 39
RST 16
CS 15

MOSI 11
CLK 13
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ479

Ȋȱ Exercise 3: Display text typed into the terminal application on to the LCD screen.
Use the # key to clear the screen of the text you have written.
» You’ll need to define the following screen_setup function to set a background
colour and clear the screen:
void screen_setup(void) { // define a function called
screen_setup lcd.background(0x0000FF); // set the background
colour
lcd.cls(); // clear the screen
}
» You’ll also need to import the MobileLCD library from http://mbed.co.uk/
projects/cookbook/svn/MobileLCD/tests/MobileLCD.
» Note also that the cursor can be moved to a chosen position to allow you to
choose where to display data, for example:
lcd.locate (3 ,1); // move cursor to row 1 column 3
// solution for SPI Exercise 3
#include "mbed.h"
#include "MobileLCD.h“ //include the Nokia
display library
MobileLCD lcd(p11, p12, p13, p15, p16); //mosi,miso,clk,cs,rst
Serial pc(USBTX, USBRX); // host terminal
comms setup
char c; // char variable for keyboard input
void screen_setup(void); // function proptotype
int main()
{
pc.printf("\n\rType something to be displayed:\n\r");
screen_setup(); // call the screen
setup function
while(1){
c = pc.getc(); // c = character
input from computer keyboard
wait(0.001);
if (c=='#')
{ // perform the following if "#"
is pressed screen_setup(); //call the screen setup fn
lcd.locate(0,0); // move the cursor back to
row 0 column 0
}
Else
{ lcd.printf("%c",c); // print character
on the LCD screen pc.printf("%c",c); //
print character on the terminal screen
}
}
}
480ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

void screen_setup(void)
{ // define a function called screen_setup
lcd.background(0x0000FF); // set the background
colour
lcd.cls(); // clear the screen
}

9.19 TIMERS AND 32-BIT ARM MBED PROGRAMMING


Using the mbed Ticker object

The Ticker interface is used to set up a recurring interrupt to repeatedly call a designated
function at a specified rate.
Timer is an object, which required the main code to continuously analyse the timer
to determine whether it was the right time to execute a specified function.
An advantage of the ticker object is that we don’t need to read the time, so we can
execute other code while the ticker is running in the background and calling the attached
function as necessary.
The mbed ticker object can also be used for scheduled programming.

Ticker A Ticker is used to call a function at a recurring interval


Functions Usage
attach Attach a function to be called by the Ticker, specifying the interval in seconds
attach Attach a member function to be called by the Ticker, specifying the interval in
seconds
attach_us Attach a function to be called by the Ticker, specifying the interval in microseconds
detach Detach the function

Ȋȱ Exercise : Use two tickers to create square wave outputs.


Ȋȱ Use an LED or an oscilloscope on the mbed pins to check that the two tickers are
executing correctly.
#include " mbed.h "
Ticker flipper1;
Ticker flipper2;
DigitalOut led1(p5);
DigitalOut led2(p6);
void flip1() { // flip 1 function
led1 = !led1;
}
void flip2() { // flip 2 function
led2 = !led2;
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ481

}
int main() {
led1 = 0;
led2 = 0;
flipper1.attach(&flip1, 0.2); // the address of the
// function to be attached
// and the interval (sec)
flipper2.attach(&flip2, 1.0);
// spin in a main loop
// flipper will interrupt it to call flip
while(1) {
wait(0.2);
}
}

Hardware interrupts

Microprocessors can be set up to perform specific tasks when hardware events are
incident.
This allows the main code to run and perform its tasks, and only jump to certain
subroutines or functions when something physical happens, e.g., a switch is pressed or
a signal input changes state.
Interrupts are used to ensure adequate service response times in processing.
The only real disadvantage of interrupt systems is the fact that programming and
code structures are more detailed and complex.

External interrupts on the mbed

External interrupts on the mbed:

InterruptIn A digital interrupt input, used to call a function on a rising or falling edge
Functions Usage
InterruptIn Create an InterruptIn connected to the specified pin
rise Attach a function to call when a rising edge occurs on the input
rise Attach a member function to call when a rising edge occurs on the input
fall Attach a function to call when a falling edge occurs on the input
fall Attach a member function to call when a falling edge occurs on the input
mode Set the input pin mode

Note: any digital input can be an interrupt except pin 19 and pin 20
482ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Exercise 4: Use the mbedInterruptIn library to toggle an LED whenever a digital


pushbutton input goes high.
#include "mbed.h"
InterruptIn button(p18); // Interrupt on digital pushbutton input
p18
DigitalOut led1(p5); // digital out to p5
void toggle(void); // function prototype
intmain() {
button.rise(&toggle); // attach the address of the toggle
} // function to the rising edge
void toggle() {
led1=!led1;
}

Switch debouncing for interrupt control

Exercise 4 doesn’t work quite as expected; it is possible for the button to become
unresponsive or out of synch with the LED.
This is because of a common issue called switch or button bouncing. When the button
is pressed it doesn’t switch from low to high, there is some ‘bounce’ in between as
shown below:

Ideal switch Actual switch


response response

It is therefore easy to see how a single button press can cause multiple interrupts and
hence the LED can get out of synch with the button.
We therefore need to ‘debounce’ the switch with a timer feature.
Exercise 5: Use the mbedInterruptIn library to toggle an LED whenever a digital input
goes high, implementing a debounce counter to avoid multiple interrupts.
#include "mbed.h"
InterruptIn button(p18); // Interrupt on digital pushbutton input
p18
DigitalOut led1(p5); // digital out to p5
Timer debounce; // define debounce timer
void toggle(void); // function prototype
intmain() {
debounce.start();
button.rise(&toggle); // attach the address of the toggle
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ483

} // function to the rising edge


void toggle() {
if (debounce.read_ms()>200) // only allow toggle if debounce
timer
led1=!led1; // has passed 200 ms
debounce.reset(); // restart timer when the toggle is performed
}
By removing the bounces, the system acts as though the switch has an ideal response.
This can be done by a variety of hardware and software methods.

Ideal switch Actual switch


response response

Ȋȱ Debouncer two cross-coupled NAND gates form a very simple Set-Reset (SR) latch.
Another example of a software debouncer would be to look for a number of sequential
readings of the switch, e.g., if the input changes from 0 to 1 and then continues to read
1 for the next ten samples then the switch has been pressed.

REFERENCES

1. http://www.noritake-itron.com/pages/ (quick specs)


2. http://www.noritake-itron.com/Specs/CU-U/CU16025-UW6J-02.pdf (full specs)
3. http://www.noritake-itron.com/Specs/CU-U/CU16025-UW6J_e01-c5.pdf
4. http://mbed.org
5. NXP LPC17xx user manual: http://www.standardics.nxp.com/products/lpc1000/
all/
6. NXP LPC17xx data sheets: http://www.standardics.nxp.com/products/lpc1000/all
7. ARM Cortex-M3 technical reference manual: http://infocenter.arm.com/help/
index.jsp?topic=/com.arm.doc.ddi0337g/index.html
8. FORMIKE KWH0151DN01-061A 128X128 color display specification. Supplied as
pdf.
9. SITRONIX ST7637 display driver data sheet (as used on above display module).
Supplied as pdf.
10. National Semiconductor DP83848C phyter Ethernet phy datasheet: http://www.
national.com/pf/DP/DP83848C.html
11. Cirrus Logic CS42L51 audio codec data sheet: http://www.cirrus.com/en/products/
pro/detail/P1088.html
12. Web server taken from Dr. Bhupendra Rathar’s pdf Devi Ahilya University,
Indore.
484ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

13. David Brash, The ARM Architecture Version, ARM. White Paper, January 2002.
14. Brian W. Kernigan and Dennis M. Ritchie, The C Programming Language (ANSI),
2nd ed, Prentice Hall, 2001.
15. Tao Lin, Hai Zhao, Jiyong Wang, Guangjie Han and Jindong Wang, An Embedded
Web Server for Equipment, School of Information Science & Engineering,
Northeastern University, Shenyang, Liaoning, China.
16. Yanzheng LI, Shuicai WU, Jia LI and Yanping BAI, The ECG Tele-monitor Based
on Embedded WebServer, Biomedical Engineering Center, Beijing University of
Technology Beijing, China.
17. Hong-Taek Ju, Mi-Joung Choi and James W. Hong, An efficient and lightweight
embedded Web server for Web-based network element management, International
Journal of Network Management, pp. 261 – 275, Oct 2000.
18. Nick Witchey, Designing an Embedded Web Server, Applied Computing
Technologies, Applied Computing Technologies, April 2000.
19. Kyle Norman, Integrating Web Servers in Embedded Applications, Luminary
Micro Applications Engineer, Luminary Micro Wild Basin, Suite 350, Austin.
20. CACH Petr and FIEDLER Petr, Ethernet Interface in Application, Department of
˜—›˜•ȱŠ—ȱ —œ›ž–Ž—Š’˜—ǰȱ›—˜ȱ—’ŸŽ›œ’¢ȱ˜ȱŽŒ‘—˜•˜¢ǰȱ˜ċŽ»Œ‘˜ŸŠǰȱ£ŽŒ‘ȱ
Republic.
21. Ian S. Schofield, David A. Naylor, Instrumentation Control Using the Rabbit 2000
Embedded Microcontroller, Astronomical Instrumentation Group, Department of
Physics, University of Lethbridge, 4401 University Drive West, Lethbridge, Alberta,
T1K 3M4, Canada.
22. Andrew S. Tanenbaum, Computer Networks, Addison Wesley, Vol. 3, 2004.
23. ST Electronics, STR91xF ARM9®-based Microcontroller Family – Reference
Manual”, September 2006.
24. Jean J. Labrosse, MicroC/OS-II: The Real Time Kernel”, 2nd ed, R & D Publications,
1992.
25. Deitel, Harvey M. and Michael S. Kogan, The Design of OS/2, 2nd ed, Addison-
Wesley, 1992.
26. Mi-Joung Choi, Hong-Taek Ju, Hyun-Jun Cha, Sook-Hyang Kim and J. Won-Ki
Hong, An Efficient Embedded Web Server for Web-based 24- Network Element
Management”, Dept. of Computer Science and Engineering, Pohang, Korea.
27. Krithi Ramamritham, John A. Stankovic, Scheduling Algorithms and Operating
Systems Support for Real-Time Systems, Proceedings of the IEEE, Vol.82, No. 1,
pp. 55-67, Jan. 1994.
28. http://www.st.com (August)
29. Degen, L., Mander, R., Salomon, G. (1992), Working with Audio: Integrating
Personal Tape Recorders and Desktop Computers. Human Factors in Computing
Systems, Proc. CHI’92. New York: ACM, pp. 413-418.
’›– Š›Žȱ ›˜›Š––’—ȱ œ’—ȱȱ ‹Žȱ ’Œ›˜Œ˜—›˜••Ž›ȱ ǭȱ •˜žȱ ˜–™’•Ž›ȳ485

30. Dubberly, H. & Mitch, D., The Knowledge Navigator, Apple Computer, Inc.
videotape, 1987.
31. Ehn, P., Kyng, M., Cardboard Computers: Mocking-it-up or Hands-on the Future.
In Design at Work: Cooperative Design of Computer Systems, eds Greenbaum,
J., and Kyng, M., Hillsdale, NJ: Lawrence Erlbaum. pp. 169-195, 1991.
32. Erickson, T., Notes on Design Practice: Stories and Prototypes as Catalysts for
Communication. In Envisioning Technology: The Scenario as a Framework for
the System Development Life Cycle, ed. Carroll, J., Addison-Wesley, 1995.
33. Hill, C., Software Design for Interactive Engineering Simulation, Doctoral Thesis,
Imperial College of Science, Technology and Medicine, University of London,
1993.
34. Hill, C., Crampton Smith, G., Curtis, E., Kamlish, S., Designing a Visual Database
for Fashion
Designers, in Human Factors in Computing Systems, Adjunct Proc. INTERCHI’93,
New York, ACM, pp. 49-50, 1993.
35. Scaife, M., Curtis, E., Hill, C., Interdisciplinary Collaboration: A Case Study of
Software Development for Fashion Designers, Interacting with Computers, Vol.6.
No. 4, pp. 395-410, 1994.
36. Schrage, M. (1996). Cultures of Prototyping. Bringing Design to Software, ed. T.
Winograd, USA, ACM Press. pp. 191-205, 1996.
37. Wong, Y.Y., Rough and Ready Prototypes: Lessons from Graphic Design, Human
Factors in Computing Systems, Proc. CHI’92, Posters and Short Talks, New York,
ACM, pp. 83-84. 23235njj, 1992.

REVIEW QUESTIONS

1. Write short note on:


(i) Hardware development using ARM MBED platform?
(ii) Software development using ARM MBED compiler?
2. Write the features of ADCs built inside LPC 1768 based ARM MBED Board?

ANSWERS

1. The MBED HDK (Hardware development kit) provides full microcontroller


sub-system design files and firmware for building development boards and
products that benefit from the native support of MBED SDK. The HDK specifies
all support components and circuits including the MBED on board interface
design that provides simple USB drag-n-drop programming and CMSIS-DAP
debug interface for the target microcontroller. Development boards that are
already based on the HDK are the quickest way to get started with MBED platform.
486ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The MBED SDK (Software development kit) is an open source C/C++ micro-
controller software platform, relied upon tens of thousands of developers to build
projects fast. The MBED SDK has been designed to provide enough hardware
abstraction to be intuitive and concile yet powerful enough to build complex
projects. It is built on the low-level ARM CMSIS API, allowing you to code down
to the metal if needed.
2. LPC 1768 features and terminologies
Ȋȱ 512 KB of on-chip FLASH
Ȋȱ 64 KB of on-chip SRAM
Ȋȱ 10\100 Ethernet MAC with external PHY interface.
Ȋȱ USB host/device OTG controller and PHY. USB2, full speed
Ȋȱ 125 digital audio interface
Ȋȱ 3 12C interfaces
Ȋȱ 2 SSP interface
Ȋȱ 1 SPI interface
Ȋȱ 2 CAN interfaces
Ȋȱ 8-channel, 12-bit on-chip APC
Ȋȱ 10-bit on-chip DAC
Ȋȱ PWM generation
Ȋȱ Quadratic encoder interface
Ȋȱ 4 GP timers
Ȋȱ Ultra-low power real-time-clock
Ȋȱ Upto 70 GPI0 pins
10 GUI DESIGNS USING Qt A C++ TOOLKIT

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ How to use open source Qt Creator & Designer to build C++ program GUI.

10.1 INTRODUCTION

Computer users today expect to interact with their computers using a graphical user
interface (GUI). C++ can be used to write GUI programs ranging from simple applets
which run on a web page to sophisticated stand-alone applications.
GUI programs differ from traditional ‘straight-through’ programs that you have
encountered. One big difference is that GUI programs are event-driven. That is, user
actions such as clicking on a button or pressing a key on the keyboard generate events,
and the program must respond to these events as they occur. And, of course, objects
are everywhere in GUI programming. Events are objects. Colors and fonts are objects.
GUI components such as buttons and menus are objects. Events are handled by instance
methods contained in objects. So, GUI programming is object-oriented programming.
Qt package provides a cross-platform, complete integrated development environment
(IDE) for application developers to create GUI applications for multiple desktop and
mobile device platforms.
First, let’s go through the basic introduction of the terms we used.

10.1.1 Qt

Qt is a cross-platform development framework written in C++. It is a cross-platform


application and UI framework for developers using C++ or QML, a CSS & JavaScript
like language. Qt Creator is the supporting Qt IDE. Qt Cloud Services provides connected
application backhand features to Qt applications.
Qt, Qt Quick and the supporting tools are developed as an open source project
governed by an inclusive meritocratic model. Qt can be used under open source (GPL
v3 and LGPL v2.1) or commercial terms. It supports the following systems:
Ȋȱ Linux
Ȋȱ Mac OS X
Ȋȱ Windows
Ȋȱ Symbian
488ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

10.1.2 C++

C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980s
and is based on the C language. The ‘++’ is a syntactic construct used in C (to increment
a variable), and C++ is intended as an incremental improvement of C. Most of C is a
subset of C++, so that most C programs can be compiled (i.e., converted into a series of
low-level instructions that the computer can execute directly) using a C++ compiler.
C is in many ways hard to categorise. Compared to assembly language it is high-level,
but it nevertheless includes many low-level facilities to directly manipulate the computer’s
memory. It is, therefore, an excellent language for writing efficient ‘systems’ programs.
But for other types of programs, C code can be hard to understand, and C programs
can, therefore, be particularly prone to certain types of error. The extra object-oriented
facilities in C++ are partly included to overcome these shortcomings.

10.1.3 GUI

In computing, a graphical user interface (GUI) is a type of interface that allows users
to interact with electronic devices through graphical icons and visual indicators such as
secondary notation, as opposed to the text-based interface, typed command labels or
text navigation. GUIs were introduced in reaction to the perceived steep learning curve
of the command-line interface (CLIs), which require commands to be typed on the
keyboard.
The actions in a GUI are usually performed through direct manipulation of the
graphical elements. In addition to computers, GUIs can be found in hand-held devices
such as MP3 players, portable media players, gaming devices and smaller household,
office and industry equipment. The term ‘GUI’ tends not to be applied to other
low-resolution types of interfaces with display resolutions, such as video games, or not
restricted to flat screens, like volumetric displays because the term is restricted to the
scope of two-dimensional display screens able to describe generic information.

10.2 Qt CREATOR

Qt Creator is an integrated development environment (IDE) that provides with tools to


design and develop applications with the Qt application framework. Qt is designed for
developing applications and user interfaces once and deploying them across several
desktop and mobile operating systems. Qt Creator provides with tools for accomplishing
your tasks throughout the whole application development life cycle, from creating a
project to deploying the application on the target platforms.
Some of the features of Qt Creator are as follows:
Ȋȱ Cross-platform Development: One of the major advantages of Qt Creator is that
it allows a team of developers to share a project across different development
platforms with a common tool for development and debugging.
Ȋȱ Creating Projects: But why do you need projects? To be able to build and run
applications, Qt Creator needs the same information as a compiler would need.
This information is specified in the project build and run settings.
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ489

Ȋȱ Code Editor: As an IDE, Qt Creator differs from a text


editor in that it knows how to build and run applications.
It understands the C++ and QML languages as code, not
just as plain text.
Ȋȱ Adding Libraries: In addition to Qt libraries, you can
link your application to other libraries, such as system
libraries or your own libraries. Further, your own
libraries might link to other libraries.
Ȋȱ Designing User Interfaces: Qt Creator provides two
integrated visual editors, Qt Quick Designer and Qt Designer.
Ȋȱ Building: Qt Creator is integrated with cross-platform systems for building
automation: qmake and CMake. In addition, you can import generic projects that
do not use qmake or CMake and specify that Qt Creator ignores your build system.
Ȋȱ Testing: If you install Qt Creator as part of Qt SDK, the GNU Symbolic Debugger
is installed automatically, and you should be ready to start debugging after you
create a new project. However, you can change the setup to use debugging tools
for Windows, for example. You can connect mobile devices to your development
PC and debug processes running on the devices.
Ȋȱ Debuggers: Qt Creator is integrated to several external native debuggers. You can
use the Qt Creator Debug mode to inspect the state of your application while
debugging. You can interact with the debugger in several ways.
Ȋȱ Code Analysis Tools: The memory available on devices is limited, and you should
use it carefully. Qt Creator integrates Valgrind code analysis tools for detecting
memory leaks and profiling function execution. These tools are only supported
on Linux and Mac OS, but you can run them remotely from Windows. You must
download and install them separately to use them from Qt Creator.

10.3 Qt DESIGNER

Qt Designer is a tool for designing and implementing user interfaces built with the Qt
multi-platform application development framework. Qt Designer makes it easy to
experiment with user interface design. At any time you can generate the code required
to reproduce the user interface from the files Qt Designer produces, changing your
design as often as you like.
Qt Designer helps you build user interfaces with layout tools that move and scale
your widgets (controls in Windows terminology) automatically at runtime. The resulting
interfaces are both functional and attractive, comfortably suiting your user’s operating
environments and preferences. Qt Designer supports Qt’s signals and slots mechanism
for type-safe communication between widgets. Qt Designer includes a code editor which
you can use to embed your own custom slots inside the generated code. Those who
prefer to separate generated code from handcrafted code can continue to use the
subclassing approach pioneered in the first version of Qt Designer.
490ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

10.4 CREATING A PROJECT IN Qt

First, start the Qt Creator through terminal (Ctrl+Alt+t) by the command ‘qtcreator &’,
this will open the Qt Creator window as follows:
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ491

Then on clicking ‘Create Project’, a small window will appear o choose ‘Qt GUI
application.’

Set the project name and location.


492ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

After this, it will ask for the name of class, and it will name the ‘.h’, ‘.cpp’ and ‘.ui’ files
itself as same of the class. After clicking on ‘Next’ click on ‘Finish’.

Now the Qt Creator window will open the project as follows:


 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ493

Here, clicking on different formats (.h, .cpp & .ui) appearing in the ‘File System’ wizard
we can open the project in that format, like shown in .h and .ui format. In .h format, a
namespace ‘ui’ is created which will be used in the program for constructing the GUI
objects.
494ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Now, for creating a simple application like a button on the window appears in .ui format,
drag ‘Push button’ form buttons in the layout table into the main window. By using
the properties of this object one can change its text and size etc. Similarly, we can
drag-out ‘Label’ form display widgets. It will appear as shown below:

Now if one wants to perform an action by clicking on the button, right click on the
button and press ‘go to slot’. The window appears as shown below:
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ495

Then select the option ‘clicked()’ and press ‘OK’. It will give the following outcome:

Here one can see that ‘pushButton_clicked()’ option is generated in the C++ code. Now
define the following statement in that option,
ui->label->setText(“Everything is fine”);
It means that in namespace ‘ui’ we introduced a pointer named ‘label’ and linked
with another pointer ‘setText’. This will ensure that on clicking the button, the label will
show that ‘Everything is fine’.
496ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Click on ‘Build’, which will build all the interfaces. For running this program, click on
the option named ‘Run’ on the left side of the main window. This will ask for saving
all programs after saving all programs, the final window comes automatically, and it
looks like:

Now if we click on the button, it appears as follows and an executable file is also created.

10.4.1 Using Signals and Slots

One can also use signals and slots to perform some other action. For doing so, first drag
out ‘progress bar’ and ‘Horizontal slider’ from ‘display widgets’. Then select them and
click on ‘lay out vertically’.
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ497

Now click on ‘Edit signal/slot’.

Click and drag out from slider to progress bar as follows:


498ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Now if one will run it then the slider and progress bar will couple. Changing one of
them can automatically change the value of other.

10.4.2 Arithmetic Calculator Development

For developing a simple arithmetic calculator, first start a new project and go into ‘.ui’
format of this project. Now insert an image as a background of the arithmetic calculator.
For inserting image, drag down a ‘label’ in the main window like shown in the following
figure.

Now go into ‘.cpp’ format of this project and there in main window (here calcWindow
in example), write the following text there:
ui->setupUi (this);
QPixmap pix(“home/neer/desktop/light_wooden_background.jpg”);
ui->label->setPixmap(pix);
where in the second line there is a variable pix for the image (given path) is declared.
In the third line, this image is related to the label so that it can appear in the place of
label. This looks as follows in the ‘.cpp’ format.
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ499

Now, on running this project the following main window appears:

Now for creating the arithmetic calculator we have to drag-drop some basic object in
‘.iu’ format window like ‘label’, ‘push-button’ and ‘like-edit’ and rename then by double
clicking or through properties widget as shown in below.
500ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Now right click on ‘A+B’ button and click on ‘add-on ‘ and select the ‘click()’ option.
This will open the project in ‘.cpp’ format. Now write this small C++ code in ‘voide
calcWindow’
{
double a,b,c;
a=ui->lineEdit->text().todouble();
b=ui->lineEdit_2->text().todouble();
c=a+b;
ui->lineEdit_3->setText(QString::number);
}
This will appear as shown:
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ501

Now on running this project, we can add up numbers putting on A and B graphically,
as shown:

Similarly, we can configure minus (-), multiply (*) and division (/) through same method.
Below is the C++ code:
Voide calcWindow::on_pushButton_clicked();
{
double a,b,c;
a=ui->lineEdit->text().todouble();
b=ui->lineEdit_2->text().todouble();
c=a+b;
ui->lineEdit_3->setText(QString::number(c));
}
Voide calcWindow::on_pushButton_2_clicked();
{
double a,b,c;
a=ui->lineEdit->text().todouble();
b=ui->lineEdit_2->text().todouble();
c=a-b;
ui->lineEdit_3->setText(QString::number(c));
}
Voide calcWindow::on_pushButton_3_clicked();
{
double a,b,c;
a=ui->lineEdit->text().todouble();
b=ui->lineEdit_2->text().todouble();
502ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

c=a*b;
ui->lineEdit_3->setText(QString::number(c));
}
Voide calcWindow::on_pushButton_4_clicked();
{
double a,b,c;
a=ui->lineEdit->text().todouble();
b=ui->lineEdit_2->text().todouble();
c=a/b;
ui->lineEdit_3->setText(QString::number(c));
}
When one write this in ‘.cpp’ format window, the window appears as follows:

Now, it will work for all kind of operations. But after performing an operation, we need
to clear window, write the following code for button ‘Clear’.
Voide calcWindow::on_pushButton_5_clicked();
{
ui->lineEdit->setText(QString::number(0));
ui->lineEdit_2->setText(QString::number(0));
ui->lineEdit_3->setText(QString::number(0));
}
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ503

When we run the project then the following calculator window appears:

10.4.3 Nuclear Binding Energy Calculator Development

Nuclear binding energy is an important information about the nuclei in the field of
nuclear physics. So it’s very good to have a tool which can provide the information
about binding energy per nucleon. In Qt Creator, we can develop such application easily
using simple C++ code. For this, first we have to insert some image and object like
‘LineEdit’, ‘PushButtion’ etc. for entering the values of ‘Z’, ‘A’ and calculating value.
After inserting the same the ‘.ui’ window will appear as follows:
504ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Go to the ‘add-on’ option of the button ‘calculate’ and write following C++ code in the
‘.cpp’ format:
ui->setupUi (this);
QPixmap pix(“home/neer/desktop/pic.jpg”);
ui->label->setPixmap(pix);

Voide binding_Energy :: on_pushbutton_clicked()


{
double z, A, E, av, as, ac, aa ;

av=15.8;
as=18.3;
ac=0.714;
aa=23.2;

z=ui->lineEdit->text().toFloat();
A=ui->lineEdit_2->text().toFloat();

E= (av*A)-(as*pow(A.0.66))-(ac*((z*z)/(pow((A,0.33))))-
(aa*((pow((A(z*z)),2))/(A)));
E=E/A;

ui->lineEdit_3->setText(QString::number(E));
}
This will appear as follows in ‘.cpp’ format,
 ȱ Žœ’—œȱ œ’—ȱ ȱ Šȱ ƸƸȱ ˜˜•”’ȳ505

For clear button following C++ code has to be written in ‘.cpp’ format of the project, so
that the new calculation can be done in the same calculator window.
Voide calcWindow::on_pushButton_2_clicked();
{
ui->lineEdit->setText(QString::number(0));
ui->lineEdit_2->setText(QString::number(0));
ui->lineEdit_3->setText(QString::number(0));
}
So, finally the ‘.cpp’ window will appear as follows:

On running this project following Binding Energy Calculator appears:


506ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

REFERENCES

1. qt-project.org
2. En.wikipedia.org
3. C++ Notes by C. A. Bertulani ([email protected])
4. http://www.slideshare.net

REVIEW QUESTIONS

1. Difference between Qt creator & Qt designer?


2. Brifly tell the function of signals & slots in Qt?

ANSWERS

1. Qt Creator
(i) Qt creator is an integrated development environment (IDE) that provides tools
to design and develop applications with the Qt application framework.
(ii) Qt creator provides with tools for accomplishing your tasks throughout the whole
application development life cycle, from creating a project to deploying the
application on the target platforms.
(iii) One of the most major advantages of Qt creator is that it allows a team of
developers to share a project across different developments platforms with a
common platform for development and debugging.
Qt designer
(i) Qt designer is a tool for designing and implementing user interfaces built with
the Qt multi platform application development framework.
(ii) Qt designer maker it easy to experiment with user interface design.
(iii) Qt designer helps you build user interface with layout tools that move and scale
your widgets automatically at runtime.
2. One can also use signals and slots to perform some other action. For doing so,
first drag out progress bar and ‘horizontal slider’ from display widgets. Then
select them and click on ‘layout vertically’.
Now click on ‘Edit Signal/slot’ and click and drag out from slider to progress bar
as follows:
Now if one will run it, then the slider and progress bar will couple. Changing
one of them can automatically change the value of other.
INTRODUCTION TO WEB AUTOMATION
11 BASICS, H/W ACCESSORIES

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Ping Utility
Ȋȱ Web Server
Ȋȱ IP address and IP forwarding
Ȋȱ Wi-Fi
Ȋȱ Network switch
Ȋȱ Routers
Ȋȱ Team viewer
Ȋȱ Solid state relays
Ȋȱ Controlling machine with network switch

11.1 INTERNET NETWORKING


11.1.1 Ping

It is a basic Internet program that allows a user to verify whether an IP address exists,
and to test the reachability of a host in the Internet protocol. The name ping is adopted
from active sonar technology – an active sonar uses a sound transmitter and a receiver.
It produces a pulse of sound, often called a ‘ping’, and then listens for the reflection of
the sound which is produced by this sonar by hitting an object. Likewise, ping operates
by sending Internet Control Message Protocol (ICMP) echo request packets to the target
host and waiting for an ICMP response. In this process, it measures the time duration
from the transmission to the reception and records any packet loss in the process. The
results of this process are printed in the form of a statistical summary of the response
packets received, including the minimum, maximum, and the mean round-trip times,
and sometimes the standard deviation of the mean. Ping is abused as a simple form of
denial-of-service attack in the form of a ping flood in which the attacker overwhelms
the victim with ICMP echo request packets.
History: This administrator’s utility programme was authored by Mike Muuss in
December 1983 using ICMP echo packets for IP network diagnosis and measurements.
Mike named it after his inspiration of the principle of echo-location in sonar technology.
508ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

He had done a lot of modeling of sonar and radar systems in his college days. Host
discovery/pin scanning/ping sweep is a feature of network scanning tools, such as nmap,
wire shark, etc.
Message format of ICMP: Routers in the Internet networking use this protocol to send
error or control information to their hosts. This protocol is of great importance for system
administrators. This protocol is a classic example of a client-server application. The
fundamental job of this protocol is to report problems with the delivery of IP datagram
(see Fig. 11.1).
The generic composition of an ICMP 32-byte packet is given below:
1. Header
2. ICMP header
Ȋȱ Type of ICMP message (8 bits)
Ȋȱ Code (8 bits)
Checksum (16 bits) is calculated with the ICMP part of the packet (the IP header
is not used). It is the 16-bit sum of the ICMP message starting with the Type field.

Figure 11.1 Sample ping test on Ubuntu desktop

Ȋȱ Header data (32 bits) field, which in this case (ICMP echo request and replies), is
composed of an identifier (16 bits) and sequence number (16 bits).
3. ICMP payload
4. Data transportation

11.1.2 Web Server

Web servers are systems of computers that do service by delivering web pages. Every
web server has an identity called the IP address, and also possibly a domain name. In
this service, the web server fetches the page and sends it to the client which requested
the data over the Internet. Any computer can act as a server by installing a server
software and connecting the machine to the Internet.
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ509

This service happens via HTTP, the underlying network protocol used to distribute
information on the World Wide Web. The primary function of a web server is to store,
process and deliver web pages to clients over HTTP. A user agent, like Mozilla Firefox
initiates a communication by making a request for a specific resource using the HTTP
protocol and the server responds to it by sending the requested content or an error
message, if unable to do so. Many generic web servers support SSP using ASP, PHP,
or other scripting languages as well (Fig. 11.2).

Figure 11.2 ICMP packet diagram

Web servers always may not be used for serving the World Wide Web. They can also
be found embedded in devices such as printers, routers, webcams and serving only a
local network. The web server is also used as a part of a system for monitoring and
administering the device in question. This means that no additional software is needed
at the client computer since only a web browser is required (Fig. 11.3).
Domain name: A group of computers and devices on a network that is administered
as a unit with common rules and procedures. Within the Internet, domains are defined
by the IP address. All devices sharing a common part of the IP address are said to be
in the same domain.
In database technology, domain refers to the description of an attribute’s allowed
values. The physical description is a set of values the attribute can have, and the semantic,
or logical description is the meaning of the attribute.
510ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.3 Working of a web server

IP address: Every computer that communicates over the Internet is assigned an IP


address that uniquely identifies the device and distinguishes it from other computers
on the Internet. An IP address is an identifier for a computer or device on a TCP/IP
network. Networks using the TCP/IP protocol route messages based on the IP address
of the destination. To view your IP address, you can use the ipconfig (IPCONFIG)
command line tool. Ipconfig displays all current TCP/IP network configuration values
and refreshes the Dynamic Host Configuration Protocol (DHCP) and Domain Name
System (DNS) settings.
The format of an IP address is a 32-bit numeric address written as four numbers
separated be periods. Each number can be in the range 0 to 255. For example, 1.160.10.240
could be an IP address. Within an isolated network, you can assign IP addresses at
random as long as each one is unique. However, connecting a private network to the
Internet requires registered IP addresses (called Internet addresses) to avoid duplicates.
An IP address can be static or dynamic. A static IP address will never change, and it is
a permanent Internet address. A dynamic IP address is a temporary address that is
assigned each time a computer or device accesses the Internet. An IP address is an
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ511

identifier for a computer or device on a TCP/IP network. Networks using the TCP/IP
protocol route messages based on the IP address of the destination. An IP address
consists of 32 bits, often shown as 4 octets of numbers from 0 to 255 represented in the
decimal form instead of the binary form. For example, the IP address 168.212.226.204
in binary form is 10101000.11010100.11100010.11001100. But it is easier for us to remember
decimals than binary numbers, so we use decimals to represent the IP addresses when
describing them. However, the binary number is important because that will determine
the class of network the IP address to which it belongs.

11.1.3 Two Parts of an IP Address

An IP address consists of two parts, one identifying the network and the other identifying
the node, or the host.
The class of the address determines which part belongs to the network address and
which part belongs to the node address. All nodes on a given network share the same
network prefix but must have a unique host number.
Class A network: In a Class A network, the binary address starts with 0. Therefore, the
decimal number can be anywhere from 1 to 126. The first 8 bits (the first octet) identify
the network and the remaining 24 bits indicate the host within the network. An example
of a Class A IP address is 102.168.212.226, where ‘102’ identifies the network and
‘168.212.226’ identifies the host on that network.
Class B network: In a Class B network, the binary addresses start with 10. Therefore,
the decimal number can be anywhere from 128 to 191. The number 127 is reserved for
loopback and is used for internal testing on the local machine. The first 16 bits (the first
two octets) identify the network and the remaining 16 bits indicate the host within the
network. An example of a Class B IP address is 168.212.226.204 where ‘168.212’ identifies
the network and ‘226.204’ identifies the host on that network.
Class C Network: Binary addresses in this class start with 110. Therefore, the decimal
number can be anywhere from 192 to 223. The first 24 bits (the first three octets) identify
the network and the remaining 8 bits indicate the host within the network. An example
of a Class C IP address is 200.168.212.226 where ‘200.168.212’ identifies the network and
‘226’ identifies the host on that network.
Class D Network: In a Class D network, the binary address starts with 1110. Therefore,
the decimal number can be anywhere from 224 to 239. Class D networks are used to
support multicasting.
Class E Network: In a Class E network, the binary address starts with 1111. Therefore,
the decimal number can be anywhere from 240 to 255. Class E networks are used for
experimentation. They have never been documented or utilized in a standard way.

11.1.4 IP Addressing

The primary job of IP is delivering messages between devices, and like any good delivery
service, it can’t do its job too well if it doesn’t know where the recipients are located.
512ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Obviously then, one of the most important functions of the IP is addressing. IP addresses
are used not only to identify IP addresses uniquely but also to facilitate the routing of
IP datagrams over internetworks. They are used and referred to extensively in TCP/IP
networking.
In this chapter, I shall provide a comprehensive explanation of the issues and
techniques associated with IP addressing. There are five subsections. The first provides
an overview of IP addressing concepts and issues. The second discusses the original
class-based (‘classful’) IP addressing scheme and how the different classes work. The
third and fourth subsections are devoted to IP subnets and subnet addressing. This
includes a discussion of subnetting concepts and also a thorough illustration of practical
step-by-step subnetting. The last subsection describes the new classless addressing
system, also sometimes called ‘supernetting’.

11.1.5 IP Forwarding

IP routing is an umbrella term for a set of protocols that determine the path that data
follows in order to travel across multiple networks from its source to its destination.
Data is routed from its source to its destination through a series of routers, and across
multiple networks. The IP routing protocols enable routers to build up a forwarding
table that correlates final destinations with next hop addresses (Fig. 11.4).
These protocols include:
Ȋȱ BGP (Border Gateway Protocol)
Ȋȱ IS-IS (Intermediate System-Intermediate System)
Ȋȱ OSPF (Open Shortest Path First)
Ȋȱ RIP (Routing Information Protocol)

Figure 11.4 Example of a routing table in Ubuntu

When an IP packet is to be forwarded, a router uses its forwarding table to determine


the next hop for the packet’s destination (based on the destination IP address in the IP
packet header), and forwards the packet appropriately. The next router then repeats
this process using its own forwarding table, and so on, until the packet reaches its
destination. At each stage, the IP address in the packet header has sufficient information
to determine the next hop; no additional protocol headers are required.
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ513

The Internet, for the purpose of routing, is divided into autonomous systems (ASs).
An AS is a group of routers that are under the control of a single administration and
exchange routing information using a common routing protocol. For example, a corporate
intranet or an ISP network can usually be regarded as an individual AS. The Internet
can be visualized as a partial mesh of ASs. An AS can be classified as one of the following
three types.
A stub AS has a single connection to another AS. Any data sent to, or received from,
a destination outside the AS must travel over that connection. A small campus network
is an example of a stub AS.
A transit AS has multiple connections to one or more ASs, which permits data that
is not destined for a node within that AS to travel through it. An ISP network is an
example of a transit AS.
A multihomed AS also has multiple connections to one or more ASs, but it does not
permit data received over one of these connections to be forwarded out of the AS again.
In other words, it does not provide a transit service to other ASs. A multihomed AS is
similar to a stub AS, except that the ingress and egress points for data traveling to or
from the AS can be chosen from one of a number of connections, depending on which
connection offers the shortest route to the eventual destination. A large enterprise network
would normally be a multihomed AS.
An Interior Gateway Protocol (IGP) calculates routes within a single AS. The IGP
enables nodes on different networks within an AS to send data to one another. The IGP
also enables data to be forwarded across an AS from ingress to egress when the AS is
providing transit services.
Routes are distributed between ASs by an Exterior Gateway Protocol (EGP). The EGP
enables routers within an AS to choose the best point of egress from the AS for the data
they are trying to route.
The EGP and the IGP running within each AS cooperate to route data across the
Internet. The EGP determines the ASs that data must cross in order to reach its destination,
and the IGP determines the path within each AS that data must follow to get from the
point of ingress (or the point of origin) to the point of egress (or the final destination).

11.1.6 Wi-fi Network

‘Wi-Fi’ is a type of wireless networking protocol that allows devices to communicate


without cords or cables. Wi-Fi is technically an industry term that represents a type of
wireless local area network (LAN) protocol based on the 802.11 IEEE network standard.
It is the most popular means of communicating data wirelessly within a fixed location.
Wi-Fi, also spelled Wifi or WiFi, is a local area wireless technology that allows an
electronic device to exchange data or connection to the Internet using 2.4 GHz UHF and
5 GHz SHF radio waves. The Wi-Fi Alliance defines Wi-Fi as any “wireless local area
network (WLAN) product that is based on the Institute of Electrical and Electronics
Engineers’ (IEEE) 802.11 standards”. However, since most modern WLANs are based
on these standards, the term ‘Wi-Fi’ is used in general English as a synonym for ‘WLAN’.
514ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Only Wi-Fi products that complete Wi-Fi Alliance interoperability certification testing
successfully may use the ‘Wi-Fi CERTIFIED’ trademark.
Many devices can use Wi-Fi, e.g., personal computers, video game consoles, smart
phones, some digital cameras, tablet computers and digital audio players. These can
connect to a network resource such as the Internet via a wireless network access point.
Such an access point (or hotspot) has a range of about 20 meters (66 feet) indoors and
a greater range outdoors. Hotspot coverage can comprise an area as small as a single
room with walls that block radio waves, or as large as many square kilometers achieved
by using multiple overlapping access points.
Wi-Fi can be less secure than wired connections (such as Ethernet) because an intruder
does not need a physical connection. Web pages that use SSL are secure, but intruders
can easily detect unencrypted Internet access. Because of this, Wi-Fi has adopted various
encryption technologies. The early encryption WEP proved easy to break. Higher quality
protocols (WPA, WPA2) were added later. An optional feature added in 2007, called
Wi-Fi Protected Setup (WPS), had a serious flaw that allowed an attacker to recover the
router’s password. The Wi-Fi Alliance has since then updated its test plan and certification
program to ensure all newly certified devices could resist attacks.

11.1.7 Router

A router is a specialized computer connected to more than one network running software
that allows the router to move data from one network to another. Routers operate at
the network layer (OSI Model’s Layer 3). The primary function of a router is to connect
networks together and keep certain kinds of broadcast traffic under control. Several
companies make routers, like Cisco (Linksys), Juniper, Nortel (Bay Networks), Redback,
Lucent, 3Com, and HP, just to name a few.
Routers used in networks perform the following functions:
1. Restrict broadcasts to the LAN
2. Act as the default gateway
3. Move (route) data between networks
4. Learn and advertise loop-free paths
Restrict broadcasts to the LAN: Networks (especially Ethernet networks) use broadcast
communication at the physical, datalink and network layer. Network layer broadcasts
are transmissions sent to all hosts using the network layer protocol (usually Internet
Protocol (IP) or IPX). Network broadcast communication is used to communicate certain
kinds of information that make the network function (ARP, RARP, DHCP, IPX- SAP
broadcasts, etc.). Since several devices could attempt to transmit simultaneously and
cause collisions, it is preferred to separate large sets of hosts into different broadcast
domains using a switch, or router. As the number of hosts on the network increases,
the amount of broadcast traffic increases. If too much broadcast traffic is present on the
network, then ordinary communication across the network becomes difficult. To reduce
broadcasts, a network administrator can break up a network with a large number of
hosts into two smaller networks. Broadcasts are then restricted to each network, and
the router performs as the ‘default gateway ‘ to reach the hosts on the other networks.
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ515

Act as the default gateway: In modern networks, people are connected to the Internet
day in and out. When your computer wants to talk to a computer on another network,
it does so by sending your data to the default gateway (your local router). The router
receives your data, looks for the remote address of that far-off computer, makes a routing
decision, and forwards your data to a different interface that is closer to that remote
computer. There could be several routers between you and the remote computer, so
several routers will take part in handling the packet, much like a firefighter’s bucket
brigade.
Move (route) data between networks: Routers have the capability to move data from
one network to another. This allows two networks managed by different organizations
to exchange data. They create a network between them and exchange data between the
routers on that network. Because a router can accept traffic from any kind of network
it is attached to, and forward it to any other network, it can also allow networks that
could not normally communicate with each other to exchange data. In technical terms,
a token ring network and an Ethernet network can communicate over a serial network.
Routers make this possible. A router can take in an Ethernet frame, strip the Ethernet
data off, and then drop the IP data into a frame of another type such as SDH/SONET,
PDH/T1, ATM, and FDDI. In this way, a router can also perform ‘protocol conversion’,
provided it has the appropriate hardware and software to support such a function. The
whole point, however, is to forward the data from the interface it receives data from,
to another interface that retransmits the received data onto another interface serving
another network.
Learn and advertise loop-free paths: Routers can only learn and advertise routes
dynamically if they are using a routing protocol such as RIP, OSPF, EIGRP, IS-IS or
BGP. Otherwise, we have to configure the routes by hand, which is called static routing.
Routing moves data on a hop-by-hop basis, what is often called ‘hot potato’ routing. If
a set of routers ends up passing the data around in a circle, without reaching the
destination, it’s called a ‘routing loop’. Packets get tossed around the loop until they
die of old age: their ‘time to live’ counter in the IP datagram is decremented as it passes
through each router and eventually it reaches zero and is discarded.

11.1.8 TeamViewer

TeamViewer is a proprietary computer software package for remote control, desktop


sharing, online meetings, web conferencing and file transfer between computers. Versions
are available for Microsoft Windows, OS X, Linux, iOS, Android, Windows RT and
Windows Phone operating systems. It is also possible to access a machine running
TeamViewer with a web browser. While the primary focus of the application is remote
control of computers, collaboration and presentation features are included. TeamViewer
can be used without charge by non-commercial users. Business, premium and corporate
versions are available. TeamViewer GmbH was founded in 2005 in Uhingen, Germany.
Permira acquired TeamViewer GmbH from GFI in 2014.
TeamViewer may be installed with an installation procedure, although the ‘Quick
Support’ version will run without installation. To connect to another computer,
TeamViewer has to be running on both machines. To install TeamViewer, administrator
516ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

access is required, but once installed any user can run it. When TeamViewer is started
on a computer, it generates a partner ID and password (user-defined passwords are
also supported). To establish a connection between a local client and a remote client,
TeamViewer generated ID and password of either client are required. The local client
requires the remote client’s ID and password to gain control over the remote client,
whereas the remote client requires the local client’s ID and password to gain control
over the local client (Fig. 11.5).

Figure 11.5 TeamViewer window

To start an online meeting, the presenter gives a Meeting ID to the participants. They
join the meeting by using the TeamViewer full version or by logging on to and entering
the Meeting ID. It is also possible to schedule a meeting in advance. TeamViewer uses
RSA private/public key exchange (2048-bit) and AES (256-bit) session encryption. In the
default configuration, TeamViewer uses one of the servers of TeamViewer.com to start
the connection and the routing of traffic between the local client and the remote host
machine. The software then determines how to establish a connection. In 70% of the
cases, after the handshake a direct connection via UDP or TCP is established; the other
connections are routed through TeamViewer GmbH’s router network (via TCP or
HTTP-tunneling).
Advantages: Although a quite complex application, TeamViewer is very easy to use,
thanks to its simple and intuitive approach to any task. This way, connecting to and
controlling a remote machine is not only easy to accomplish, but also quite fast. Since
you can run TeamViewer from its mounted volume, you do not need to install the app
for a one-time use. Following the same pattern, the remote control isn’t necessary if you
just want to transfer files (this is extremely useful if you are low on resources).
The ‘Meeting’ mode will also prove to be a lifesaver if you need to make a presentation
or work on a project while having your team scattered all over the world.
Disadvantages: The TeamViewer documentation is focused mainly on the Windows
application without at least stating which features are not yet available on other platforms.
The TeamViewer connections are secure, and you can limit the access by implementing
confirmation messages and modifying the access rights, but, to do that, you must know
what you should look for and where. TeamViewer does not warn you in any way about
how vulnerable you become once a connection is established and how you can take
minimal precautions at least.
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ517

11.2 HARD DRIVERS


11.2.1 Driver Circuits

A typical digital logic output pin can only supply tens of milliampere of current. Even
though they might require the same voltage levels, small external devices such as high-
power LEDs, motors, speakers, light bulbs, buzzers, solenoids, and relays can require
hundreds of MA. Larger devices might even need several amps. To control smaller
devices that use DC, a transistor-based driver circuit can be used to boost the current
to the levels required by the device. When the voltage and current levels are in the
correct range, the transistor acts like a high-current switch controlled by the lower current
digital logic signal. A discrete BJT is sometimes used instead of a newer MOSFET
transistor especially on older or low voltage circuits as shown below. On mbed, any
GPIO pin could be used for the logic control input to the circuit with Digital Out (Fig.
11.6).

Figure 11.6 Basic driver circuit using a BJT transistor

The transistor primarily provides current gain. PNP, NPN, or MOS transistors can
Š•œ˜ȱ ‹Žȱ žœŽǯȱ ‘Žȱ ›Žœ’œ˜›ȱ žœŽȱ ˜—ȱ ‘Žȱ ‹ŠœŽȱ ˜ȱ ‘Žȱ ›Š—œ’œ˜›ȱ ’œȱ ¢™’ŒŠ••¢ȱ Š›˜ž—ȱ ŗȱ ̛ǯȱ
On inductive loads (i.e., motors, relays and solenoids), a diode is often connected
backward across the load to suppress the voltage spikes (back EMF) generated when
turning the devices off. (Recall, on an inductor V=L×di/dt, so a negative voltage spike
is produced when turning the device off.) Sometimes the diode is also connected across
the transistor instead of the load (this protects the transistor). The 2N3904 shown below
(Fig. 11.7) is a small discrete BJT transistor that can be used for a driver circuit needing
less than 200 mA. In this circuit with BJTs, Vcc can also be a higher voltage supply than
the logic power supply. Often 6 or 12 V DC is needed for motors or relays. In battery
operated devices, the load may be directly connected to the battery power and not
passed through the voltage regulator. Many devices such as motors have a momentary
large inrush current spike when they are first turned on and have a larger stall current,
so be a bit conservative on the maximum current ratings.
518ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.7 2N3904 transistor in a TO-92 package

Depending on the current gain of the transistor used, some adjustments may be
needed in the value of the base resistor. A high gain TO-92 transistor such as the ZTX689B
can drive up to 2 A at up to 12 V in this circuit. A Darlington transistor pair contains
two BJT transistors connected together for a higher current gain. If a Darlington transistor
in a TO-92 package such as a ZTX605 is used in the driver circuit, outputs of 1 A to 100
V are possible. At high current levels, the transistor might get a bit hot. Transistors can
even get too hot and burn out if the circuit is not designed correctly. The transistor has
to dissipate the power (V×I) across its C-E junction (i.e., the switch point) as heat. This
means that the transistor should either be completely ‘on’ (saturation) or ‘off’ (cutoff)
to minimize heat dissipation and maximize efficiency. Larger power transistors have
metal tabs on the case that can be connected to a heat sink for cooling. The pins on
larger power transistors are often too large for standard breadboards, and the spacing
is not always compatible.

11.2.2 PWM Control

The logic signal (control) turns the transistor on and off to drive high current loads. For
motor speed control or dimming lights, a digital PWM output signal is typically used
for control instead of an analog output. Digital PWM is more energy efficient than analog
as it significantly reduces the heat dissipated by the transistor (i.e., it is always completely
‘on’ or ‘off’). For motors, the PWM clock rate is typically in the tens of KHz range. For
lighting, it needs to be greater than 50 Hz or perhaps 100 Hz. Early studies for electric
power systems showed that many people got headache caused by lighting systems that
use less than 50 Hz AC even if they do not directly perceive a flicker. A Class-D amplifier
uses PWM to drive audio speakers, and the PWM clock rate is typically around ten
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ519

times the highest frequency of the audio signal. A low-pass filter is sometimes added
to the output. The mbed PWMout Handbook page shows an example using PWM to
dim an LED. Even when using PWM, some large transistors may require a heatsink for
proper cooling. If the transistor gets too hot to touch, it will need a larger heatsink.
Noise issues from high current loads: Switching high current inductive loads and motor
arcing can put noise spikes or voltage surges on power supply lines, and it is possible
that they can become large enough or that the supply voltage could momentarily drop
low enough when turning on a large inductive load to cause a microprocessor to crash
and even reset when using the same power supply as the load. So additional power
supply decoupling capacitors may need to be added near the high current load, or a
separate power supply can be used for the high current load.
If high voltage spikes, surges, or electrostatic discharge (static electricity) are a
potential issue, transient-voltage-suppression (TVS) diodes (also known as transorbs)
or varistors (also known as MOVs) are sometimes connected across a high current
load or the high voltage supply lines for even more protection. MOVs are typically
found in AC surge protector outlet strips. A wide variety of these devices is available
in different voltage and current ranges. These devices typically clip off voltage spikes
above a fixed threshold voltage. It is common to pick a transorb or MOV with a
clip-off threshold voltage a bit higher than the normal operating range found in the
circuit (>20%). Activated transorbs or MOVs have to dissipate the energy in the clipped
off voltage spike, and they are typically rated by the amount of energy that they can
absorb before overheating and burning out, so the duration of the overvoltage spike
needs to be relatively short.

11.2.3 Driver ICs

As an alternative to using discrete transistors, special purpose driver ICs are also available
that can drive multiple devices. These ICs contain several internal transistor driver
circuits similar to the one just described above. A small number is still available in a
DIP package that can plug into a breadboard such as the ULN2803 8-channel 500 mA
50 V driver seen below, but most new ones are surface mount ICs and require a breakout
board for use on a breadboard (Fig. 11.8).

Figure 11.8 ULN2803 8-channel Darlington driver DIP IC


520ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.9 TLC5940 16-channel PWM driver

The TI TLC5940 is a 16-channel driver IC with 12-bit duty cycle PWM control (0-4095),
6-bit current limit control (0-63), and a daisy chainable serial interface (SPI). The maximum
drive current is 120 mA per output. It is handy for expanding the number of high current
drive PWM outputs available. This IC was originally targeted for driving LED arrays.
The 16 PWM outputs might sound like a lot, but a humanoid robot might need over
twenty to control all of the servo motors used in the joints. In addition to the DIP package
seen above, it is also available in surface mounts. Sparkfun makes the breakout board
seen below using the surface mount package. A TLC5940 code library is available for
mbed. Driver ICs may also require heatsinks or other cooling considerations when used
at high current levels (see Fig. 11.9 & 11.10).

Figure 11.10 Sparkfun TLC5940 breakout board

Devices that require several amperes of current will need a more complex driver
circuit with larger power transistors on heatsinks, and more than one transistor current
amplification stage may be required. It is not advisable or reliable in the long term to
connect several small BJT transistors in parallel to increase the current output provided
by the driver circuit. A larger power transistor must be used. Driver circuits can be built
using small discrete transistors such as the TO-92 size 2N3904 on a standard breadboard.
If still a higher current drive is needed, the larger power transistors used will not fit
directly on a breadboard, and the wires are not large enough. Having these devices
already assembled on a small PCB will save prototyping time with mbed, so those
options will be the primary focus here.
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ521

For speakers, an audio amplifier IC is often used to drive the speaker. New Class-D
audio amplifiers actually use PWM.

11.2.4 MOSFETs

At higher voltage and high current levels, newer MOSFET transistors are more efficient
than the older BJTs. In BJTs, the base current controls the switch, but in MOSFETs, it is
the gate voltage. A common N-channel RFP30N06LE MOSFET transistor symbol and
pinout is shown below (Fig. 11.11).

Figure 11.11 N-channel MOSFET transistor symbol and TO-220 package pinout

Figure 11.12 Sparkfun MOSFET driver breakout board


522ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The board seen above uses the RFP30N06LE MOSFET transistor rated at 60 V and 30
A for higher current load. The trace size on the PCB and the wire size for the screw
terminals limits loads to around 4 A. Screw terminals are used for high current
connections since the wires need to be larger than the standard breadboard jumper
wires. The schematic is seen in the image below. This special MOSFET has a very low
gate input voltage that works with 3.3 V logic signals like those on mbed.
A typical MOSFET runs just a bit more efficiently if the gate input is a bit higher than
the supply voltage. Special MOSFET driver ICs such as the LTC1155 use a charge pump
circuit to drive the gate voltage higher on higher voltage MOSFET driver circuits using
a normal digital logic level control signal (i.e., useful when load voltage (RAW in the
schematic diagram) is larger than the logic supply voltage). The LTC1155 is used with
a MOSFET in many laptop PCs and cell phones to turn power on and off for power
management and is available in an 8-pin DIP package or surface mount. Overvoltage
and short circuit protection can also be added using the LTC1155. Some large MOSFETs
including the one on the Sparkfun board already contain an internal snubber diode for
driving inductive loads. If this is not the case, it would be a good idea to add an external
diode when driving inductive loads (see Fig. 11.12).

Figure 11.13 MOSFET driver circuit for high current DC loads

Floating inputs:ȱ ˜Žȱ ‘Žȱ ŗŖȱ ̛ȱ ™ž••Ȭ˜ —ȱ ›Žœ’œ˜›ȱ ˜—ȱ ‘Žȱ Œ˜—›˜•ȱ ’—™žȱ •’—Žǯȱ ‘’œȱ
prevents the gate input from floating high and turning on the device when nothing is
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ523

driving the input. If it did float, it is also possible that the MOSFET might oscillate and
overheat. In most cases, the device should be off if something is wrong. This can happen
if a wire was not connected or perhaps briefly connected when the microcontroller is
reset, and GPIO pins reset to input mode. It also might happen if the power supply for
the microcontroller is not on, but another power supply for the device is on. A similar
design issue of leaving control inputs floating in a computer control system in a
hydroelectric power plant once caused a major power blackout in California when power
was lost on the computer (Fig. 11.13).

11.2.5 Wiring

Any DigitalOut pin can be used for control (connects to the control input of the driver
circuit). If you plan using PWM, select one of the mbed PWMOut pins. Keep in mind
that mbed can only supply about 200 mA of current for external devices via USB power,
so an external DC power supply may also be needed for large loads. When using external
DC power supplies for additional power (to RAW in schematic above), only connect the
supply grounds together (and not mbed Vcc and RAW even if the voltage is the same).
Here is an example of a program that turns the transistor switch on and off every 0.2
second. The program can be tried using ARM MBED.
#include “mbed.h”

DigitalOut myled(LED1);
DigitalOut Ctrl(p8);

int main() {
while(1) {
Ctrl = 1;
myled = 1;
wait(.2);
Ctrl = 0;
myled = 0;
wait(.2);
}
}

11.2.6 IGBTs

The insulated gate bipolar transistor (IGBT) is a new type of semiconductor device used
as an electronic switch in modern designs that combine high efficiency and fast switching.
It is used in medium and high power applications such as appliances, electric cars,
trains, variable speed refrigerators, air conditioners, stereo systems that use switching
amplifiers, and even welding machines. They can be connected in parallel to make
524ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

devices with ratings up to 6000 V and hundreds of amperes. It has an isolated gate FET
as the control input of a BJT (Fig. 11.14).

Figure 11.14 IGBT schematic symbol

The IGBT module seen above is used to switch the drive motor in hybrid cars. It
contains six IGBTs (3-phase AC motor with a variable frequency drive using PWM) and
is rated at 800 A/650 V. A wide array of IGBT modules is available ranging from several
amperes to several thousand amperes and in this range they can be more energy efficient
than power MOSFETs (Fig. 11.15).

Figure 11.15 Infineon hybrid car IGBT switch module

11.2.7 Special Purpose Driver ICs

As an alternative to using several discrete power transistors mounted on a PCB, multiple


driver circuits are often packaged in ICs targeted for particular applications to save
space and reduce cost. Two of the most common examples are motor and LED driver
ICs.

11.2.8 H-Bridge Driver ICs

To control and reverse a DC motor, an H-bridge circuit is used with two control signals
and four driver transistors. This allows the current direction through the load to be
reversed similar to swapping the wires on a DC motor (Fig. 11.16).
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ525

Figure 11.16 Basic H-bridge driver for DC motor control

The basic H-bridge circuit with four power transistors that provide drive current for
the motor is seen above. In this circuit, you can think of the power transistors functioning
as on/off switches. Two digital logic level inputs, forward and reverse, turn diagonal
pairs of transistors on and off to reverse the current flow through the DC motor (M).
In this basic circuit, forward and reverse must not both be turned on at the same time,
or it will short the power supply. More advanced H-bridge circuits prevent this issue
and add a dynamic brake feature. MOSFETs are often used in modern H-bridge ICs
instead of BJTs, for example, code using an H-bridge driver to control the direction of
a DC motor. It also uses digital PWM for motor speed control. Small H-bridge modules
are available on breakout boards.

Figure 11.17 Pololu or Sparkfun 1.2A MOSFET dual H-bridge breakout board
526ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The small breakout board seen above uses Toshiba’s TB6612FNG dual H-bridge motor
driver IC, which can independently control two bidirectional DC motors or one bipolar
stepper motor. A recommended motor voltage of 4.5–13.5 V and peak current output
of 3 A per channel (1 A continuous) make this a handy motor driver for low-power
motors. Many small robots have two DC drive motors controlled by a dual H-bridge
driver with PWM speed control. The Sparkfun magician robot cookbook page has code
examples for mbed. Higher current H-bridge modules are also available (Fig. 11.17).
The speed of DC motors varies with the load, and will also vary a bit from motor to
motor even on identical motors. For accurate speed control under varying loads, feedback
is typically required. Three cookbook projects, QEI, PID, and mbed Rover provide some
additional background on how to use feedback for more accurate speed control of DC
motors.

11.2.9 Stepper Motor Driver ICs

Stepper motors have multiple coil windings that need to be activated in the current
sequence to rotate the motor shaft by a fixed angle without the need for position feedback
hardware. Stepper motors are used in devices to provide low-cost, accurate position
control (i.e., moving the print head on an inkjet printer). Stepper motor driver ICs contain
an H-bridge driver for each winding and often also include a small state machine or
counter to sequence through the correct states to drive the motor. The typical control
inputs are step and direction. The newest stepper motor driver ICs can respond to a
variety of complex commands that even include the capability to move fractions of a
step using PWM or perhaps move multiple steps automatically. The Pololu stepper
motor driver breakout board seen below will drive a bipolar stepper motor up to 2 A
per coil using the Allegro A4988 DMOS microstepping driver IC. An example library
to control stepper motors is available in the cookbook. A wide variety of stepper motor
driver ICs is available (see Fig. 11.18).

Figure 11.18 Pololu stepper motor driver breakout board


—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ527

11.2.10 LED Driver ICs

High-power bright LEDs require more current than the typical digital logic output pin
can provide, and they need a driver circuit. The small module seen below contains the
Allegro A6281 IC with three 150 mA driver circuits for a high-power red, green and
blue (RGB) LED. It also includes PWM dimming hardware for each of the three driver
circuits, and it can generate 230 different colors and brightness levels. Code examples
for mbed can be found on the Shiftbrite cookbook page. The modules can be chained
together to build large LED arrays. With the rapid growth of LED lighting, quite a few
LED driver ICs are available (Fig. 11.19).

Figure 11.19 Shiftbrite RGB LED driver breakout board

11.3 RELAYS AND SOLID STATE RELAYS


11.3.1 Relays

Relays can also be used to switch high current and/or high voltage AC and DC devices
using logic signals for control (Fig. 11.20).

Figure 11.20 Electromechanical relay


528ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

An electromechanical relay contains an electromagnetic coil (right side of the image


above) that moves a metal arm to make and break an electrical connection.
Electromechanical relays can be used to switch high current and also AC devices. They
provide electrical isolation between the control signal and the load and are relatively
low cost. No common ground connection between the control signal and the load is
needed. A standard digital logic GPIO output pin does not supply enough current to
drive a relay coil directly. When using logic signals to control a relay, a driver circuit
must be used to boost the current needed to energize the relay’s electromagnetic coil.
The load is switched on and off using the relay’s metal contacts that move when the
coil is energized. Since the metal contacts actually touch, relays will have a lesser voltage
drop across the switch point than transistor circuits. They are sometimes used to switch
regulated power supplies on and off. Relays tend to be more resistant to failure caused
by high voltage surges than semiconductor devices.
Electromechanical relays do have some limitations for designers to consider:
Ȋȱ The number of lifetime on/off cycles is limited by mechanical wear (typically 106
to 107 cycles).
Ȋȱ They have slow on/off times – around 20 per minute, too slow for motor speed
control or dimming lights.
Ȋȱ Relay contacts can wear out due to arcing on inductive loads (perhaps as few as
105 cycles) even on rated loads.
Ȋȱ Oxidation on relay contacts can be a problem on low voltage analog signals.
(around 2 V is needed to punch initially through the oxidation layer that occurs
between any two metal contacts).
Ȋȱ Worn out relays will sometimes stick due to mechanical wear and an audible click
is typically heard during switching.
If a relay is being used to switch high current AC loads, the relay’s contact life can
be greatly extended by turning it off near an AC zero crossing. This requires a zero
crossing detection circuit for synchronization to the AC supply or a driver circuit that
always turns off near zero such as a TRIAC or SSR.
Many relays and solenoids are rated only for ‘intermittent duty’. This means that
they should only be turned ‘on’ for short periods of time and ‘off’ for the vast majority
of the time. If left ‘on’ for long, the coil wire will overheat, and it can melt through the
thin insulation on the tiny coil wires and destroy the device. In an application that needs
to leave a relay or solenoid turned ‘on’ for long or undetermined periods of time a
device is needed that is rated for ‘continuous duty’.

Figure 11.21 Sparkfun relay board with driver


—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ529

Sparkfun makes a low-cost relay board shown above that contains both the relay and
the required driver circuit built using a discrete transistor. The relay coils on this relay
require around 200 mA at 5 V DC. It is easier to drive relays like this that use a lower
coil voltage. The relay board’s driver circuit is built using a BJT as seen in the schematic
diagram below. The relay can switch up to 220 V AC at 20 A using a logic signal for
control, but the small PCB layout and screw terminals are likely to limit it to a lower
voltage and current levels to at least half of these ratings. A similar board is available
from Sparky’s Widgets. It is probably wise to be very conservative on the maximum
voltage and current ratings quoted for relays in datasheets (Fig. 11.22).

Figure 11.22 Sparkfun relay board schematic

The snubber diode backward across the relay coil absorbs the reverse voltage inductive
spike that occurs when turning off the coil (i.e., V=Ldi/dt).
Any digital out pin can be used to control the relay (connects to the input of the relay
driver circuit).
Safety note on high voltages: A high voltage power line shorted to a digital logic circuit
on a breadboard can blow up an entire computer system, or cause electrocution if
touched. For safety, keep the wires for any high voltage and/or high current devices
well away from the breadboard and do not touch them when power is on. Even a
momentary wire short can blow things up. An inline fuse and even a GFI breaker is not
a bad idea. Long before a standard household AC circuit breaker trips, electronic parts
will blow out with a short. Make sure that the bottom side of the PCB does not short
out on any metallic surfaces. Breadboard contacts and small jumper wires only handle
about one amp. The relay boards typically use screw terminals to attach the larger wires
needed for the external device. Just driving the coil of a large relay requires most of the
additional current that can be supplied to mbed via the USB cable, so an external DC
power supply will likely be needed to power the relay coils and the load of the external
device. For electrical isolation, when using a relay to control external AC devices or
high voltage DC devices, do not connect the grounds on the power supplies from the
control side to the load side.
530ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Here is an example program that turns the relay on and off every 2 seconds.
#include “mbed.h”
DigitalOut myled(LED1);
DigitalOut Ctrl(p8);
int main() {
while(1) {
Ctrl = 1;
myled = 1;
wait(2);
Ctrl = 0;
myled = 0;
wait(2);
}
}
A demo using mbed with this code example for the Sparky’s Widget relay breakout
board is available at http://mbed.org/users/4180_1/notebook/relay-breakout-boards/.
For safety and especially if you do not have prior experience working with high
voltage AC, one of the sealed devices such as the Power Switch Tail II seen below would
be a safer alternative to switch small household AC devices. It has an internal switch
module, and the high voltage connections are all enclosed in the case. Standard AC
plugs are already attached, and international versions of the Power Switch Tail are also
available. The US version is also available from Sparkfun. A code example for mbed is
available at http://mbed.org/users/4180_1/notebook/powerswitch-tail-ii/ (Fig. 11.23)

Figure 11.23 The Power Switch Tail II has an internal driver and relay circuit with
the standard AC plugs for the US

Figure 11.24 Power Switch Tail II – schematic diagram


—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ531

(Fig. 11.24) In the schematic above, A1 is a VO2223 0.9 A 600 V optically isolated
TRIAC (Phototriac) in a DIP package that is used to drive the mechanical relay. Note
that it also has two MOVs included for surge suppression. It addition to the standard
relay version, a Power Switch Tail with a solid state relay (SSR) is also available. SSRs
and TRIACs will be explained in a later section. The small Phidgets dual relay board
seen below works in a similar manner to the Sparkfun board, but it has two relays (Fig.
11.25).

Figure 11.25 Phidgets dual relay board

Relays need to be selected based on both the input and output current and voltage
rating. Since contacts can wear out on the output side be conservative on current ratings.

11.3.2 Reed Relays

Figure 11.26 A small reed relay module in a DIP package


532ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

A reed relay is a type of relay that uses an electromagnet to control one or more reed
switches. The contacts are of magnetic material, and the electromagnet acts directly on
them without requiring an armature to move them. Sealed in a long, narrow glass tube,
the contacts are protected from corrosion and are usually plated with silver. As the
moving parts are small and lightweight, reed relays can switch much faster than relays
with armatures. They typically switch lower current values than a large relay. They are
mechanically simple, making for a bit more reliability and longer life. The coil current
needed is lower (perhaps 10 mA @ 5 V) and in some cases, a driver circuit may not be
needed if the digital logic output has high drive current. Some reed relays contain a
snubber diode. If not, an external back EMF snubber diode would still be a good idea.
Many are small enough to come in a DIP package that can plug into a breadboard (Fig.
11.26).

11.3.3 Solid State Relays

In many applications, solid state relays can be used instead of electromechanical relays.
Solid state relays (SSRs) offer several advantages over electromechanical relays (Fig.
11.27). These are:
Ȋȱ Most have optical isolation between input and output load
Ȋȱ No moving parts - built using semiconductors
Ȋȱ Some are fast enough for motor speed control and dimming lights
Ȋȱ Resistant to shock and vibration
Ȋȱ Around 100 times more reliable than mechanical relays
Ȋȱ Silent during operation

Figure 11.27 Sparkfun solid state relay board


—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ533

The schematic is shown below for the Sparkfun SSR board seen above. It uses a Sharp
SSR module and can switch 125 V AC at 8 A (AC only and not DC). Note that it also
requires a driver circuit and the external wire connections are the same as the relay
board. A demo for mbed is available at http://mbed.org/users/4180_1/notebook/
ssr-breakout-boards/ (Fig. 1.28).

Figure 11.28 Sparkfun solid state relay board schematic diagram

11.3.4 Optical Isolation

Optical or mechanical isolation (relays) between higher voltage supplies and computers
is always a good idea. Not having to connect grounds between supplies helps in noisy
industrial environments. Long wires can also pick up large transient voltages. One of
the first projects to control and instrument an airport ended abruptly when a lightning
bolt from a thunderstorm hit near the end of the runway and the ground wires carried
the ground voltage transient spike all the way back to the control tower and blew up
the computer. Most SSRs have an optoisolator on the input. As seen below, Sparkfun
also makes a small optoisolator breakout board with small driver transistors on the
output to isolate the computer output signals and convert them to higher voltage signals.
It has limited current drive, but it could be added to the input side of a driver circuit
to provide optical isolation. Optoisolators are sometimes also used on sensor inputs to
a computer. In this case, the sensor drives the input side, and the output side connects
to the computer (Fig. 11.29).
534ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.29 Sparkfun optoisolater breakout board

As shown below, the ILD2213T optocoupler IC used on the Sparkfun board contains
two optically coupled pairs consisting of a gallium arsenide infrared LED and an NPN
silicon phototransistor. Signal information, including a DC level, can be transmitted by
the LED via IR (infrared light) to the phototransistor while maintaining 4000 V of
electrical isolation between the input and output. Before reaching 4000 V, other parts
such as wires and connectors will likely short out first. Optoisolators tend to be a bit
slow to switch when compared to the speed of digital logic circuits. This device is in
the five-microsecond range. A few SSRs use reed relays on the input signal or feed the
input through a DC to AC converter with a transformer for electrical isolation (Fig.
11.30).

Figure 11.30 ILD213T dual optocoupler IC


—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ535

11.3.5 Other SSR Modules

Unfortunately, SSR modules typically cost a little more than mechanical relays. Many
SSRs include a zero crossing circuit that turns on or off the device only when the AC
voltage level is zero (a zero crossing). This also helps to reduce RF noise emissions
generated by switching high current loads. The Phidgets SSR board seen below can
switch both AC and DC voltages. It uses a small NEC/CEL SSR IC (Fig. 11.31).

Figure 11.31 Phidgets SSR board

11.3.6 Switching AC

Some solid state relays can also drive AC loads. This is possible using a TRIAC as in
the Sparkfun SSR board schematic given above, with the Sharp SSR module. The TRIAC
symbol looks like two diodes connected in opposite directions as shown below. The
gate control input (G) requires only a few milliamps and the AC load connects to A1
and A2. In the Sharp SSR module, the IR light from the LED drives the TRIAC gate
input (provides optical isolation). A TRIAC’s gate input can be carefully time controlled
in phase with the AC signal to dim lights, control motor speed, or adjust the power
output to the load. Household light dimmer switches often use TRIACs (Fig. 11.32).

Figure 11.32 A TRIAC can switch AC loads

Two MOSFETs with their source pins connected together as in the Phidgets SSR
module with the NEC/CEL SSR IC will also drive AC loads as seen below. The gate
input is optically isolated, and the MOSFETs drain pins connect to the AC load. This
536ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

works since all MOSFETs have a substrate diode that always conducts current in the
reverse direction (only the normal current direction can be switched). Be sure to check
the SSR’s datasheet, as SSRs can be AC only (TRIAC) or AC/DC (have two MOSFETs)
or DC only (one MOSFET) (Fig. 11.33).

Figure 11.33 SSR using two MOSFETs to switch AC loads with optical isolation

The power SSR tail module seen below can be used to dim incandescent or dimmable
LED lights (Fig. 11.34).

Figure 11.34 Power SSR tail includes AC plugs and an SSR in an enclosed case

As seen in the schematic below, it contains a solid state relay built using an optoisolator
with digital logic inputs, a TRIAC for AC switching, and an MOV for surge suppression.
A zero crossing and state detection tail module with isolation are also available (Fig.
11.35).
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ537

Figure 11.35 Power SSR tail schematic diagram

11.3.7 Higher Power SSRs

Opto 22 developed the first SSRs, and today makes a wide variety of DC and AC SSR
modules including the large module below that can switch 480 V AC at 45 A with a 3
V DC logic control input. They are frequently used in industrial automation systems.
Heatsinks may also be needed on SSRs (see Fig. 11.36).

Figure 11.36 Opto 22 480D45 SSR module

11.3.8 Industrial Automation Systems and PACs

Programmable automation controllers (PACs) for industrial automation systems with a


large number of inputs and outputs often mount a customized mixture of relays, AC/
DC SSR modules, and AC/DC isolated input modules on special breakout boards or rail
mount systems with screw terminals. Some SSRs mount directly to the rail. They are
handy whenever there is a large number of external I/Os to hook up with larger wires.
A ribbon cable connector ties the digital I/O signals to the microcontroller. Such packaging
works out well and helps to keep the wiring under control and organized. If a lot of
external devices need to be connected in a prototype, many of these systems can be
adapted for use with small microcontrollers such as mbed.
538ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.37 DIN rail mounting system for SSRs and relays

Figure 11.38 Two types of direct DIN rail mount SSR modules from Crydom and Power IO

Figure 11.39 DIN rail mount optically isolated AC input module


—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ539

Some even have a DIN rail mount expansion board for mbed.

11.3.9 Home Automation Systems

If you only need to control household AC devices, several low-cost home automation
systems are available with small plug-in modules for controlling household AC devices
and dimming lights. X10 is of the first low-cost systems, and it uses signaling over the
power lines to control each module. Switches on each X10 control module are configured
by the user to select a unique address (0...255) for each AC device as seen below. X10
power line control signals are sensitive to distance and noise, and will not crossover
from one power phase to the other, just like home networking plug-in devices. In addition
to a power line interface to decode the control signals, a module contains a relay for
appliances, or a TRIAC to dim lights. A small interface device is available from X10 to
send the control signals over the power line using a microprocessor. An easier to use
RS232 serial interface for X10 can still be found, but it is no longer in production. There
are two mbed X10 projects already available in the mbed cookbook, links to ways to
interface to the X10 power line signals, and code for a wireless interface to the X10
wireless module. The X10 wireless receiver module then sends out the signals on the
power line to control modules (Fig. 11.40).

Figure 11.40 A plug-in X10 appliance module can switch household AC devices
540ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Another home automation system is the Z-wave. It uses RF signals to control the
plug-in AC modules. Insteon uses both power line and RF signals in a mesh network.
One of the controllers from these systems could be interfaced with mbed to use these
modules. WiFi controlled AC outlet strips are also starting to appear such as the one
seen below. These systems work well in homes, but probably would not be appropriate
for use in noisy safety-critical industrial environments (Figs. 11.41 & 11.42).

Figure 11.41 The iRemoTap can be controlled via WiFi

Figure 11.42 The WeMo switch contains a IoT WiFi controlled relay.
A WeMo teardown shows the internal parts
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ541

11.3.10 Power Switches

The Power Switch Tail is a low-cost module designed to switch AC loads such as
household lights and appliances using a digital logic control signal. The US version is
rated at 120 V AC @ 15A. For safety and especially if you do not have prior experience
working with high voltage AC, a sealed device such as the Power Switch Tail II shown
below is a safer alternative to switch small household AC devices rather than building
a high voltage AC circuit on a breadboard or even a small relay breakout board or SSR
breakout board with a bare PCB without a case. It has an internal switch module, and
the high voltage connections are all enclosed in the case. Standard AC plugs are already
attached. International versions of the Power Switch Tail are also available. On the
international version, an extension cord (with the correct plug types for the country)
can be cut in two and soldered or screwed onto the board inside the case, and one of
the two versions is set up for countries with higher voltages. The high voltage
international version (i.e., for 200-240 V AC) has a relay with a higher voltage coil and
higher voltage surge suppression MOVs. The US version is also available from Sparkfun.
Another handy feature is that the internal driver circuit for the relay is set up so that
an external DC power supply is not needed for mbed to drive the relay: the USB power
will suffice. Any digital output pin on mbed will drive it directly (Figs. 11.43 & 11.44).

Figure 11.43 The Power Switch Tail II has an internal driver and relay
circuit with the standard AC plugs for the US

Figure 11.44 Add your own AC plugs to the Power Switch Tail II U international
version kit and attach the cover
542ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.45 Power Switch Tail II schematic diagram

In the schematic above, A1 is a VO2223 0.9 A 600 V optically isolated TRIAC (Phototriac)
in a DIP package that is used to drive the mechanical relay. Note that it also has two
MOVs included for surge suppression. The module can switch up to 120 V AC at 15 A
loads, and the internal relay is rated at 240 V at 40 A. Since a TRIAC drives the relay,
it cannot be used for DC switching (TRIACs work only with AC). Figure 11.45 shows
the PCB inside the case. The two wires attached to the screw terminals (bottom of the
figure) are the digital control signal and logic ground. It will operate off of a 3.3 V or
5 V logic output signal, and it draws about the same current as a small LED. Several
Power Switch Tail modules could be used using mbed’s USB cable power without the
need for an external DC power supply for mbed. The digital connections can be made
without opening the safety case, but here is a view of the PCB inside (see Fig. 11.46).

Figure 11.46 Power Switch Tail II with safety cover off to view PCB

Any DigitalOut pin can be used to control the relay (connects to the input of the relay
driver circuit). Here is an example program that turns the relay on and off every
2 seconds. This program cable tried at using ARM MBED.
#include “mbed.h”

DigitalOut myled(LED1);
DigitalOut Ctrl(p8);

int main() {
while(1) {
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ543

Ctrl = 1;
myled = 1;
wait(2);
Ctrl = 0;
myled = 0;
wait(2);
}
}
The digital output control signal (mbed P8) and a logic ground (mbed gnd pin 1) are
connected using a small screw terminal block built into the case of the Power Switch
Tail. The AC connections use standard AC plugs. The digital signals are optically isolated
from the AC load.

11.4 CONTROLLING MACHINE USING NETWORK/PROPRIETARY


COMPUTER SOFTWARE OR MOBILE WI-FI

11.4.1 Introduction

In this project work a cryogenic machine which is connected to the web server (this is
an ATMEL-ATMEGA168 based tcp/ip stack (visit www.tuxgraphics.org/eledmics/200606-
article 06061shtml)) is controlled through the Internet, Wi-Fi and a proprietary software
called Team Viewer via Ethernet network switch called router. The figure below shows
the schematic diagram (Fig. 11.47).

Proxy Personal Computer


10.0.0.101 with E – Switch
Team Viewer IP – 10.0.0.41
IP - 10.0.7.144

To Internet

wi-
Network Switch

Sureh's
2G mobile
Joby-sir's
At
3G Mobile
Tamil Nadu

With teamviewer
Brower run.
Figure 11.47 Schematic diagram of controlling software by web server, Wi-Fi and by Team Viewer
544ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

A cryogenic engine which has a solenoid coil and relay in it is connected to a web
server. That web server is programmed in order to control the cryogenic engine. The IP
address of the web server is 10.0.0.41. In the schematic diagram, the E-Switch represents
the web server connected with the cryogenic engine. The figure below is the machine
setup where bottom box emitting bright light is the cryogenic engine. The middle box
is the web server having IP -10.0.0.41. The top one is network switch through which
cryogenic engine is controlled. Here, Dlink network switch which has a Wi-Fi facility
is used.
Now the connection is made between the network switch and the personal computer
using an Internet cable, and another connection is made between the network switch
and web server which is inherently connected to the cryogenic machine. Now Internet
proxy settings at the personal computer is changed by adding one more IP address in
the network settings of the PC so that it can handle more than two IP addresses at the
same time. The connection was successfully tested using ping utility program which
showed the successful connection between the computer to the web server via the
network switch (Fig. 11.48).

Figure 11.48 Experimental setup of cryogenic machine with embedded server with network switch

Figure 11.49 Connection between network switch web server and embedded system
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ545

Then two mobiles in which one was directly connected to the Dlink switch via wireless
and connected to the cryogenic server, and the other one in which Team Viewer was
installed to control the PC via ethernet. The Team Viewer software was successfully
installed in the PC as well (see Fig. 11.49).
Then the PC in which Qt designer programme was written in order to run cryogenic
machine via the Internet was successfully tested and the mobile having Team Viewer
was also connected to the personal computer. Then the PC was controlled by the mobile
which had Team Viewer software in it, and the cryogenic machine was tested by a
mobile which had the Team Viewer proprietary software. Another mobile having
connection via a wireless network by the network switch to the web server was also
used to run the machine successfully. The figure below shows the connection between
the PC and cryogenic server directly through the network switch (Figs. 11.50, 11.51,
11.52 & 11.53).

Figure 11.50 Experimental setup of cryogenic machine connected with personal computer

Figure 11.51 Machine’s solenoidal and relay coil is now operated by Qt designer
which is installed in the PC
546ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 11.52 Connection is established between mobile and personal computer

Figure 11.53 The cryogenic engine’s relay is on after the personal computer is
operated through mobile using Team Viewer

11.4.2 Conclusion

In this project, a cryogenic machine which was connected to a web server to operate
from a distance via the Internet was operated successfully. Then this setup was connected
to a network switch with two mobile phones. One phone was connected to the web
server via a network switch which had a Wi-Fi facility and then the other phone was
used to control the PC which had software program (called Qt designer) to operate the
cryogenic machine. The mobile phone which was used to control PC had the Team
Viewer software. The PC was operated by proprietary software installed mobile phone
to switch on/off the cryogenic machine. Finally, the cryogenic machine was successfully
operated by the PC, Wi-Fi connected phone and the proprietary software installed mobile
phone, using a network switch.
—›˜žŒ’˜—ȱ ˜ȱ Ž‹ȱž˜–Š’˜—ȱ Šœ’Œœǰȱ ȦȱŒŒŽœœ˜›’Žœȳ547

REFERENCES

http://tuxgraphics.org/electronics/200905/embedded-tcp-ip-stack.shtml
http://arduino.cc/en/Main/ArduinoEthernetShield
http://stackoverflow.com/questions/23157817/http-vs-tcp-ip-send-data-to-a-web-server
http://en.wikipedia.org/
http://www.ping127001.com/pingpage.htm
http://searchnetworking.techtarget.com/definition/ping
http://en.wikipedia.org/wiki/Ping_%28networking_utility%29
http://www.linuxuser.co.uk/features/internet-control-message-protocol-icmp-explained
http://www.webopedia.com/TERM/W/Web_server.html
http://www.metaswitch.com/wiki/what-ip-routing

REVIEW QUESTIONS

1. What is Ping?
2. Explain MOSFET and IGBTs.
3. What are the advantages of using solid state relay over electromechanical relays?

ANSWERS

1. Ping is networking utility program or a tool to test if a particular host is reachable.


2. MOSFET
It is a metal oxide field-effect transistor where the voltage determines the
conductivity of the device.
IGBT
An insulated gate bipolar transistor is a 3-terminal power semiconductor device,
used as an electronic switch.
3. Advantages of solid state relay
Its ability to switch off AC loads at the point of zero load current, thereby
eliminating the arching and electrical noise.
COMPUTER AUTOMATED MEASUREMENT
12 AND CONTROL (CAMAC) & VME BUS

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ What is CAMAC, why and where it is used?
Ȋȱ A small introduction to VME bus is also discussed at the end of the chapter.

12.1 INTRODUCTION

Incompatible instruments have for many years been a problem


to laboratories and industrial organizations that need to
construct composite instrumentation systems. Lack of
standardization of the mechanical, electrical and data-transfer
interfaces presented by such instruments leads to wasted
design efforts and inefficient system designs. Further wastage
of effort may be incurred if the solution to the interfacing
problems of one installation is not sufficiently general to be
applied to other similar installations.
The CAMAC standard for modular instrumentation
Figure 12.1
systems has been developed to alleviate this problem,
particularly in applications involving computer automated measurement and control.
The standard has gained a wide international acceptance and has been republished by
various national and international standards organizations.

12.1.1 What is CAMAC?

Computer Automated Measurement And Control (CAMAC) is a standard bus and


modular crate electronics standard for data acquisition and control used in nuclear and
particle physics experiments. It is defined by ANSI/IEEE Std 583-1982 Modular
Instrumentation and Digital Interface System, as a standardized instrumentation system
designated CAMAC for computer automated measurement and control. The system
features a fully specified data highway (dataway) together with modular functional units
that are completely compatible and that are available from diverse sources.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ549

Figure 12.2

Data gathering and analysis in experimental sciences has been seen undergoing a
major revolution in the last quarter century due to the appearance of low-cost digital
computers. It has significantly altered the instrumentation around an accelerator or a
nuclear research reactor, which are being increasingly made with a built-in microprocessor.
These inexpensive microprocessors can very easily and rapidly transform raw data into
elaborate computed results in a user-friendly form.
The first internationally accepted standard in nuclear electronics is the well-known
NIM Standard. As digital information began to supplement analog instrumentation in
the nuclear environment, a new standard CAMAC was designed by the ESONE group.
It is now widely used in industrial process control and nuclear instrumentation around
a reactor in an accelerator laboratory.
The use of CAMAC-based systems is favored since one can easily enhance or
reconfigure the system using alternate functional units in the CAMAC crate. The typical
configuration of devices to each other and a computer is uneconomical. The money and
effort expended on such interfacing are immense, and that is the problem which is
alleviated by the CAMAC system.

Figure 12.3

CAMAC is basically a data acquisition system that plays the role between the devices
and a computer. A computer reads the data from a particular device (or a portion of
550ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

the device) through the CAMAC, processes it, and then the CAMAC outputs the
commands of the computer onto the device for proper controlling. Although the primary
application of CAMAC is data acquisition, it may also be used for remotely programmable
trigger and logic applications. The bus allows data exchange between plug-in modules
(up to 24 in a single crate) and a crate controller, which then interfaces to a PC.

12.1.2 Why to Use CAMAC

It would be again very costly if we connect each device individually to the computer.
Also, a large number of ports and a very efficient controlling mechanism would be
required. CAMAC solves these problems. CAMAC instruments are modular function
channel units that are accommodated in a CAMAC crate. The CAMAC crate serves as
the common housing for CAMAC instruments and also provides the dataway for all
the instruments that are inserted in the crate. Hence, CAMAC provides us with an
alternative way to connect hundreds of devices to a computer. It provides efficient data
read/write operations to be performed between computer and devices. Thus, for
networking the devices and further connecting them to the computer, we need data
acquisition systems like CAMAC.

12.1.3 Basic Features of CAMAC

The system has a 1 μs dataway cycle time and a very high addressing capability. The
dataway is parallel, with 24 ‘read’ lines and 24 ‘write’ lines so that words of 24 bits or
less can be handled in a single data transfer. Typically, up to 23 stations can be addressed
within a crate, either singly or in combination with 16 sub-addresses for each station,
together with 32 function codes. This high addressing capability is further multiplied
by 7 in the case of the standard 7-crate parallel highway system, and by 62 in the case
of the standard serial highway.
Assemblies of crates may be interconnected by means of parallel or serial highways.
Modular system with functional plug-in units mounts in the standard crate. It is designed
to exploit high packing density possible with solid state devices. Plug-in units connect
to the data highway (dataway) which is a part of the crate and carries data, control
signals, and power.

Table 12.1 Different number of lines in CAMAC


Read Lines 24
Write Lines 24
Functions(binary coded) 32
Station Address (dedicated) 24
Station Demand (dedicated) 24
Sub-Address (per station address, binary coded) 16
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ551

The maximum word length is 24 bits for a single data transfer. Typically, in a 25
station crate, 23 stations can be addressed or can make demands since two stations are
usually occupied by the crate controller. CAMAC instruments are modular functional
units that are accommodated in a CAMAC crate. A typical CAMAC module is based
on standard 8, ~222 mm high panel and has a single width of 17 mm. The CAMAC
crates serve as the common housing for CAMAC instruments and also provides the
dataway for all the instruments that are inserted in the crate. The instruments receive
digital inputs from and transmit their digital outputs along the dataway.
All stations into which the modular instruments can be inserted are identical except
the control station which is located at the extreme right. This station is reserved for the
crate controller which handles all communications between the instruments and dataway
and also between crates and the computer or other external controllers.

Advantages of CAMAC

1. Flexibility
2. Optimization of systems
3. Ease of restructuring
4. Deferred obsolescence, updating capability
5. High degree of computer independence
6. Reduction of interfaces
7. Ready interchange between installations
8. Reduction of inventories
9. Increased utilizations
10. Ease of re-serviceability
11. Reduction of downtime
12. On the shelf blank modules
13. Reduction of design effort
14. Software economies
15. Availability of numerous compatible instruments from many commercial suppliers

12.1.4 Control Systems for an ion Accelerator: Case Study

Operation of any system can be controlled either locally or remotely, including an


accelerator machine.
Local: In the local control system, the operator has to go near the machine every time
and turn some knob, to change the parameters of a device for the optimum beam
transmission. For example, if a Faraday cup has to be inserted to measure the beam
current, the machine operator has to go near the device to operate it.
552ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 12.4 Manual pots

Figure 12.5 Manual control

Remote: In the remote control system, the operation of any device to optimize its
parameter for maximum beam transmission is done from a remote place. In this method,
the controls of all the devices can be centrally located at any desirable remote location.
It means that there is no need to go near the device. A remote control system can be
implemented in any of the following ways.
Hard-wiring: One way of achieving remote control system is by hard-wiring. This means
that a parallel control panel for every device has to be incorporated in the remote control
console. The operator can change the parameters of the device in the control room and
the same would be reflected in the accelerator. The operator can control the operation
of these devices through this centralized control console. However, while this type of
control console can be used for the operation, it has some shortcomings as explained
below:
1. It requires a lot of panel space.
2. Good quality long cables, which have minimum attenuation have to be laid from
the device controller to remote control console.
3. Modification of the system is usually difficult.
4. Cumbersome and difficult to execute.
Computer controlled: With a large number of equipment scattered over a large area, a
manual control system can become very complex. This is precisely where the introduction
of computer in control system comes into picture.
Such a system
Ȋȱ is fast and easy to control,
Ȋȱ requires less panel space,
Ȋȱ lends safety to instruments, and
Ȋȱ is cost efficient.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ553

Equipment safety can also be taken into account by such a system.


A centralized computer control system can be designed using a number of computers
on the control system. For example, if a computer can control 10 I/O devices, we require
10 computers to control 100 such devices. It means that all the 10 computers will be
used to control the operation of big machines like 15 UD Pelletron accelerator. Therefore,
this kind of arrangements is quite cumbersome and difficult to operate.
Another approach is to have a master knob to control and a set of meters to display.
The master knob can be assigned to any device in the system and so is the meter. What
is needed to implement such a system is an assigning mechanism to select one device,
to control and monitor its function, from the list of the total number of devices.
Communication to outside world by a computer is done through the input/output
ports. Both the memory and input/output ports are accessible by the CPU, each I/O port
has a unique address, i.e., the CPU can access the ports uniquely by the address of that
particular port. One can interface an accelerator to these I/O ports and access them
through software.
Local control vs remote control: Remote control operation is preferred over local control
operations because of the following reasons:
1. Any charged particle under the influence of external forces can emit radiation.
These radiations are harmful to human health if these exceed permissible limit.
If the ion accelerator is operated, using the local system, one has to enter the high
radiation area. This may cause health hazard for the operator. Whereas, in a
remote control system, a centralized control system can be set up where radiation
levels are minimum and are under permissible limits.
2. As the number of devices for control of ion accelerator is large, a centralized
control operation provides ease of operation over the remote control system.
Most suitable control system for heavy ion Pelletron accelerator
The formal type of control system (hard-wired centralized control system) is good for
small accelerators. Such a system is faster and considering the human response time,
this can be suitable for small machines.
But the 15 UD Pelletron accelerator is a big machine, having various devices that need
their parameters to be optimized, in many iterations, to get an optimized accelerated
heavy ion beam of desired beam specification essential for any experiment using
accelerated heavy ion beam. Hence, it would be quite cumbersome to establish this
hard-wired centralized control system. It was here when the need of computer in the
control systems emerged.
For heavy ion accelerators like the Pelletron accelerator at IUAC, we prefer remote
control via a computer. A computer is installed in a remote control room. To the computer,
further devices are connected. This networked control is made possible using a control
system like CAMAC.
554ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

12.1.5 Dataway

The dataway at the rear of a CAMAC crate consists primarily of bused lines that
interconnect the stations and that are utilized to transmit read, write, control and address
information. The dataway also includes power supply line and a limited number of
dedicated lines. The controller addresses specific stations singly or in combination, by
means of dedicated station lines. A second set of dedicated lines is used by the instruments
to alert the controller when they want attention. This interrupt capability is an important
feature of CAMAC that has proved to be of immense value.
In the 25 station crate, 24 are designated ‘normal stations’ and are wired identically.
The wiring of a control station is different from that of the normal stations. Since a crate
controller must have access to read (R) and write (W) lines, it must occupy one normal
station in addition to the control station.
Dataway lines fall into four categories:
(a) All station bus lines linking the corresponding dataway connector contacts at all
normal stations, including the control station.
(b) Normal station bus lines linking the corresponding dataway connector contacts
at all normal stations, but are not connected to the control station (these include
read and write lines).
(c) Individual lines between the control stations and each normal station. There are
two such lines:
Ȋȱ N line by which the control system addresses each specific normal station (station
number line).
Ȋȱ L line (‘look at me’) which is a demand line used by the station to advice the
control it wishes attention of.
(d) Patch contacts (for each station) that are not connected to the dataway and are
available for patch connections.
The instruments within a crate speak a common language with the dataway. The
controller, which also speaks the common dataway language, serves as a translator if
the crate is controlled by a computer.

12.1.6 Highway

The interconnection between the crates and between the crates and a computer and/or
another controller is called a highway. With dedicated crate controllers designed to
interface with specific computers, the highway becomes an extension of the computer
I/O bus.
Highways can be either parallel or serial, single ended or balanced (Figs. 12.6 & 12.7).
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ555

Computer I/O Parallel Crate 1


Branch Driver

Crate 1

Crate 1

Crate 1

Figure 12.6 Block diagram representing parallel highway connection of CAMAC crates

Serial Branch
Computer I/O Crate 1
Driver

Crate 1

Crate 1

Crate 1

Figure 12.7 Block diagram representing serial highway connection of CAMAC crates

Updating installations, such as industrial control systems, has traditionally been very
difficult. Since these difficulties are not present in CAMAC systems, with standardized
multi-source functional units, economical modernizing of CAMAC industrial control
556ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

systems is feasible. The standardization and transportability of software become feasible


with CAMAC systems because of the standardized dataway operations and a high
degree of computer independence. Subroutines for CAMAC are based largely on
compatibility with FORTRAN. External connections to plug-in units may conform to
the digital or analog signal standards of associated transducers, computers, etc. or the
recommended standards.

12.2 DATAWAY LINES

A dataway is a multi-wire assembly at the rear of CAMAC crate that:


(i) interconnects the stations,
(ii) serves as a communication link between the plug-in units within a CAMAC crate,
(iii) provides power to the plug-in units via power buses that are a part of the dataway,
and
(iv) conforms to the requirements for a dataway as specified in ANSI/IEEE, Std 583
1982.
A CAMAC data transfer control operation on the dataway, characterized by the
generation of ‘busy’ and ‘strobe’ signals, is called a dataway operation. There are two
types of dataway operations:
(i) During command operations, the controller generates a command consisting of
signals on individual station number lines to specify one or more modules on
the sub-address bus lines to specify the subsection of the module and on the
function bus lines to specify the operation to be performed.
(ii) During unaddressed operations, there is no command, but the controller generates
one of the common control signals on the initialize or clear bus lines, and this
operates on all modules connected to the bus line.
During the command and unaddressed operations, the controller generates a signal
on the busy bus line. The busy signal is available at all stations to indicate that a dataway
operation is in progress. Two timing signals, strobes S1 and S2, are generated in sequence
on separate bus lines during command operations. Only strobe S2 is mandatory during
unaddressed operations, but S1 may also be generated.

12.2.1 Use of Each Data Line

1. Commands: The state of the signals on the individual station number lines
specifying a module or modules, the four sub-address lines specifying a subsection
of a module, and five function lines constitute a command. The command signals
are accompanied by a signal on the busy bus line, which indicates to all units
that a dataway operation is in progress.
(a) Station Number (N): Each normal station is addressed by a signal on an
individual station number line Ni, which comes from a separate contact at the
control station. The stations are numbered in the decimal form: the left side
is viewed as the front beginning from station 1 (addressed by N1). There is
no restriction on the number of stations that can be addressed simultaneously.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ557

(b) Sub-addresses A8 A8 A4 A1: Different sections of a module are addressed


by signals on the four A bus lines. These signals are decoded in the module
to select one of up to 16 sub-addresses numbered in the decimal from A(0)
to A(15). The sub-address may be used to select, for example, a register within
the module or a feature that is to control the response signal Q, or a section
of the module that is to be operated on by functions such as ‘enable’, ‘disable’,
and ‘execute’.
(c) Function F16 F8 F4 F2 F1: The function to be performed at the specified
sub-address in the selected module is defined by the signals on the five F bus
lines. These signals are decoded in the module to select one of up to 32
functions, numbered in decimal from F(0) to F(31). The function codes are
subdivided into three groups, involving read operations, write operations and
operations with no transfer of data. The standard function codes have defined
actions in modules and controllers. There are also reserved codes, for any
further addition to standard codes where its use is not defined in detail.

Table 12.2 Operation of different function codes


Code Function F16 F8 F4 F2 F1
F0 Read group 1 register 0 0 0 0 0
F1 Read group 2 register 0 0 0 0 1
F2 Read and clear group 1 register 0 0 0 1 0
F3 Read compliment of group 1 register 0 0 0 1 1
F4 Non-Standard 0 0 1 0 0
F5 Reserved 0 0 1 0 1
F6 Non-Standard 0 0 1 1 0
F7 Reserved 0 0 1 1 1
F8 Test Look At Me 0 1 0 0 0
F9 Clear group 1 register 0 1 0 0 1
F10 Clear Look At Me 0 1 0 1 0
F11 Clear group 2 register 0 1 0 1 1
F12 Non-Standard 0 1 1 0 0
F13 Reserved 0 1 1 0 1
F14 Non-Standard 0 1 1 1 0
F15 Reserved 0 1 1 1 1
F16 Overwrite group 1 register 1 0 0 0 0
F17 Overwrite group 2 register 1 0 0 0 1
F18 Selectively set group 1 register 1 0 0 1 0
F19 Selectively set group 2 register 1 0 0 1 1
F20 Non-Standard 1 0 1 0 0
558ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

F21 Selective clear group 1 register 1 0 1 0 1


F22 Non-Standard 1 0 1 1 0
F23 Selective clear group 2 register 1 0 1 1 1
F24 Disable 1 1 0 0 0
F25 Execute 1 1 0 0 1
F26 Enable 1 1 0 1 0
F27 Test Status 1 1 0 1 1
F28 Non-Standard 1 1 1 0 0
F29 Reserved 1 1 1 0 1
F30 Non-Standard 1 1 1 1 0
F31 Reserved 1 1 1 1 1

2. Strobe Signals (S1 and S2): During each command operation, the controllers
generate two strobe signals, S1 and S2, in sequence on two separate bus lines. In
response to these timing signals, plug-in units initiate various actions appropriate
to the command that is present on the dataway.
3. Data: All the information carried by the read and write lines is conveniently
described as data, although it may be information concerned with status or control
features in modules. Information that is transferred to or from a control register
in a module is thus regarded as data. Up to 24 bits may be transferred in parallel
between the controller and the selected module. Independent lines are provided
for read and write directions of transfer.
4. Status Information
(a) Look at me (LAM): The ‘look at me’ lines, like the N lines, are individual
connections from each normal station to separate contacts at the control station.
Any module may generate a signal from its individual line Li to indicate that
it requires attention. Modules that occupy more than one station may indicate
different demands by signals on appropriate L lines. L signal generated by a
module may represent demands for attention originating from more than
LAM source in the module. Individual bits of LAM status register are set by
the corresponding LAM sources and are cleared by appropriate command
and initialize signals.
The LAM requests are examined collectively by reading the state of all LAM
requests (read group 2 at A14), or individually test the LAM with an
appropriate sub-address A(i). The output of this signal as the dataway L signal
is inhibited while the module is addressed by N, possibly in conjunction with
certain F and A codes or group of codes. A module that has generated L=1
must not clear the LAM status register until it receives an appropriate
command or initialize signal. Modules may contain registers for LAM
information. These registers are not mandatory, but if included they should
be accessed as group 2 registers at the following sub-addresses:
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ559

» LAM Status register A(12)


» LAM Mask register A(13)
» LAM Request register A(14)
Corresponding bit positions should be associated with same LAM source. The
state of each data bit read from the LAM status, or LAM request register is
the same as the state of Q response that would be obtained by a test status
or test LAM operation.
The data word read from A(12) should have LAM status information in the
low order bits and may also contain other status information. Each bit of data
word loaded into A(13) should be in the 1 state to enable the corresponding
LAM request and in the 0 state to disable it.
L signals are allowed to be initiated at any time, maintained continuously
and removed in advance of strobes S1 and S2. LAM signals can also be used
for operation synchronization in block transfers.
(b) Busy (B): The ‘busy’ signal B=1 must be generated during each dataway
command operation (when N signals are generated) and during unaddressed
operation (when Z or C are generated). The busy signal is used to interlock
various aspects of a system that can compete for the use of dataway. The
signal B=1 indicates to all units that a dataway operation is in progress.
(c) Response (Q): During every command operation, the addressed module may
generate a signal on the Q bus line to indicate the status of any selected feature
of the module. In read and write operations, the addressed modules must
establish the signal Q=0 or Q=1 before strobe S1 and must maintain it until
at least S2.

Table 12.3 Recommended mode for performing stop mode CAMAC block transfer
Position of
operation
Transfer
Q relative to Module Interface Computer
Direction
block of n
words
Store data word
Data word Pass data word
Read in computer
transmitted keep channel open
memory
Q=1 1 to n
Data word already Data word
Write Data word accepted passed keep already
channel open delivered
No significant data Do not pass data No action
Read
word transmitted word close channel required
Q=0 n+ 1 Close channel data Data word to be
Data word not
Write word already recovered for
accepted
passed retransmission
560ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Table 12.4 Special application mode for performing ‘stop’ on word mode CAMAC
Block transfers
Position of
operation
Transfer
Q relative to Module Interface Computer
Direction
block of n
words
Store data word
Data word Pass data word keep
Read in computer
transmitted channel open
memory
Q=1 1 to n – 1
Data word
Data word Data word already
Write already
accepted passed keep channel open
delivered
Store data word
Data word Pass data word close
Read in computer
transmitted channel
Q=0 N memory
Data word Close channel data word Word already
Write
accepted already passed delivered

There is a risk that the system will lock up if an operation is repeated


indefinitely while waiting for Q = 1. A block of data transfer accompanied by
Q = 1 is followed by at least one Q = 0 to indicate the end of the block.
(d) Command accepted (X): Whenever a module is addressed during a command
operation, it must generate X = 1 on the command accepted bus line if it
recognizes the command as one that is equipped to perform either within the
module or in association with the external equipment. The signal on the X
must reach a steady state before S1 and must be maintained until S2.
(e) Common Controls (Z, C, I): During unaddressed dataway operations, either
initialize Z or clear C is generated by the controller and received by each unit
connected to appropriate bus line.
» Z Initialize: The signal is intended to be used at the system start up. Initialize
must have absolute priority over other signals. In response to Z = 1, all data
and control registers must be reset, and if possible all LAM registers must be
disabled.
» I Inhibit: The signal I = 1 must inhibit any feature to which it is connected in
a module. The designer is free to choose which activities (for example, data
taking) within a module are inhibited by this signal.
» C Clear: The signal C = 1 must clear all registers to which it is connected.
Units that generate C must also initiate a sequence including busy and strobe
S2. The designer is free to choose which registers are cleared in response to
C S2.
(f) Non-standard connections: Five contacts P1-P5 on the dataway connector at
each normal station and seven contacts P1-P7 at the control station are available
for unspecified uses.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ561

12.3 MECHANICAL CHARACTERISTICS


12.3.1 What is Crate

A CAMAC crate is a mounting unit or housing for plug-in units that includes a dataway
and conforms to the standards of ANSI/IEEE. An assembly of crate controller and one
or more CAMAC crate operate in conformity with dataway requirements of ANSI/IEEE.
Each plug-in unit occupies one or more mounting stations in the crate. At each station,
there is an 86-contact connector socket giving access to the CAMAC dataway, a data
highway which forms a part of the crate. The dataway consists mainly of bus lines for
data, control, and power.
A typical dataway operation involves at least two plug-in units, one of which acts as
a controller and other as a controlled module. In this standard, the controller refers to
a unit occupying the control station and at least one normal station. The module refers
to the unit occupying one or more normal stations. Both receive signals from some
dataway lines and generate signals on others.
Note: In practice, there can be special areas of units that combine some properties of a
controller with some properties of a module.

12.3.2 CAMAC Crate

The Model 1502 series of powered CAMAC crate fully complies with the CAMAC
specifications of IEEE-583. The crate includes the CAMAC dataway with an 86-contact
PC edge connector at each station. All units include one or more self-contained blowers
as well as a power supply which converts AC source to mandatory DC CAMAC dataway
voltages (± 6 V and ± 24 V) and also provide optional ± 12 V outputs.

Table 12.5 Classifying different CAMAC crates (e.g., M/S Kinetic Systems)
Model 1502 25 - Slot Crate
Model 1507 11 - Slot Crate
Model 1572 25 – Slot Crate
All crates in this series are arranged for a 19-inch relay rack mounting and include
module mounting holes for CAMAC only. The module 1502 is a full featured, 25-station
CAMAC crate. It includes a rear mounted power supply and a front removable fan tray.
The crate can deliver up to 525 W of power. The power supply features ±6 V outputs
shared to 52 A and ±24 V outputs shared to 9 A. The front panel of the fan tray includes
an over-temperature warning LED, a switch selected digital meter for monitoring all
voltages and currents and removing air tank filters (Fig. 12.8).

12.3.3 Power Supply Mounting

Slide the power supply on the rear ‘floor’ of the crate assembly until the connectors are
seated. Tighten the screw lock knobs in the direction of the arrows until the latches are
fully seated, and locked (Fig. 12.9).
562ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 12.8 Sub-assemblies of a CAMAC crate

Figure 12.9 Rear view of a power supply


Similarly, crates can be mounted to the 19” relay rack standards using 10-32 screws.
Table 12.6 Maximum load for different power supplies
Power Voltage Maximum Load
+24 Volt Supply 6 amperes
–24 Volt Supply 6 amperes
+12 Volt Supply 3 amperes
-12 Volt Supply 3 amperes
+6 Volt Supply 52 amperes
-6 Volt Supply 52 amperes
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ563

The maximum load on +24 V and –24 V combined shall be 9 amperes, and on the +6
V and –6 V combined shall be 52 amperes. The +12 V and –12 V supplies are derived
from the ±24 V supplies. Therefore, the sum of the loads for the +12 V, –12 V, +24 V,
and –24 V supplies must not exceed 9 amperes.
The front panel power supply temperature warning LED indicates that the ambient
temperature is too high, the shared load is too heavy, or the power supply airflow (on
the sides of the crate) is blocked. If the temperature increases further, the AC power
supply is cut off. When the power supply cools, the AC power is restored. Always turn
the crate power off when inserting or removing CAMAC modules to avoid possible
damage caused by momentary misalignment of contacts.
There are five patch lines, P1 to P5. Lines P1 and P2 are each ‘jumpered’ on the
dataway through all slots, while P3 to P5 have no connections and may be wire wrapped
on the rear of the dataway to meet the user’s needs. Care must be exercised in the
application of these ‘free use’ lines to assure that one module is not using the ‘jumpered’
P2 line for one purpose and a second module for another purpose.

Table 12.7 CAMAC backplane pin connections


Normal Station (1-24th slot) CAMAC Control Station (25th slot)
Control/ Control/ Control/ Control/
Pins Pins
Data Data Data Data
P1 1 1R B P1 1 1R B
P2 2 2R F16 P2 2 2R F16
P3 3 3R F8 P3 3 3R F8
P4 4 4R F4 P4 4 4R F4
P5 5 5R F2 P5 5 5R F2
X 6 6R F1 X 6 6R F1
I 7 7R A8 I 7 7R A8
C 8 8R A4 C 8 8R A4
N 9 9R A2 P6 9 9R A2
L 10 10R A1 P7 10 10R A1
S1 11 11R Z S1 11 11R Z
S2 12 12R Q S2 12 12R Q
W24 13 13R W23 L24 13 13R N24
W22 14 14R W21 L23 14 14R N23
W20 15 15R W19 L22 15 15R N22
W18 16 16R W17 L21 16 16R N21
W16 17 17R W15 L20 17 17R N20
W14 18 18R W13 L19 18 18R N19
W12 19 19R W11 L18 19 19R N18
W10 20 20R W9 L17 20 20R N17
W8 21 21R W7 L16 21 21R N16
564ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

W6 22 22R W5 L15 22 22R N15


W4 23 23R W3 L14 23 23R N14
W2 24 24R W1 L13 24 24R N13
R24 25 25R R23 L12 25 25R N12
R22 26 26R R21 L11 26 26R N11
R20 27 27R R19 L10 27 27R N10
R18 28 28R R17 L9 28 28R N9
R16 29 29R R15 L8 29 29R N8
R14 30 30R R13 L7 30 30R N7
R12 31 31R R11 L6 31 31R N6
R10 32 32R R9 L5 32 32R N5
R8 33 33R R7 L4 33 33R N4
R6 34 34R R5 L3 34 34R N3
R4 35 35R R3 L2 35 35R N2
R2 36 36R R1 L1 36 36R N1
–12V 37 37R –24V –12V 37 37R -24V
38 38R –6V 38 38R -6V
39 39R 39 39R
Y1 40 40R E Y1 40 40R E
+12V 41 41R +24V +12V 41 41R +24V
Y2 42 43R +6V Y2 42 42R +6V
0V 43 43R 0V 0V 43 43R 0V
1. P are the patch connections.
2. Note that there are 24 read/write lines in the normal station (R/W).
3. F represents the function to be performed. The function corresponding to each
binary combination of 5 bits is given later.
4. A represents the sub-addresses in the connected module.
5. X is the command-accepted line.
6. I is the inhibit line.
7. C is the clear line.
8. N is the station number line. The N line corresponding to selected station gets
high.
9. L is the ‘look at me’ line.
10. B is the busy line.
11. Q is the response line.
12. Z is the initialize line.
13. S1 and S2 are strobe signals.
14. L1 to L24 and N1 to N24 are control station contacts for ‘look at me’ commands
and addressing each station respectively.
15. E is earth signal.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ565

Figure 12.10 CAMAC control station connection to normal station

12.3.4 Plug-in Units (CAMAC Modules)

CAMAC modules are plug-in units that are plugged into CAMAC crates. The module
forms an interface between processes (may be analog or digital in nature) and CAMAC
dataway.
The devices or parts to be controlled are attached to these modules which are, in turn,
plugged into the CAMAC crate. Further, the CAMAC sends the input data to be processed
into the computer and brings back the commands.
Sixteen-channel scanning A/D converter: The Model 3512 16-channel scanning A/D
converter is single width CAMAC module for converting 16 analog voltages to equivalent
digital values and which can be read via the dataway. The inputs are continuously
scanned and converted, and the results are stored a 16-word memory in the module.
Thus, the CAMAC read cycles are asynchronous with the conversion process, eliminating
any overhead due to testing for the converter busy. The analog voltages are converted
using a sample and hold amplifier and a successive approximation converter. The Model
3512 provides high transient voltage protection and contains optional input filters. It is
566ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

useful in very high noise environments. It has a 12-bit resolution. On the front panel,
the N line flashes whenever the module is addressed. The ACTIVE light is on whenever
the module is powered, and scanning is activated. It has a resolution of 12 bits.
Monitoring four 20 mA signals: For monitoring four 20 mA analog signals, the standard
™›ŠŒ’ŒŽȱ’œȱ˜ȱ–˜ž—ȱŠȱ™›ŽŒ’œ’˜—ȱŘśŖȱǍȱ›Žœ’œ˜›ȱŽ¡Ž›—Š•ȱ˜ȱ‘Žȱ–˜ž•ŽȱŠ—ȱžœŽȱ‘ŽȱŖȱ˜ȱ
5 V input range. This allows the input to the Model 3512 to be disconnected without
disrupting the current loop. The loop must be such that the maximum operating mode
voltage is not exceeded. It has a 50-socket ribbon connection.

Table 12.8 Different commands distinguished by distinct function and address signals
Command Q Action
F(0).A(i) RD1 1 Reads Data Register
F(16).A(0) WT1 1 Write Channel Number
F(24).A(0) DIS 1 Disable the automatic scan and clear channel register
F(26).A(0) ENB 1 Enable the automatic scan
Z CZ 0 Enable the automatic scan and restart sequence controller

Note:
1. Sub-address (i) ranges from 0 to 15 for channels 0 to 15, respectively (Fig. 12.11).
2. X = 1 for all valid addressed commands.

Figure 12.11 Simplified block diagram of 16-channel scanning A/D converter


Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ567

Eight-channel D/A converter: The Model 3110 is a single width CAMAC module for
generating eight output voltages. The outputs are referenced to a common ground (the
module ground) (Fig. 12.12).

Table 12.9 Action for different commands of the module


Command Q Action
F(0).A(i) RD1 1 Reads the Data register i
F(16).A(i) WT1 1 Writes the data register i
F(1).A(15) RD2 1 Reads the module identifying number (e.g., 3110 = 60468)

It also has a 50-contact ribbon connector.

Figure 12.12 Simplified block diagram of 3110 8 channel 10 bit D/A converter

Input Gate/Output Register (IGOR): The Model 3063 is a single width module that
contains a 16-bit input gate, a 16-bit output register, a 1-bit status input, and four 0.5
second pulse outputs. Full handshaking is provided for the input gate and output
register. The handshaking signals can be tested. They can also generate LAM. The module
can be used without handshaking if required. The four pulsed control outputs can drive
loads up to 100 mA and +24 V. Six additional F(16) commands are provided to allow
the output register to be written four bits at a time or eight bits at a time. This allows
the module to drive independent of 4-bit or 8-bit devices. The Model 3063 is available
with a 50-pin ‘D’ or 50-contact Amphenol ribbon connector.
568ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Table 12.10 Action for different commands of the module


Command Q Action
F(0).A(0) RD1 1 Reads the input data and clears the LAM status.
F(1).A(15) RD2 1 Reads the module ID number
F(8).A(0) TLM LRR Tests the Read LAM request
F(8).A(1) TLM LRW Tests the Write LAM request
F(8).A(15) TLM LR Tests if a LAM request is present
Clears the LAM status bits, disables all LAM
F(9).A(0) CL1 1
requests, sets DIAC and DOPR true
F(9).A(1) CL1 1 Same as F(9).A(0)
F(10).A(0) CLM 1 Clears the Read LAM register
F(10).A(1) CLM 1 Clears the Write register
Writes the output data register word (D01 to D16)
F(16).A(1) WT1 1
and clears the Write LAM status
Writes the output data register byte 1 (D01 to D08)
F(16).A(2) WT1 1
and clears Write LAM status.
Writes the output data register byte 2 (D09 to D16)
F(16).A(3) WT1 1
and clears write LAM status
Writes the output data register nibble 1 (D01 to
F(16).A(8) WT1 1
D04) and clears Write LAM status.
Writes the output data register nibble 2 (D05 to
F(16).A(9) WT1 1
D08) and clears Write LAM status.
Writes the output data register nibble 3 (D09 to
F(16).A(10) WT1 1
D12) and clears Write LAM status.
Writes the output data register nibble 4 (D13 to
F(16).A(11) WT1 1
D16) and clears Write LAM status.
F(24).A(0) DIS 1 Disables the Read LAM request
F(24).A(1) DIS 1 Disables the write LAM request
F(25).A(0) XEQ A ACTIVE Executes pulse A (0.5 seconds)
F(25).A(1) XEQ B ACTIVE Executes pulse B (0.5 seconds)
F(25).A(2) XEQ C ACTIVE Executes pulse C (0.5 seconds)
F(25).A(3) XEQ D ACTIVE Executes pulse D (0.5 seconds)
F(26).A(0) ENB 1 Enables the Read LAM request
F(26).A(1) ENB 1 Enables the Write LAM request
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ569

Command Q Action
F(27).A(0) TST DP Tests if Data Present LAM source is true
F(27).A(1) TST TC Tests if Transfer Complete LAM source is true
F(27).A(2) TST TST Tests if TST input is true
Clears the LAM status bits, disables all LAM
Z CZ 0
requests, and sets DIAC and DOPR true.

Note:
X = 1 valid for all valid addressed commands.
The execute command returns Q = 0 if that execute pulse is still true from a previous
command.
It has a 50-contact ribbon connector. The data input register gate contains 16 bits.
These are read by an F(0).A(0) command (read lines R1 to R16). A read staticize register
is provided to prevent the data from changing early in the dataway cycle.
Input transfer timing (handshake signals used): Two high handshake signals are provided
for input data. Data input present (DIPR) is set high by the external device, indicating
that new data is present on the data input (DI) lines. When the data is read by the
F(0).A(0) command, the module asserts data input accepted (DIAC), indicating that it
has accepted the data and is ready for another data word. The F(26).A(0) command
enables the read LAM request (allows the read LAM status to assert the L line). A
F(24).A(0) disables this LAM request. When a new word of input data is present and
stable (DPR = 1), the read LAM status (LSR) is set. This is cleared by a read command
or clear LAM operation. In a polling environment, the F(27).A(0) command is used to
determine if stable data is present (DP = 1) and data has not yet been read. This returns
Q = 1 (Q = 0 otherwise).
Data output register: It contains 16 bits. These are written by various F(16) commands.
After the data is written, the data output lines remain in the selected pattern until the
next write operation. In some cases, it is desirable to control 8-bit devices or 4-bit devices
separately. There are four pulsed control outputs provided, given by F(25) commands.
The module ID command F(1).A(15) returns a unique pattern indicating the module
type and serial number.

Table 12.11 Different IGOR signal lines


DIPR Data Input Present line
DIAC Data Input Accepted line
LSR Read LAM Status line
DOPR Data Output Present line
DOAC Data Output Accepted line
570ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

24-bit isolated output register: The Model 3074 is a single width module containing a
24-bit register that drives 24 output circuits. Each output option is available with a
50-contact ribbon connector or a 50-pin ‘D’ connector. Both connector options are front
panel mounted (Fig. 12.13).

Figure 12.13 Simplified block diagram of 3063 IGOR

Table 12.12: Action for different commands of the module


Command Q Action
F(0).A(0) RD1 1 Reads the 24-bit data output register
F(16).A(0) WT1 1 Writes the 24-bit data output register
Z CZ 0 Clears the 24-bit output register

Since both read and write commands are provided, ‘selective set’ and ‘selective clear’
functions can be achieved by reading the register, performing the appropriate software
sequences (logical AND, etc.), and then writing the module register.
Isolated output register gives 24 V as the active output. It is connected to a relay. The
on/off of the relay gives different status outputs/indications (Fig. 12.14).
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ571

Figure 12.14 Simplified block diagram of 24-bit isolated output register

24-bit isolated input gate: The Model 3471 is a single width CAMAC module that
provides 24 individually isolated contact sense circuits. The sense circuits detect the
presence or absence of voltage at its terminals and is suitable for sensing such remote
process contact closures as limit switches, machine tool relay contacts, pressure switches,
manual switches, and mercury wetted contacts. Four voltage options are available: 12
V DC, 24 V DC, 48 V DC and 120 V DC (Fig. 12.15).
It also has a 50-socket ribbon connection.

Figure 12.15 Simplified block diagram of a 24-bit isolated input gate


572ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Table 12.13 Action for different commands of the module


Command Q Action
F(0).A(0) RD1 1 Reads the current state of inputs
F(1).A(15) RD2 1 Reads the module identifying number
Spark protection modules: There are four kinds of spark protection modules used with
each kind of CAMAC modules. It is basically comprised of passive component such as
varistors, capacitors, inductors, resistors and zenner diode (Tranzorb). Spark protection
modules are used to protect the CAMAC control system from any kind of surge (Fig.
12.16).

Figure 12.16

12.3.5 Use of CAMAC Modules


Table 12.14 Uses of different CAMAC modules
CAMAC Module Function
24-Bit Isolated Output Register To control the status of different devices, e.g., on/off, etc.
To read the status of devices and tell the status of the controller,
24-Bit Isolated Input Gate
e.g., a device is on/off, Faraday cup is inserted or not, etc.
Input Gate/Output Register Used to control and read magnetic devices, like bending
(IGOR) magnet and quadrupole.
Used for voltage control/current control. For example, it
Eight Channel D/A Converter
changes the output of power supply.
Used for readback/voltage read. It converts the physical data
16-Channel Scanning A/D
of the device into analog for communication with the
Converter
computer.
Used for protecting CAMAC crates from sparks due to high
Spark Protection Modules
voltage
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ573

Figure 12.17 Actual CAMAC crate photograph

Figure 12.18 Actual CAMAC modules used


574ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

12.4 SERIAL CONNECTION OF CRATES

The serial highway transfers data and control information in either bit serial mode (using
one data signal and a bit clock signal) or byte serial mode (using 8 data signals and a
byte clock signal). Clock rates up to 5 MHz can be used, depending upon individual
system characteristics.
In a primary application, the control devices are CAMAC crate assemblies with the
serial crate controllers (SCCs), which conforms to a defined message structure. The serial
highway is intended to complement the parallel highway. It will be attractive for certain
applications which the parallel highway was not designed to cover, for example, where
there are long distances between crates or where simplicity of connections is desirable.
However, the time required to perform a complete operation, including dataway cycle,
will generally be longer in a serial system than on the parallel system. Interconnections
between the devices may be made directly, using the defined signal standard, or indirectly
through communication channels with other signal standards and types of modulation.

12.4.1 Principle

The SH (serial highway) interconnects a master device (the serial driver SD) and up to
62 CAMAC crate assemblies or other controlled devices. At any time, there is only one
active master device, but the standard does not exclude systems in which more than
one device is capable of acting as a master.
The addressing scheme allows a maximum of 62 controlled devices, whose assigned
addresses need not be related to the actual sequence of devices along the highway. The
SH forms the unidirectional loop from the output port of SD, through each controlled
device, in turn, and back to the input port of SD. When describing conditions with
respect to a particular device, it is often convenient to use the term ‘upstream’ to refer
to the part of the SH between the output port of the SD and the device and the term
‘downstream’ to refer to the part between the device and the input port of the SD (see
Fig. 12.19).

Device Device

Serial
Driver
(SD)

Figure 12.19 Block diagram showing CAMAC serial highway loop configuration
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ575

12.4.2 Message Structure

All messages transmitted on the SH consist of sequences of 8-bit bytes. All information
related to the measurement is contained within these 8-bit bytes. The 8 bits constituting
a byte are labelled Bit 1 (least significant) to Bit 8 (most significant). The bits in the SH
messages are distinguished from corresponding dataway signals by the prefix S. For
example, bits SA1-SA8 correspond to dataway signals A1-A8. In all bytes, bits 1-6 are
available for information fields. Bit 7 of every byte is a delimiter bit which allows the
receiving devices to identify the first and last bytes of each message. Bit 8 is available
for use as odd parity bit (with an appropriate value so that the byte contains an odd
number of bits in logic 1 state). It is always used in this way in the first and last bytes
of a message and all bytes of messages associated with CAMAC SCCs.
Every message starts with a header byte. This includes a device address (a crate
address when the device is an SCC). In a message from the SD, the header byte contains
the address of the destinations. In the message to the SD, it contains the address of the
source. Bit 7 of the header byte is at logic 0 and bit 8 conserves the odd parity over the
whole byte.
Every message ends with a delimiter byte in which bit 7 is at logic 1 and bit 8 conserves
the odd parity.
The length and content of the ‘text’ between the header byte and delimiter byte of a
message can be chosen to suit the needs of the individual device. In each byte, between
the header and delimiter byte, bit 7 is at logic 0. If there are any bytes between the
delimiter byte of one message and header byte of next, they are also delimiter bytes
with Bit 7 at logic 1. Thus, the header byte of a message can be identified because after
one or more bytes with bit 7 at logic 1, it is the first byte with bit 7 at logic 0. Similarly,
the last byte of a message can be identified because after one or more bytes with bit 7
at logic 0 it is the first byte with bit 7 at logic 1 (Fig. 12.20).
Note: The error detection over a block of bytes constituting a message or part of a
message can be provided by the combination of byte parity in bit 8 of each byte and a
set of column parity bits in bits 1-6 of the last byte of the block.

Figure 12.20 Typical structure of a message sent to/from CAMAC crate controller

Transmission: Bytes are transmitted either in bit serial mode or byte serial mode. In the
bit serial mode, the 8-bit byte is transmitted with least significant bit (bit 1) first. It is
576ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

preceded by a start bit (logic 0) and followed by a stop bit and an optional pause
(logic 1) (Fig. 12.21).

Figure 12.21 Message transmission format in bit transfer mode

The start and stop bits form a ‘byte frame’ from which receiving devices can recover
a byte clock.
The message structure and protocol of the SH are identical in the two modes of
transmission. Throughout an SH system, bytes are transferred in synchronism with the
byte clock which accompanies the data in byte serial mode and is derived from byte
framing in bit serial mode. The clock rate is uniform throughout a system. The absolute
maximum clock rate is 5 MHz, but the performance of the communication channel or
the connected devices may require a lower clock rate in particular systems.
Three types of messages are used by the serial crate controllers:
(i) ‘Command’ messages are generated by the SD and instruct an addressed SCC to
perform a CAMAC operation. The addressed crate controller should transmit a
truncated form of the command message.
(ii) In response to the command message, the addressed crate controller sends a
‘reply’ message to the SD. The command message from the SD to an SCC and
the resulting reply message from the SCC to the SD constitute a command/reply
transaction.
(iii) Any SCC may generate a ‘demand’ message to indicate that there is a ‘look at
me’ (LAM) request on the dataway in the crate.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ577

Command message: A command message can be either complete or truncated.

B 0 Crate Address Header Byte


B 0 M I Sub-Address
B 0 1 Function Command
B 0 1 Station Number
B 0 Write Data
B 0 Write Data
Write Data
B 0 Write Data
B 0 Write Data Sum Byte
B 0 Column Parity
1 0 SPACE Reply Space
1 0 SPACE
1 1 END End Byte
Figure 12.22: CAMAC command message structure

Group 5-8 is included for write commands, but is omitted for read and control
commands. The message must be transmitted as a consecutive sequence of bytes, starting
with the header byte (crate address) and finishing with the end byte. Three bytes contain
the sub-address, function and station number fields of the CAMAC command. The
message continues with a sequence of space bytes providing the SCC an opportunity
to transmit a reply, and with an end delimiter byte. The addressed SCC should transmit
a truncated form of the command message, consisting of a header byte followed by an
end byte (Fig. 12.23).

Reply message:

0 Crate Address Header Byte


0 M I Status Status Byte
0 Read Data
0 Read Data
Read Data
0 Read Data
0 Read Data
End Sum Byte
0 Column Parity

Delimiter Bites
Byte Parity Bite
Figure 12.23 CAMAC reply message structure
578ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Bytes 3-6 are included in the reply to a read command, but is omitted in the reply to
other commands.

Demand message:

Figure 12.24 CAMAC demand message structure

Message fields:

Ȋȱ Crate Address Field (6 bits): This field defines the destination address in command
messages and the source address in reply and demand messages. Each SCC must
respond to the address assigned to it from the set (01)8 to (76)8 and must not respond
to neither (00)8 nor (77)8. The address (00)8 is reserved for use at the SD. Under
certain error conditions, a ‘space’ byte can be falsely identified as a header byte.
The recommended space byte has a bit pattern corresponding to the address (77)8.
This address is not used, and there are (76)8 {(62)10} available crate addresses.
Ȋȱ Station Number (5 bits, SN1-SN16): This field in the command message defines
the station number within the CAMAC crate.
Ȋȱ Sub-Address Field (4 bits, SA1-SA8): This field in the command message defines
a sub-address at the selected station in the crate.
Ȋȱ Function Field (5 bits, SF1-SF16): The values of these bits define the function to be
performed by the command and hence differentiate between different types of
commands (read, write and control).
Ȋȱ Write Data field (24 bits SW1-SW24): This field is included in the command message
if SF16 = 1 and SF8 = 0. It contains data associated with the write command.
Ȋȱ Read Data field (24 bits SR1-SR24): This field is included in the reply message if
the function field of the column contains the data requested by a read command.
Ȋȱ Message Identification Field (M1 and M2): This command in the command and
reply messages (2 bits) and in the demand message (only M2), is used to identify
the three types of message.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ579

Table 12.15 Identification of different types of messages using M1 and M2


Message M2 M1
Command 0 0
Reply 0 1
Demand 1 -
This field is required by the SD to distinguish between reply and demand messages
of equal length. It may also be used by the SCC to identify command message as
additional security against executing false commands.
Ȋȱ Status Field (4 bits: Error, Response, Command Accepted, and Delayed): This field
in the reply message shows how the SCC has responded to the command message.
The error (ERR) bit indicates whether the error detection checks on the command
message were satisfactory. The delayed error (DERR) bit provides similar
information about the previous command. For a command that has been executed,
the SQ and SX bits indicate the response Q and command accepted X status of
the feature of the module or controller that has been accessed by the command.
Ȋȱ Serial Graded L (SGL) Field (5 bits: SGL1:SGL5): This field of the demand message
indicates/identifies the type of demand, the source of demand, or the action
performed by the demand. It may be derived from the L signals on the dataway
of the crate by any process of selection, grouping, priority coding, etc., that is
performed by the SCC or by a separate encoder, connected to the SCC.
Formatting bytes: Formatting bytes are an important part of the message structure, but
these do not contain information fields as defined in the previous section. These indicate
the end of each message, provide column parity component of the geometric error
detection scheme, and maintain the byte lock during intervals within messages.
Ȋȱ Delimiter Bytes: A delimiter byte must have bit 7 at logic 1, and bit 8 with the
appropriate value to conserve odd parity. All other bytes, which do not satisfy
these conditions are non-delimiter bytes. The class of delimiter bytes includes
‘end’, ‘endsum’, and ‘wait’ bytes. Delimiter bytes are used to indicate the last byte
of each message and any bytes that occur between messages. Each message consists
of a sequence of non-delimiter bytes terminated by a delimiter byte.
Ȋȱ Column Parity Field: The sum and endsum bytes contain a column parity field in
bits 1 to 6. This field provides the column parity component of a geometric error
detection scheme. Each bit of column parity field conserves the even parity over
the corresponding bit position in each byte, from the header byte to sum or endsum.
Ȋȱ End Byte: The end byte is a delimiter byte generated by the SD to terminate
complete command messages and by SCCs to terminate command messages. End
byte with a bit pattern (11100000) equivalent to (340)8 must be generated by the
SD as the last byte of every command message. All unaddressed crate controllers
must retransmit received end bytes unchanged. An addressed crate controller must
either retransmit the received end byte of the command message or replace it with
an endsum byte (reply message).
580ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Wait Byte: The wait byte is a delimiter byte generated by the SD and by addressed
SCCs. The SD may generate wait bytes between successive command messages.
An addressed SCC generates wait bytes in response to received bytes, between
the truncated command messages and the header of the reply message. And also,
if required, between the endsum byte of the reply message and completion of
command/reply transaction. The wait has no information field. Although it is not
mandatory for the SD to generate bytes during intervals between command
messages, the generation of wait bytes is recommended to permit the propagation
of reply messages to be completed in a typical SH which includes logical delays.
Any bytes generated by an SD or SCC during intervals between messages must
be wait bytes with a bit pattern (11100000)2 equivalent to (340)8. A wait byte always
follows another delimiter byte. Under certain conditions, connected with the
generation of demand messages, an SCC is permitted to transmit another byte in
place of a received wait byte.
Ȋȱ EndSum Byte: The endsum byte is a delimiter byte and is generated by the SCC
to terminate each reply or demand message. The column parity fields (bits 1-6)
conserves even parity over all bytes between the header byte and the endsum
bytes.
Ȋȱ Sum Byte: The sum byte is a non-delimiter byte and is generated by the SD in the
command message. Bits 1-6 of this byte conserves even column parity over all
bytes of the message between the header byte and sum byte inclusive. The
addressed SCC uses the sum byte in the geometric error detection test on the
command message, before deciding whether to execute the command.
Ȋȱ Space Byte: The space byte is a non-delimiter byte. A sequence of space bytes
generated by the SD between the sum and end bytes of a command message forms
the reply space. The addressed SCC generates its reply message in place of some
or all of the space bytes in the reply space. The bit pattern of space bytes generated
by the SD should be (10111111)2, equal to (277)8.
Note: An SCC that is expecting to receive space bytes in the reply space of a command
message must accept any non-delimiter byte as a substitute for the space byte. Acceptable
substitutes for space bytes need not have the recommended bit pattern or conserve odd
byte parity.
Command/reply message sequences: These sections define the sequences of input and
output bytes that occur when an SCC receives a command message, performs a CAMAC
read, write or control operations and transmits a reply message. In the bit serial mode
the retransmission of bytes typically involves a delay of only one-bit period, whereas
in byte serial mode there is typically a delay of a one-byte period. Essentially, space
bytes allow time for execution of the command. The minimum number of these bytes
is, in principle, zero but a minimum of one byte may be more convenient to implement.
Optional excess space bytes are used in one method of controlling the length of the
reply space. The minimum number of these bytes is zero.
The SCC is normally awaiting a header byte. The SCC recognizes the header byte
addressed to itself, receives and checks the command and data, executes the command,
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ581

and sends a reply during the reply space, and finally terminates the transaction when
it receives the end byte. These sequences assume that the SCC has previously received
one or more delimiter bytes (the end or endsum byte of a previous message, possibly
followed by one or more wait states) and is waiting for the header byte at the beginning
of the new message. While the SCC is waiting for the header byte, it must retransmit
each byte it receives, checking its contents for proper action. Demand message generation
is inhibited if it receives a non-delimiter byte addressed to itself.
If the SCC receives any byte other than a delimiter byte or the header byte of a
message addressed to it, then it must treat this as the header byte of a message to or
from another SCC. It must inhibit the initiation of demand messages and pass the
message unchanged.
While receiving the command message, the addressed SCC should transmit a truncated
form of the command message consisting only of the header byte and end byte, followed
by a sequence of wait bytes until it is ready to transmit the reply message. The addressed
SCC must execute the command and send the appropriate reply if the byte and column
parity are correct, MI field is correct, and the SCC is not in the bypassed condition.
Otherwise SCC must not execute the command. If the SCC executes the command, it
must send a reply message. Transmission of a reply message must not start until the Q
and X responses are established. If the SCC does not execute the command because the
parity or MI field test is not correct, it must send a 3-byte error-reply message. If the
SCC does not execute the command because the dataway offline or bypass conditions
are not satisfied, it must send a reply message with status field SX at logic 0 to indicate
that command is not accepted by the SCC.

1 Delimiter 1 Delimiter
0 Header 0 Header
0 Sub-Address 0 End
0 Function Truncated 0 Wait
Command
0 Station number 0 Wait
Message
0 Sum 0 Wait
0 Space 0 Wait
Command
0 Space Message 0 Header
0 Space 0 Status
0 Space 0 Read Data
0 Space 0 Read Data
Reply
0 Space Message 0 Read Data
0 Space 0 Read Data
0 Space 0 Endsum
1 End 1 Wait
Header or Wait

Figure 12.25 Command/reply sequence read operation


582ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

In the above-shown block diagram of the command message, for a write operation,
there would be 24-bit write data field in the command message and no data field in the
reply message. For the control operation, there would be no data field in neither command
nor reply message. If the command has not been executed, the transmission of the reply
message may start as soon as presumed sum byte has been received. Otherwise, the
reply message is delayed with respect to the execution of the command. Under many
typical conditions of dataway cycle timing and SH transmission rate, execution of
command can be completed before the SCC receives the first space byte. If so, the SCC
may transmit the header byte of the reply message as it receives the first space byte,
then transmit the status byte, receive the second space byte and so on.
For read operation, the command message does not include a write data field. The
reply message includes a 24-bit read data field. Thus, the SCC expects to find the sum
byte as the fifth byte of the received message and performs the column parity check
over the first five bytes of the message.
For a write operation, the command message includes a 24-bit write data field. The
reply message does not include a read data field. Thus, the SCC expects to find the sum
byte as the ninth byte of the received message and performs the column parity check
over the first nine bytes of the message.
For a control operation, the SCC expects the sum byte as the fifth byte of the received
message and performs the column parity check over the first five bytes of the message.
The addressed SCC should transmit a truncated form of the received command message,
consisting only of the header byte (containing crate address field) and an end byte. This
is a precautionary practice so that only one crate can respond to the command message.
Some special cases, however, may require the SCC to retransmit the command message.
Space Bytes: The space bytes are partially or fully replaced by the reply message from
the addressed SCC. The SCC transmits wait bytes in place of received space bytes until
it has executed the command. Then it transmits the first byte of a reply message in place
of next space byte.
In one mode of operation, the SD continues to generate excess space bytes until it
has received the reply message. It then generates the end byte to terminate the transaction.
In another mode, the SD generates a calculated number of space bytes and then terminates
the transaction by sending the end byte. It then continues to generate wait bytes until
it has received the reply message.
In another mode, appropriate to high-performance systems with low error rates, the
SD does not wait to receive the reply to one command message before starting to generate
the next. In this mode, the SD preferably generates the exact minimum number of space
bytes so that the addressed SCC generates the endsum byte of the reply message when
it receives the end byte of the command message. Under error-free conditions, an SD
operating in this mode transmits a sequence of command messages and receives a
corresponding sequence of reply messages in the same relative order but possibly
considerably delayed, and with interposed demand messages. The SD must include
within the command message enough space bytes to provide time for the SCC to execute
the command and to transmit the reply message.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ583

Identification of the message type: Under normal conditions, the messages on the SH
consists of complete command messages, truncated command messages, reply messages,
and demand messages. Under error conditions, there may also be various forms of
incomplete and spurious messages, for example due to loss of synchronism or abandoned
operations or corruption of wait bytes. The three main pieces of information available
to an SCC or SD for identifying the type of messages as message identification field MI,
the function field SF, and the message length.
The MI field provides the basic means of distinguishing among reply, demand, and
complete command messages. The message length (the number of bytes from the header
to first delimiter byte inclusive) provides a means of distinguishing between complete
and truncated command messages, and between a reply message with or without a data
field. The SF field of a complete command message distinguishes between command
messages with or without data field.

12.4.3 Highway D Ports

All SCCs and SDs must have input and output D port connectors and must implement
these connectors either in the bit serial mode or byte serial mode. An SCC or SD may
also have additional ports to other standards (U ports) unless these are specifically
excluded (Fig. 12.26).
D connector input Contact D output Connector
Circuit ground (earth) 1 Circuit ground (earth)
2
Bus 1 (Free Use) Bus 1 (Free Use)
3

Bit serial data in or Byte serial 4


Bit serial data out or Byte serial LSB out
data LSB in 5
6
Byte serial Bit 2 in Byte serial Bit 2 out
7
8
Byte serial Bit 3 in Byte serial Bit 3 in
9
10
Byte serial Bit 4 in Byte serial Bit 4 in
11
12
Byte serial Bit 5 in Byte serial Bit 5 in
13
14
Byte serial Bit 6 in Byte serial Bit 6 in
15
584ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

16
Byte serial Bit 7 in Byte serial Bit 7 in
17
18
Byte serial MSB in Byte serial MSB out
19
20
Bus 2 (free use) Bus 2 (free use)
21
22
Bit/Byte clock in Bit/Byte clock out
23
Bypass control 24 Bypass control
Reserved for control signal 25 Reserved for control signal
Figure 12.26 CAMAC crate D pin connections

The even numbered signal is Terminal A, carrying signal and odd numbered contact
is Terminal B, carrying signal.
Note: The standards for data and clock signals at D ports are based on Standards RS-422
of the electronics industry association.

12.5 VME BUS

Other than CAMAC, other control systems can also be built using the VME bus for
network controlling different devices of the accelerator.
The VME bus (Versa Module Europa bus) is a computer bus standard, originally
developed for the Motorola 68000 line of CPUs, but later widely used for many
applications and standardized by the IEC as ANSI/IEEE 1014-1987. It is physically based
on Eurocard sizes, mechanicals and connectors (DIN 41612), but uses its own signaling
system, which Eurocard does not define. It was first developed in 1981 and continues
to see widespread use today.
VME uses separate 32-bit data and address buses. The VME bus is a master-slave
computer architecture. The signaling scheme is asynchronous, meaning that the transfer
is not tied to the timing of a bus clock. VITA (VME International Trade Association) is
the organization whose purpose is to promote and develop the VME.
Unlike NIM and CAMAC, the VME was created for the industry and not for physics
applications. However, the North American, European and Japanese physics communities
have joined to work with the VITA and founded the VME International Physics
Association (VIPA). The main difference between CAMAC and VME Bus is that VME
has an integrated OS within it, whereas CAMAC just has a crate controller.
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ585

Figure 12.27 Different components of VME

12.5.1 Advantages of VME over CAMAC Standard

As the VME is an asynchronous bus, the bandwidth indicated is a theoretical limit. For
VME64, if works around 80 MB/s of theoretical maximum bandwidth. Usually, the actual
transfer rate is less than 50% of the bandwidth.
High readout speeds: High density modules can provide up to 640 channels (1 controller
+ 20 digitizers) in a single VME crate with 21 slots. Usage of high bandwidth optical
interconnect link makes sure that the interconnect technology doesn’t become a bottleneck
while transferring data.
586ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

12.6 IMPLEMENTATION IN ACCELERATORS : A CASE OF PRACTICALLY


WORKING SYSTEM STUDY IN PHYSICS MACHINE CONTROL
12.6.1 Present

CAMAC systems are for operational control of 15 UD Pelletron Accelerator. The devices
are connected to different CAMAC modules. A total number of four CAMAC crates are
used to control the operation of the accelerator from ion source to experimental channel,
as shown in Fig. 12.28. The computer processes the device input parameters and sends
the output for proper control of the devices. Earlier, the CAMAC crate controllers were
connected serially to a computer at the control console for its control operation.
In the newer version, there is an embedded computer inside each CAMAC crate
controller. The embedded computer makes it more intelligent and carries out the more
complex processing at the CAMAC end itself. This saves time and improves efficiency.
At present, all four CAMAC crate controllers and computer at the control console
communicate with each other using LAN networking.
LAN networking: Each CAMAC crate controller has a specific IP address. The data
transmission works according to the TCP/IP protocol. In total, there are four CAMAC
crates for the control of 15 UD Pelletron Accelerator. All these CAMAC crates are
interconnected via a LAN. The LAN works on the client/server topology. All the CAMAC
crates are the servers, which access data from the device. The computer which is kept
in the control room, to which all the CAMAC crates are connected, acts as a client.

Table 12.16 Control area of each CAMAC crate


All the devices from ion source to the low energy dead section ( 01 Area
CAMAC Crate #1
to D-1 )
All the devices from terminal upper half to switching magnet ( T1 to 04
CAMAC Crate #2
Area)
CAMAC Crate #3 All the devices on the switching lines
CAMAC Crate #4 Device status display and interlock board

Table 12.17 Different area designations inside the Pelletron accelerator


01 Area Between ion source and injector magnet
02 Area Between injector magnet and entry to Pelletron accelerator
CT Area Top of accelerating column
D-1 Low energy dead section
T-1 Terminal upper half
T-2 Terminal lower half
D-2 High energy dead section
CB Area Bottom of accelerator column
03 Area Exit of pelletron accelerator to analyser magnet
04 Area Analyser magnet to switching magnet
Computer Automated Measurement and Control (CAMAC) & VMEȱ žœȳ587

The layout of entire control system is shown in Fig. 12.28.

Figure 12.28 Layout of control system


588ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

REFERENCES

1. CAMAC Instrumentation and Interface Standards, IEEE, 1982.


2. NSC school on accelerator physics year 1988-89.
3. H. Wiedemann, Particle Accelerator Physics 1, second edition, Springer, 1999.
4. www.wikipedia.org/camac.
5. R. Hellborg (Ed.), Electrostatic Accelerator, Springer, 2005.
6. Greg Norton, “New developments in design and applications for Pelletron
accelerator,” Pramana, Vol 59, 2002.
7. W. Scharf, Particle Accelerators and Their Uses, Part 1, Harwood Academic Publishers,
1986.
8. E. Cottereau, Tandetron, CNRS/CEA, BAT 30 Ave de la Terasse, F-91198 Gif Sur
Yvette Cedex, France.

REVIEW QUESTIONS

1. What is CAMAC?
2. Why do we use CAMAC?
3. What are the basic features of CAMAC?
4. What are the advantages of CAMAC?
5. What is CRATE?

ANSWERS

1 Computer automated measurement and control is a standard bus and modular


crate electronics standard for data acquisition and control used in nuclear and
particle physics experiments.
2. It would be again very costly if we connect each device individually to the
computer. Also a large number of parts and a very efficient controlling mechanism
would be required. CAMAC solves these problems. CAMAC instruments are
modular function channel units that are accommodated in a CAMAC crate.
3. Advantages of CAMAC
ȱ ȱ ŗǯȲ•Ž¡’‹’•’¢
ȱ ȱ ŘǯȲ™’–’£Š’˜—ȱ˜ȱœ¢œŽ–œ
ȱ ȱ řǯȲŠœŽȱ˜ȱ›Žœ›žŒž›’—
ȱ ȱ ŚǯȲŽŽ››Žȱ˜‹œ˜•ŽœŒŽ—ŒŽǰȱž™Š’—ȱŒŠ™Š‹’•’¢
ȱ ȱ śǯȲ ’‘ȱŽ›ŽŽȱ˜ȱŒ˜–™žŽ›ȱ’—Ž™Ž—Ž—ŒŽǯ
4. A CAMAC crate is a mounting unit or houring for plug-in unit that includes a
dataway and conforms to the standards of ANSI/IEEE. An assembly crate
controller and or more CAMAC crate operates in conformity with dataway
requirements of ANSI/IEEE.
5. A CRATE is a modular standard to place a large number of modules over a
backplane.
FIELD-PROGRAMMABLE GATE ARRAYS
13 (FPGAs) & VHDL BASICS

OBJECTIVE
After going through this chapter, the students will be able to understand:
s Introduction to FPGA
s Explanation of a Spartan-3E kit to understand FPGA design flow and all basics
for future understanding.
s Learn FPGA implementation and design flow using Xilinx ISE WebPACK

13.1 INTRODUCTION TO FPGA


Field-programmable gate arrays (FPGAs) are pre-fabricated silicon devices that can be
electrically programmed to become almost any kind of digital circuit or system. They
have many advantages over application specific integrated circuits (ASIC). ASICs are
designed for specific applications using CAD tools and are fabricated at a foundry.
Developing an ASIC takes much time and is costly.
Furthermore, it is not possible to correct errors after fabrication. In contrast to ASICs,
FPGAs are configured after fabrication and they can also be reconfigured. This is done
with a hardware description language (HDL) which is compiled to a bit stream and
downloaded to the FPGA. The disadvantages of FPGAs are that the same application
needs more space (transistors) on the chip, and the application runs slower on an FPGA,
which is as modern as the ASIC counterpart. Due to the increase of transistor density,
FPGA was getting more powerful over the years. On the other hand, the development
of ASIC was getting slower and more expensive. Therefore, FPGAs are increasingly
applied to high-performance embedded system (Fig. 13.1).

Figure 13.1 FPGA diagram


590ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 13.2

An FPGA is an integrated circuit designed to be configured by a customer or a


designer after manufacturing—hence ‘field-programmable’. The FPGA configuration is
generally specified using a hardware description language (HDL), similar to that used
in an application-specific integrated circuit (ASIC) (circuit diagrams were previously
used to specify the configuration, as they were for ASICs, but this is increasingly rare).
FPGAs can be used to implement any logical function that an ASIC could perform. The
ability to update the functionality after shipping, partial reconfiguration of a portion
of the design and the low non-recurring engineering costs relative to an ASIC
design (notwithstanding the generally higher unit cost), offers advantages for many
applications.
FPGAs contain programmable logic components called ‘logic blocks’, and a hierarchy
of reconfigurable interconnects that allow the blocks to be ‘wired together’—somewhat
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ591

like many (changeable) logic gates that can be inter-wired in (many) different
configurations. Logic blocks can be configured to perform complex combinational
functions or merely simple logic gates like AND and XOR. In most FPGAs, the logic
blocks also include memory elements, which may be simple flip-flops or more complete
blocks of memory.
In addition to digital functions, some FPGAs have analog features. The most common
analog feature is programmable slew rate and drives strength on each output pin,
allowing the engineer to set slow rates on lightly loaded pins that would otherwise ring
in an unacceptable manner, and to set strong, faster rates on heavily loaded pins on
high-speed channels that would otherwise run too slow. Another relatively common
analog feature is differential comparators on input pins designed to be connected to
differential signaling channels. A few ‘mixed signal FPGAs’ have integrated peripheral
analog-to-digital converters (ADCs) and digital-to-analog converters (DACs) with analog
signal conditioning blocks allowing them to operate as a system-on-a-chip. Such devices
blur the line between an FPGA, which carries digital ones and zeros on its internal
programmable interconnect fabric, and field-programmable analog array (FPAA), which
carries analog values on its internal programmable interconnect fabric.

13.1.1 FPGA Architecture

The most common FPGA architecture consists of an array of logic blocks (called
configurable logic block, CLB, or logic array block, LAB, depending on the vendor), I/O
pads, and routing channels. Generally, all the routing channels have the same width
(number of wires). Multiple I/O pads may fit into the height of one row or the width
of one column in the array.
An application circuit must be mapped into an FPGA with adequate resources. While
the number of CLBs/LABs and I/Os required is easily determined from the design, the
number of routing tracks needed may vary considerably even among designs with the
same amount of logic. For example, a crossbar switch requires much more routing than
a systolic array with the same gate count. Since unused routing tracks increase the cost
(and decrease the performance) of the part without providing any benefit, FPGA
manufacturers try to provide just enough tracks so that most designs that will fit in
terms of lookup tables (LUTs) and IOs can be routed. This is determined by estimates
such as those derived from Rent’s rule or by experiments with existing designs.
In general, a logic block (CLB) consists of a few logical cells (called ALM, LE, slice,
etc.). A typical cell consists of a 4-input LUT, a full adder (FA) and a D-type flip-flop,
as shown below. The LUTs are, in this figure, split into two 3-input LUTs. In the ‘normal
mode’, those are combined into a 4-input LUT through the left mux. In the ‘arithmetic’
mode, their outputs are fed to the FA. The selection of mode is programmed into the
middle multiplexer. The output can be either synchronous or asynchronous, depending
on the programming of the mux to the right, in the figure example. In practice, entire
or parts of the FA are put as functions into the LUTs in order to save space. (see Fig.
13.3).
592ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 13.3 Simplified illustration of a logic cell

ALMs and slices usually contain two or four structures similar to the figure, with
some shared signals. CLBs/LABs typically contain a few ALMs/LEs/slices. In recent
years, manufacturers have started moving to 6-input LUTs in their high-performance
parts, claiming increased performance. Since clock signals (and often other high-fan-out
signals) are normally routed via special-purpose dedicated routing networks in
commercial FPGAs, they and other signals are separately managed. For this example
architecture, the locations of the FPGA logic block pins are shown below (Fig. 13.4).

Figure 13.4 Logic block pin locations

Each input is accessible from one side of the logic block, while the output pin can
connect to routing wires in both the channels to the right and the channel below the
logic block. Each logic block output pin can connect to any of the wiring segments in
the channels adjacent to it. Similarly, an I/O pad can connect to any one of the wiring
segments in the channel adjacent to it. For example, an I/O pad at the top of the chip
can connect to any of the W wires (where W is the channel width) in the horizontal
channel immediately below it. Generally, the FPGA routing is unsegmented, that is,
each wiring segment spans only one logic block before it terminates in a switch box. By
turning on some of the programmable switches within a switch box, longer paths can
be constructed. For higher speed interconnects, some FPGA architectures use longer
routing lines that span multiple logic blocks.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ593

Whenever a vertical channel and a horizontal channel intersect, there is a switch box.
In this architecture, when a wire enters a switch box, there are three programmable
switches that allow it to connect to three other wires in adjacent channel segments. The
pattern, or topology, of switches used in this architecture is the planar or domain-based
switch box topology. In this switch box topology, a wire in track number one connects
only to wires in track number one in adjacent channel segments, wires in track number
two connect only to other wires in track number two and so on. The figure below
illustrates the connections in a switch box (Fig. 13.5).

Figure 13.5 Switch box topology

Modern FPGA families expand upon the above capabilities to include higher level
functionality fixed into the silicon. Having these common functions embedded into the
silicon reduces the area required and gives those functions increased speed compared
to building them from primitives. Examples of these include multipliers, generic DSP
blocks, embedded processors, high-speed I/O logic, and embedded memories.
FPGAs are also widely used for systems validation including pre-silicon validation,
post-silicon validation, and firmware development. This allows chip companies to
validate their design before the chip is produced in the factory, reducing the
time-to-market.
To shrink the size and power consumption of FPGAs, vendors such as Tabula and
Xilinx have introduced new 3D or stacked architectures. Following the introduction of
its 28 nm 7-series FPGAs, Xilinx revealed that several of the highest-density parts in
those FPGA product lines would be constructed using multiple dies in one package,
employing technology developed for 3D construction and stacked-die assemblies. The
technology stacks several (three or four) active FPGA dice side-by-side on a silicon
interposer – a single piece of silicon that carries a passive interconnect.
594ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

13.1.2 FPGA Design and Programming

To define the behavior of the FPGA, the user provides an HDL or a schematic design.
The HDL form is more suited to work with large structures because it’s possible just to
specify them numerically rather than drawing every piece by hand. However, a schematic
entry can allow for easier visualization of design.
Then, using an electronic design automation tool, a technology-mapped netlist is
generated. The netlist can then be fitted to the actual FPGA architecture using a process
called place-and-route, usually performed by the FPGA company’s proprietary place-
and-route software. The user will validate the map, place and route results via timing
analysis, simulation, and other verification methodologies. Once the design and validation
process is complete, the binary file generated (also using the FPGA company’s proprietary
software) is used to (re)configure the FPGA. This file is transferred to the FPGA/CPLD
via a serial interface (JTAG) or an external memory device like an EEPROM.
The most common HDLs are VHDL and Verilog, although in an attempt to reduce
the complexity of designing in HDLs, which have been compared to the equivalent of
assembly languages, there are moves to raise the abstraction level through the introduction
of alternative languages. National Instrument’s LabVIEW graphical programming
language (sometimes referred to as ‘G’) has an FPGA add-on module available to target
and program FPGA hardware.
To simplify the design of complex systems in FPGAs, there exist libraries of predefined
complex functions and circuits that have been tested and optimized to speed up the
design process. These predefined circuits are commonly called ‘IP cores’ and are available
from FPGA vendors and third-party IP suppliers (rarely free, and typically released
under proprietary licenses). Other predefined circuits are available from developer
communities such as OpenCores (typically released under free and open source licenses
such as the GPL, BSD or similar license), and other sources.
In a typical design flow, an FPGA application developer will simulate the design at
multiple stages throughout the design process. Initially, the RTL description in VHDL
or Verilog is simulated by creating test benches to simulate the system and observe
results. Then, after the synthesis engine has mapped the design to a netlist, the netlist
is translated to a gate level description where the simulation is repeated to confirm the
synthesis proceeded without errors. Finally, the design is laid out in the FPGA at which
point propagation delays can be added and the simulation runs again with these values
back-annotated onto the netlist.
FPGAs are digital integrated circuits (ICs) that contain configurable (programmable)
blocks of logic along with configurable interconnects between these blocks. Design
engineers can configure such devices to perform a tremendous variety of tasks. Gate
array is a type of logic chip that can be programmed at the field level. These devices
can be re-configured to change logic function while resident in the system. Fully fabricated
FPGA chips contain tens to hundreds of thousands or even more, of logic gates with
programmable interconnects. Programmable interconnects are available to users for their
custom hardware programming to realize the desired functionality. This design style
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ595

provides the means for fast prototyping and also for cost-effective chip design, especially
for low applications. FPGAs are programmable digital logic chips. They can be
programmed to do almost any digital function.

General workflow when burning the FPGAs

1. A computer is used to describe any ‘logic function’. A schematic, a text file is


made for describing the function.
2. Then the ‘logic function’ is compiled on the computer, with the help of software
(ISE WebPACK 11.1) provided by the FPGA vendor. That creates a binary file
that can be downloaded into the FPGA.
3. Thus, a cable is connected from the computer to the FPGA, and the binary file
(.bit file) is downloaded onto the FPGA, and that makes the FPGA to behave
according to the ‘logic function’.

Points to be remembered:

1. A binary file can be download to FPGAs as many time as we desire - no limits


– with different functionalities every time. If a mistake is made in the design, we
have to fix the ‘logic function’, re-compile and re-download it. No PCB, solder
or component is required to be changed.
2. The designs can run much faster than for a board with discrete components, since
everything runs within the FPGA, on its silicon die.
3. FPGAs lose their functionality when the power goes away (like RAM in a
computer). So, the binary file should be re-downloaded when the power goes
and backed up to restore the functionality.

13.1.3 Spartan-3e FPGA Family: Introduction

The Spartan-3E family of FPGAs is specifically designed to meet the needs of high
volume, cost-sensitive consumer electronic applications. The five-member family offers
densities ranging from 100,000 to 1.6 million system gates, as shown in Table 13.1.

Table 13.1: Summary of Spartan-3E FPGA chips


Device System Equip- CLB Array Distri- Block Dedica- DCMs Maxi- Maximum
Gates ment (One CLB = Four Slices) buted Ram ted mum Differ-
Logic Rows Columns Total Total RAM bits(1) Multi- User ential IO
Cells CLBs Slices bits(1) pliers IO Pairs

XC3S100E 100K 2,160 22 16 240 960 15K 72K 4 2 108 40


XC3S250E 250K 5,508 34 26 612 2,448 38K 216K 12 4 172 68
XC3S500E 500K 10,476 46 34 1,164 4,656 73k 360k 20 4 232 92
xc3s1200e 1200k 19,512 60 46 2,168 8,672 136k 504k 28 8 304 124
xc3s1600e 1600k 33,192 76 58 3,688 14,752 231k 648k 36 8 376 156
596ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The Spartan-3E family builds on the success of the earlier Spartan-3 family by
increasing the amount of logic per I/O, significantly reducing the cost per logic cell.
New features improve system performance and reduce the cost of configuration. These
Spartan-3E enhancements, combined with advanced 90 nm process technology, deliver
more functionality and bandwidth per dollar than was previously possible, setting new
standards in the programmable logic industry. Because of their exceptionally low cost,
Spartan-3E FPGAs are ideally suited to a wide range of consumer electronics applications,
including broadband access, home networking, display/projection, and digital television
equipment.
The Spartan-3E family is a superior alternative to mask programmed ASICs. FPGAs
avoid the high initial cost, the lengthy development cycles, and the inherent inflexibility
of conventional ASICs. Also, FPGA programmability permits design upgrades in the
field with no hardware replacement necessary, an impossibility with ASICs.

Features of XC3S500E FPGA chip

s Very low cost, high-performance logic solution for high-volume, consumer-oriented


applications.
s Multi-voltage, multi-standard select I/O interface pin
s Up to 376 I/O pins or 156 differential signal pairs
s LVCMOS, LVTTL, HSTL, and SSTL single-ended signal standards
s 3.3 V, 2.5 V, 1.8 V, 1.5 V, and 1.2 V signaling
s 622+ Mbps data transfer rate per I/O
s True LVDS, RSDS, mini-LVDS, differential HSTL/SSTL differential I/O
s Enhanced double data rate (DDR) support.
s DDR SDRAM supports up to 333 Mbps.

Abundant, flexible logic resources

s Densities up to 33,192 logic cells, including optional shift register or distributed


RAM support.
s Efficient wide multiplexers, wide logic.
s IEEE 1149.1/1532 JTAG programming/debug port.

Hierarchical select RAM memory architecture

s Up to 648 Kbits of fast block RAM.


s Up to 231 Kbits of efficient distributed RAM.
s Up to eight digital clock managers (DCMs).
s Frequency synthesis, multiplication, division.
s High-resolution phase shifting.
s Wide frequency range (5 MHz to over 300 MHz).
s Eight global clocks plus eight additional clocks per each half of device,
plus abundant low-skew routing.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ597

s Configuration interface to industry-standard PROMs.


s Low-cost, space-saving SPI serial Flash PROM.
s Parallel NOR Flash PROM.
s Low-cost Xilinx Platform Flash with JTAG.
s Fully supported by Xilinx ISE development system. Synthesis, mapping, placement
and routing.
s Pb-free packaging options.
Architectural overview: The Spartan-3E family architecture consists of five fundamental
programmable functional elements.
Configurable logic blocks (CLBs): These contain flexible look-up tables (LUTs) that
implement logic plus storage elements used as flip-flops or latches. CLBs perform a
wide variety of logical functions as well as store data. CLBs constitute the main logic
resource for implementing synchronous as well as combinatorial circuits. Each CLB
contains four slices, and each slice contains two LUTs to implement logic and two
dedicated storage elements that can be used as flip-flops or latches. LUTs can be used
as a 16×1 memory (RAM16) or as a 16-bit shift register (SRL16), and additional
multiplexers and carry logic simplify wide logic and arithmetic functions. Most general-
purpose logic in design is automatically mapped to the slice resources in the CLBs. Each
CLB is identical, and the Spartan-3E family CLB structure is identical to that for the
Spartan-3 family (Fig. 13.6).

Figure 13.6 CLB locations

Block RAM: It provides data storage in the form of 18-Kbit dual-port blocks. Spartan-3E
devices incorporate 4 to 36 dedicated block RAMs, which are organized as dual-port
configurable 18 Kbit blocks. Functionally, the block RAM is identical to the Spartan-3
598ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

architecture block RAM. Block RAM synchronously stores large amounts of data while
distributed RAM, previously described, is better suited for buffering small amounts of
data anywhere along signal paths. This section describes basic block RAM functions.
Each block RAM is configurable by setting the content’s initial values, default signal
value of the output registers, port aspect ratios, and write modes. Block RAM can be
used in single-port or dual-port modes.
Configuration: Spartan-3E FPGAs are programmed by loading configuration data into
robust, reprogrammable, static CMOS configuration latches (CCLs) that collectively
control all functional elements and routing resources. The FPGA’s configuration data is
stored externally in a PROM or some other non-volatile medium, either on or off the
board. After applying power, the configuration data is written to the FPGA using any
of the six different modes:
1. Master serial from a Xilinx platform flash PROM.
2. Serial peripheral interface (SPI) from an industry-standard SPI serial flash.
3. Byte peripheral interface (BPI), up or down, from an industry-standard X8 or X8/
X16 parallel NOR flash.
4. Slave serial, typically downloaded from a processor.
5. Slave parallel, typically downloaded from a processor.
6. Boundary scan (JTAG), typically downloaded from a processor or system.
We used the JTAG configurational mode.

Merits of FPGA

s FPGA-based design has a very short turn-around time, i.e., the time required from
the start of the design process until a functional chip is available.
s No physical manufacturing step is necessary for customizing the FPGA chip.
s FPGA offers a very valuable option.
s Offers a tightly integrated design environment for high-complexity FPGA design.
s Easy to learn and use.

Demerits of FPGA

s The typical price of FPGA chips is usually higher than other alternatives of the
same design, but for small volume production of chips and fast prototyping.
s FPGA chip is volatile.

13.2 SPARTAN-3E KIT: A POPULAR KIT TO LEARN AND UNDERSTAND


FPGA DESIGN FLOW BASICS
[Link: xilinx.com/products/boards-and-kits/1-elhacw.html]
13.2.1 Overview of Spartan-3E

The Spartan-3E starter board provides a powerful and highly advanced self-contained
development platform for designs targeting the Spartan 3E FPGA from Xilinx. It features
a 500 K gate Spartan-3E FPGA with a 32-bit RISC processor and DDR interfaces. The
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ599

board also features a Xilinx platform flash, USB and JTAG parallel programming
interfaces with numerous FPGA configuration options via the onboard Intel strata flash
and ST Microelectronics serial flash. The board is fully compatible with all versions of
the Xilinx ISE tools including the free webPACK. The board is shipped with a power
supply and USB cable for programming so that designs can be implemented immediately
with no hidden costs. The Spartan-3E starter board is also compatible with the micro
blaze embedded development kit (EDK) and pico blaze from Xilinx.

13.2.2 Key Components and Features

The key features of the Spartan-3E starter kit board are:


s Xilinx XC3S500E Spartan-3E FPGA
» Up to 232 user-I/O pins
» 320-pin FBGA package
» Over 10,000 logic cells
s Xilinx 4 Mbit platform flash configuration PROM
s Xilinx 64-macrocell XC2C64A Cool Runner CPLD
s 64 MB (512 Mbit) of DDR SDRAM, ×16 data interface, 100+ MHz
s 16 MB (128 Mbit) of parallel NOR flash (Intel strata flash)
» FPGA configuration storage
» Micro blaze code storage/shadowing
s 16 Mbits of SPI serial flash (STMicro)
» FPGA configuration storage
» Micro blaze code shadowing
s 2-line, 16-character LCD screen
» PS/2 mouse or keyboard port
» VGA display port
» 10/100 Ethernet PHY (requires Ethernet MAC in FPGA)
» Two 9-pin RS-232 ports (DTE- and DCE-style)
» On-board USB-based FPGA/CPLD download/debug interface
» 50 MHz clock oscillator
» SHA-1 1-wire serial EEPROM for bit stream copy protection
» Hirose FX2 expansion connector
» Three Diligent 6-pin expansion connector
» Four-output, SPI-based digital-to-analog converter (DAC)
» Two-input, SPI-based analog-to-digital converter (ADC) with programmable-
gain pre-amplifier
» Chip Scope™ Soft Touch debugging port
» Rotary encoder with push-button shaft
» Eight discrete LEDs
» Four slide switches
600ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Design trade-offs: A few system-level design trade-offs are required in order to provide
the Spartan-3E starter kit board with most functionality.

13.2.3 Configuration Methods Galore


A typical FPGA application uses a single non-volatile memory to store configuration
images. To demonstrate new Spartan-3E capabilities, the starter kit board has three
different configuration memory sources that all need to function well together. The extra
configuration functions make the starter kit board more complex than typical Spartan-3E
applications. The starter kit board also includes an onboard USB-based JTAG programming
interface. The on-chip circuitry simplifies the device programming experience. In typical
applications, the JTAG programming hardware resides off-board or in a separate
programming module, such as the Xilinx platform USB cable.

Voltages for all Applications


The Spartan-3E starter kit board showcases a triple-output regulator developed by Texas
Instruments, the TPS75003, specifically to power Spartan-3 and Spartan-3E FPGAs.
However, the starter kit board includes DDR SDRAM, which requires its own high-
current supply. Similarly, the USB-based JTAG download solution requires a separate
1.8 V supply.

13.2.4 Switches, Buttons, and Knobs


Slide switches
Locations and labels: The Spartan-3E starter kit board has four slide switches. The slide
switches are located in the lower right corner of the board and are labeled SW3 through
SW0. Switch SW3 is the left-most switch, and SW0 is the right-most switch (Fig. 13.7).

Figure 13.7 Four slide switches


’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ601

Operation: When in the UP or ON position, a switch connects the FPGA pin to 3.3 V, a
logic ‘high’. When DOWN or in the OFF position, the switch connects the FPGA pin to
the ground, a logic ‘low’. The switches typically exhibit about 2 ms of mechanical bounce,
and there is no active debouncing circuitry, although such circuitry could easily be
added to the FPGA design programmed on the board.
UCF location constraints: (Fig. 13.8) provides the UCF constraints for the four slide
switches, including the I/O pin assignment and the I/O standard used. The PULLUP
resistor is not required, but it defines the input value when the switch is in the middle
of a transition.

Figure 13.8 UCF Constraints for slide switches

Push-button switches

Locations and labels: The Spartan-3E starter kit board has four momentary contact push-
button switches, shown in Fig. 13.9. The push-buttons are located in the lower left corner
of
the board and are labeled BTN_NORTH, BTN_EAST, BTN_SOUTH, and BTN_WEST.

Figure 13.9 Four push-button switches surround rotary push-button switch

Operation: Pressing a push button connects the associated FPGA pin to 3.3 V, as shown
in Fig. 13.10. Use an internal pull-down resistor within the FPGA pin to generate a logic
‘low’ when the button is not pressed. There is no active debouncing circuitry on the
push-button.
602ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 13.10 Push-button switches require an internal pull-down

UCF location constraints: The UCF constraints for the four push-button switches,
including the I/O pin assignment and the I/O standard used and defines a pull-down
resistor on each input (Fig. 13.10).

Figure 13.11 UCF constraints for push-button switches

Rotary push-button switch

Locations and labels: The rotary push-button switch is located in the center of the four
individual push-button switches. The switch produces three outputs. The two shaft
encoder outputs are ROT_A and ROT_B. The center push-button switch is
ROT_CENTER.
Operation: The rotary push-button switch integrates two different functions. The switch
shaft rotates and outputs values whenever the shaft turns. The shaft can also be pressed,
acting as a push-button switch.
Push-button switch: Pressing the knob on the rotary/push-button switch connects the
associated FPGA pin to 3.3 V, as shown in Fig. 13.12. Use an internal pull-down resistor
within the FPGA pin to generate a logic ‘low’. There is no active debouncing circuitry
on the push-button.

Figure 13.12 Push-button switches require an internal pull-up


’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ603

Discrete LEDs

Locations and labels: The Spartan-3E starter kit board has eight individual surface-
mount LEDs located above the slide switches as shown in Fig. 13.13. The LEDs are
labeled LED7 through LED0. LED7 is the left-most LED, LED0 the right-most LED.

Figure 13.13 Eight discrete LEDs

UCF location constraints: Figure 13.14 provides the UCF constraints for the four push-
button switches, including the I/O pin assignment, the I/O standard used, the output
slew rate, and the output drive current.

Figure 13.14 UCF constraints for eight discrete LED

13.2.5 Clock Sources

Overview: As shown in Fig. 13.15, the Spartan-3E starter kit board supports three primary
clock input sources, all of which are located below the Xilinx logo, near the Spartan-3E
logo.
s The board includes an onboard 50 MHz clock oscillator.
s Clocks can be supplied off-board via an SMA-style connector. Alternatively, the
FPGA can generate clock signals or other high-speed signals on the SMA-style
connector.
s Optionally, install a separate 8-pin DIP-style clock oscillator in the supplied socket.
604ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 13.15 Available clock inputs

Clock connection: Each of the clock inputs connect directly to a global buffer input in
I/O Bank 0, along the top of the FPGA. As shown in Table 13.1, each of the clock inputs
also optimally connects to an associated DCM.
Voltage control: The voltage for all I/O pins in FPGA I/O Bank 0 is controlled by jumper
JP9. Consequently, these clock resources are also controlled by jumper JP9. By default,
JP9 is set for 3.3 V. The onboard oscillator is a 3.3 V device and might not perform as
expected when jumper JP9 is set for 2.5 V.
50 MHz onboard oscillator: The board includes a 50 MHz oscillator with a 40% to 60%
output duty cycle. The oscillator is accurate to ±2500 Hz or ±50 ppm.
Auxiliary clock oscillator socket: The provided 8-pin socket accepts clock oscillators
that fit the 8-pin DIP footprint. Use this socket if the FPGA application requires a
frequency other than 50 MHz. Alternatively, use the FPGA’s digital clock manager
(DCM) to generate or synthesize other frequencies from the onboard 50 MHz oscillator.
SMA clock input or output connector: To provide a clock from an external source,
connect the input clock signal to the SMA connector. The FPGA can also generate a
single-ended clock output or another high-speed signal on the SMA clock connector for
an external device.
UCF constraints: The clock input sources require two different types of constraints. The
location constraints define the I/O pin assignments and I/O standards. The period
constraints define the clock period—and consequently the clock frequency—and the
duty cycle of the incoming clock signal.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ605

Location: Figure 13.16 provides the UCF constraints for the three clock input sources,
including the I/O pin assignment and the I/O standard used. The settings assume that
jumper JP9 is set for 3.3 V. If JP9 is set for 2.5 V, adjust the IOSTANDARD settings
accordingly.

Figure 13.16 UCF location constraints for clock sources

Clock period constraints: The Xilinx ISE development software uses timing-driven logic
placement and routing. Set the clock ‘period’ constraint as appropriate. An example
constraint appears for the onboard 50 MHz clock oscillator. The CLK_50MHZ frequency
is 50 MHz, which equates to a 20 ns period. The output duty cycle from the oscillator
ranges between 40% and 60%.

Figure 13.17 UCF clock ‘period’ constant

13.2.6 FPGA Configuration Options

The Spartan-3E starter kit board supports a variety of FPGA configuration options:
s Download FPGA designs directly to the Spartan-3E FPGA via JTAG, using the
onboard
s USB interface. The onboard USB-JTAG logic also provides in-system programming
for the onboard platform flash PROM and the Xilinx XC2C64A CPLD.
s SPI serial flash and strata flash programming are performed separately.
s Program the onboard 4 Mbit Xilinx XCF04S serial platform flash PROM, then
configure the FPGA from the image stored in the platform flash PROM using the
master serial mode.
s Program the onboard 16 Mbit ST Microelectronics SPI serial flash PROM, then
configure the FPGA from the image stored in the SPI serial flash PROM using the
SPI mode.
s Program the onboard 128 Mbit Intel strata flash parallel NOR flash PROM, then
configure the FPGA from the image stored in the flash PROM using BPI up or
BPI down configuration modes. N FPGA applications can dynamically load two
different FPGA configurations using the Spartan-3E FPGA’s multi-boot mode.
s Figure 13.18 indicates the position of the USB download/programming interface
and the onboard non-volatile memories that potentially store FPGA configuration
images. Figure 13.19 provides additional details on configuration options.
606ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 13.18 Spartan-3E starter kit FPGA configuration options

Figure 13.19 Detailed configuration options

The configuration mode jumpers determine which configuration mode the FPGA uses
when power is first applied, or whenever the PROG button is pressed. The DONE pin
LED lights when the FPGA successfully finishes the configuration. Pressing the PROG
button forces the FPGA to restart its configuration process. The 4 Mbit Xilinx platform
flash PROM provides easy, JTAG-programmable configuration storage for the FPGA.
The FPGA configures from the platform flash using the master serial mode.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ607

The 64-macrocell XC2C64A Cool Runner II CPLD provides additional programming


capabilities and flexibility when using the BPI up, BPI down, or multi-boot configuration
modes and loading the FPGA from the strata flash parallel flash PROM. The CPLD is
user programmable.

13.2.7 Configuration Mode Jumpers

The J30 jumper block settings control the FPGA’s configuration mode. Inserting a jumper
grounds the associated mode pin. Insert or remove individual jumpers to select the
FPGA’s configuration mode and associated configuration memory source.

Table 13.2: Spartan 3E configuration mode jumper settings


Configuration Mode Pins FPGA Configuration Image Source Jumper Setting
Mode M2:M1:M0
Master Serial 0:0:0 Platform Flash PROM

SPI ("SPI Serial 1:1:0 SPI Serial FlashPROM starting at


Flash") address 0

BPI Up "Intel 0:1:0 StrataFlash parallel Flash PROM,


Stratal Flash starting at address 0 and
Parallel NOR Flash incrementing through address
PROM space. The CPLD controls address
lines A[24:20] during BPI
configuration
BPI Down "Intel 0:1:1 StrataFlash parallel Flash PROM,
Stratal Flash starting at address 0× 1FF_FFFF
Parallel NOR Flash and decrementing through address
PROM space. The CPLD controls address
lines A[24:20] during BPI
configuration
JTAG 0:1:0 Download from host via USB-JTAG
port

PROG push-button: The PROG push-button forces the FPGA to reconfigure from the
selected configuration memory source. Press and release this button to restart the FPGA
configuration process at any time.
608ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

DONE pin LED: The DONE pin LED lights whenever the FPGA is successfully
configured. If this LED is not lit, then the FPGA is not configured.
Programming the FPGA, CPLD, or platform flash PROM via USB: The Spartan-3E
starter kit includes embedded USB-based programming logic and a USB endpoint with
a Type B connector. Via a USB cable connection to the host PC, the iMPACT programming
software directly programs the FPGA, the platform flash PROM, or the onboard CPLD.
Direct programming of the parallel or serial flash PROMs is not presently supported.
Connecting the USB cable: The kit includes a standard USB Type A/Type B cable.

Figure 13.20 Standard USB Type A/Type B

The wider and narrower Type A connector fits the USB connector at the back of the
computer.
After installing the Xilinx software, connect the square Type B connector to the
Spartan-3E starter kit board. The USB connector is on the left side of the board,
immediately next to the Ethernet connector. When the board is powered on, the Windows
operating system should recognize and install the associated driver software (Fig. 13.21).

Figure 13.21 Connecting the USB Type B connector to the starter kit board connector

When the USB cable driver is successfully installed, and the board is correctly connected
to the PC, a green LED lights up, indicating a good connection.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ609

Programming via iMPACT: After successfully compiling an FPGA design using the
Xilinx development software, the design can be downloaded using the iMPACT
programming software and the USB cable. To begin the programming, connect the USB
cable to the starter kit board and apply power to the board. Then, double-click Configure
Device (iMPACT) within Project Navigator (Fig. 13.22).

Figure 13.22 Double click to invoke iMPACT

13.2.8 RS-232 Serial Ports


Overview: The Spartan-3E starter kit board has two RS-232 serial ports: a female DB9
DCE connector and a male DTE connector. The DCE-style port connects directly to the
serial port connector available on most personal computers and workstations via a
standard straight-through serial cable. Null modem, gender changers, or crossover cables
are not required. Use the DTE-style connector to control other RS-232 peripherals, such
as modems or printers, or perform simple loopback testing with the DCE connector
(Fig. 13.23).

Standard Standard
9-pin serial cable 9-pin serial cable

DCE DTE Pin 1


Pin 5

Pin 9 Pin 6

DCE DCE
Female DB9 Male DB9

5 4 3 2 1 5 4 3 2 1

9 8 7 6 9 8 7 6
J9 J10

GND GND

RS-232 Volatage Translator (IC2)


RS232 DCE RXD

RS232 DCE RXD


RS232 DCE TXD

RS232 DCE TXD

(R7) (M14) (U8) (M13)


Spartan-3E FPGA

UG200_E7_01_022006

Figure 13.23 RS-232 serial ports


610ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

see Fig. 13.23 shows the connection between the FPGA and the two DB9 connectors.
The FPGA supplies serial output data using LVTTL or LVCMOS levels to the Maxim
device, which in turn, converts the logic value to the appropriate RS-232 voltage level.
Likewise, the Maxim device converts the RS-232 serial input data to LVTTL levels for
the FPGA. A series resistor between the Maxim output pin and the FPGA’s RXD pin
protects against accidental logic conflicts.
UCF location constraints: Figure 13.24 and Figure 13.25 provide the UCF constraints
for the DTE and DCE RS-232 ports, respectively, including the I/O pin assignment and
the I/O standard used.

Figure 13.24 UCF location constraints for DTERS-232 serial port

Figure 13.25 UCF location constraints for DCE RS-2323 serial port

13.2.9 Digital to Analog Converter (DAC)

The Spartan-3E starter kit board includes an SPI-compatible, four-channel, serial DAC.
The DAC device is a Linear Technology LTC2624 quad DAC with 12-bit unsigned
resolution. The four outputs from the DAC appear on the J5 header, which uses the
Digilent 6-pin peripheral module format. The DAC and the header are located
immediately above the Ethernet RJ-45 connector (Fig. 13.26).

o
Figure 13.26 Digital-to-analog converter and associated header

SPI communication: The FPGA uses a serial peripheral interface (SPI) to communicate
digital values to each of the four DAC channels. The SPI bus is a full-duplex, synchronous,
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ611

character-oriented channel employing a simple four-wire interface. A bus master—the


FPGA in this example—drives the bus clock signal (SPI_SCK) and transmits serial data
(SPI_MOSI) to the selected bus slave—the DAC in this example. At the same time, the
bus slave provides serial data (SPI_MISO) back to the bus master (Fig. 13.27).

LTC 2624 DAC


Header J5
REF A
VOUTC A
3.3V DAC A
REF B 12
VOUTC
DAC B B
12
REF C
VOUTC C
2.5V DAC C
12
REF D
VOUTC
DAC D D
Spartan-3E FPGA 12
GND
(N10) (T4) SPI_MOSI SDI SDO
(NB) DAC_CS CS/LD
(U16) SPI_SCK SCK SPI Control Interface VCC
(3.3V)
(P8) DAC_CLR
CLR
SPI_MOSI
UG230_C9_02_021506

Figure 13.27 Digital-to-analog connection schematic

Interface signals: The interface signals between the FPGA and the DAC. The SPI_MOSI,
SPI_MISO, and SPI_SCK signals are shared with other devices on the SPI bus. The
DAC_CS signal is the active-low slave select input to the DAC. The DAC_CLR signal
is the active-low, asynchronous reset input to the DAC.

Table 13.3 DAC interface signals


Signal FPGA Pin Direction Description
SPI_MOSI T4 FPGAoDAC Serial data: Master Output, Slave Input
DAC_CS N8 FPGAoDAC Active-Low chip-select. Digital-to-analog
conversion starts when signal returns High.
SPI_SCK U16 FPGAoDAC Clock
DAC_CLR P8 FPGAoDAC Asynchronous, active-Low reset input
SPI_MISO N10 FPGA¨DAC Serial data: Master Input, Skave Output

The serial data output from the DAC is primarily used to cascade multiple DACs.
This signal can be ignored in most applications although it does demonstrate full-duplex
communication over the SPI bus.
Disable other devices on the SPI bus to avoid contention: The SPI bus signals are
shared by other devices on the board. It is vital that other devices are disabled when
612ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

the FPGA communicates with the DAC to avoid bus contention. Table 13.4 provides the
signals and logic values required to disable the other devices. Although the strata flash
PROM is a parallel device, its least significant data bit is shared with the SPI_MISO
signal.

Table 13.4 Disabled devices on the SPI bus


Signal Disabled Device Disable Value
SPI_SS_B SPI serial Flash 1
AMP_CS Programmable pre-amplifier 1
AD_CONV Analog-to-Digital Converter (ADC) 0
SF_CEO StrataFlash Parallel Flash PROM 1
FPGA_INIT_B Platform Flash PROM 1

SPI communication details: Figure 13.28 shows a detailed example of the SPI bus timing.
Each bit is transmitted or received relative to the SPI_SCK clock signal. The bus is fully
static and supports locks rate up to the maximum of 50 MHz. However, check all
timing parameters using the LTC2624 data sheet if operating at or close to the maximum
speed.

Figure 13.28 SPI communication waveforms

After driving the DAC_CS slave select signal Low, the FPGA transmits data on the
SPI_MOSI signal, MSB first. The LTC2624 captures input data (SPI_MOSI) on the rising
edge of SPI_SCK; the data must be valid for at least 4 ns relative to the rising clock
edge.
The LTC2624 DAC transmits its data on the SPI_MISO signal on the falling edge of
SPI_SCK. The FPGA captures this data on the next rising SPI_SCK edge. The FPGA
must read the first SPI_MISO value on the first rising SPI_SCK edge after DAC_CS goes
Low. Otherwise, bit 31 is missed.
After transmitting all 32 data bits, the FPGA completes the SPI bus transaction by
returning the DAC_CS slave select signal ‘high’. The ‘high’-going edge starts the actual
digital-to-analog conversion process within the DAC.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ613

Communication protocol: Figure 13.29 shows the communication protocol required to


interface with the LTC2624 DAC. The DAC supports both a 24-bit and 32-bit protocol.
Inside the DAC, the SPI interface is formed by a 32-bit shift register. Each 32-bit command
word consists of a command, an address, followed by data value. As a new command
enters the DAC, the previous 32-bit command word is echoed back to the master. The
response from the DAC can be ignored although it is useful to confirm correct
communication.

Figure 13.29 SPI communications protocol to LTC2624 DAC

The FPGA first sends eight dummy or ‘don’t care’ bits, followed by a 4-bit command.
The most commonly used command with the board is COMMAND[3:0] = “0011”, which
immediately updates the selected DAC output with the specified data value. Following
the command, the FPGA selects one or all the DAC output channels via a 4-bit address
field. Following the address field, the FPGA sends a 12-bit unsigned data value that the
DAC converts to an analog value on the selected output(s). Finally, four additional
dummy or don’t care bits pad the 32-bit command word.
Specifying the DAC output voltage: Each DAC output level is the analog equivalent
of a 12-bit unsigned digital value, D [11:0], written by the FPGA to the DAC via the SPI
interface. The reference voltage, VREFERENCE, is different between the four DAC
outputs. Channels A and B use a 3.3 V reference voltage and Channels C and D uses a
2.5 V reference. The reference voltages themselves have a ±5% tolerance, so there will
be slight corresponding variances in the output voltage.

DAC outputs A and B

UCF location constraints: Figure 13.30 provides the UCF constraints for the DAC
interface, including the I/O pin assignment and the I/O standard used.
614ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 13.30 UCF location constraints for the DAC interface

13.2.10 Analog Capture Circuit


The Spartan-3E starter kit board includes a two-channel analog capture circuit, consisting
of a programmable scaling pre-amplifier and an analog-to-digital converter (ADC), as
shown in Fig. 13.31. Analog inputs are supplied on the J7 header.

Figure 13.31 Two-channel analog capture circuit

The analog capture circuit consists of a Linear Technology LTC6912-1 programmable


preamplifier that scales the incoming analog signal on header J7 (Fig. 13.32). The output
of the pre-amplifier connects to a Linear Technology LTC1407A-1 ADC. Both the
pre-amplifier and the ADC are serially programmed or controlled by the FPGA.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ615

Header J7
REFAB (3.3V)

REFCD (2.5V)
LTC 6912-1 AMP LTC 1407A-1 ADC

VINA –
+A + A/D
– Channel 0
14
VINB –
+ A/D
+ B
– Channel 1
GND

VCC (3.3V)
14
REF-1.65V

Spartan-3E FPGA
SPI_MOSI
(N10) (T4) DIN 0 1 2 3 0 1 2 3 DOUT 0 – 13 0 – 13 SDO
(E18) (N7) AMP_CS CS/LD A GAIN B GAIN CHANNEL 1 CHANNEL 0
(U16) SPI_SCK SCK SPI Control Interface SCK SPI Control Interface
AMP_SHDN SHDN CONV
(P7)

(P11) AD_CONV

AMP_DOUT
SPI_MISO

Figure 13.32 Detailed view of analog capture circuit

13.2.11 Digital Outputs from Analog Inputs

The analog capture circuit converts the analog voltage on VINA or VINB and converts
it to a 14-bit digital representation, D[13:0]. The GAIN is the current setting loaded into
the programmable pre-amplifier. The various allowable settings for GAIN and allowable
voltages applied to the VINA and VINB inputs. The reference voltage for the amplifier
and the ADC is 1.65 V, generated via a voltage divider shown in Fig. 13.32. Consequently,
1.65 V is subtracted from the input voltage on VINA or VINB.
The maximum range of the ADC is ±1.25 V, centered around the reference voltage,
1.65 V. Hence, 1.25 V appears in the denominator to scale the analog input accordingly.
Finally, the ADC presents a 14-bit, two’s complement digital output.

13.2.12 Analog to Digital Converter (ADC)

The LTC1407A-1 provides two ADCs. Both analog inputs are sampled simultaneously
when the AD_CONV signal is applied.
616ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Interface: Table below lists the interface signals between the FPGA and the ADC. The
SPI_MOSI, SPI_MISO, and SPI_SCK signals are shared with other devices on the SPI
bus. The DAC_CS signal is the active-low slave select input to the DAC. The DAC_CLR
signal is the active-low, asynchronous reset input to the DAC.

Table: ADC interface signals


Signal FPGA Pin Direction Description
SPI_SCK U16 FPGAoADC Clock
AD_CONV P11 FPGAoADC Active-High shutdown and reset
SPI_MISO N10 FPGA¨ADC Serial data: Master Input, Serial Output.
Presents the digital representation of the
sample analog values as two 14-bit two's
complement binary values.

SPI control interface: Figure 13.33 provides an example SPI bus transaction to the ADC.
When the AD_CONV signal goes ‘high’, the ADC simultaneously samples both analog
channels. The results of this conversion are not presented until the next time AD_CONV
is asserted, a latency of one sample. The maximum sample rate is approximately 1.5
MHz. The ADC presents the digital representation of the sampled analog values as a
14-bit, two’s complement binary value.

Figure 13.33 Analog-to-digital conversion interface

Figure 13.33 shows detailed transaction timing. The AD_CONV signal is not a
traditional SPI slave select enable. Be sure to provide enough SPI_SCK clock cycles so
that the ADC leaves the SPI_MISO signal in the high-impedance state. Otherwise, the
ADC blocks communication to the other SPI peripherals. As shown in Fig. 13.34, use a
34-cycle communications sequence. The ADC 3-states its data output for two clock cycles
before and after each 14-bit data transfer.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ617

Figure 13.34: Detailed SPI timing to ADC

UCF location constraints: Figure 13.35 provides the user constraint file (UCF) constraints
for the amplifier interface, including the I/O pin assignment and I/O standard used.

Figure 13.35: UCF constraints

Disable other devices on the SPI bus to avoid contention: The SPI bus signals are
shared by other devices on the board. It is vital that other devices are disabled when
the FPGA communicates with the AMP or ADC to avoid bus contention. Although the
strata flash PROM is a parallel device, its least significant data bit is shared with the
SPI_MISO signal. The platform flash PROM is only potentially enabled if the FPGA is
set up for Master Serial mode configuration.

13.3 UNDERSTAND IMPLEMENTATION & DESIGN FLOW BY USING XILINX


ISE WEBPACK 11.1
[You may refer xilinx website for latest versions in future]

The most popular trend currently is to design in HDL at an RTL level, because logic
synthesis tools can create gate level netlists from RTL level design. Behavioral synthesis
allowed engineers to design directly in terms of algorithms and the behavior of the
circuit, and then use EDA tools to do the translation and optimization in each phase of
the design. Verilog HDL is also constantly enhanced to meet the new verification
methodology.
618ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

13.3.1 Introduction

The newest version of ISE, Version 11.1, adds more innovative technology to help lower
logic development and production costs. ISE 11.1 delivers faster performance than any
other PLD offering , unequaled high-speed design capabilities, and the easiest to use
design software available. ISE slashes design and verification times. Unparalleled ease-
of-use is a big part of ISE 11.1. With the release of ISE 11.1, Xilinx is now able to offer
customers an integrated simulation solution with the new ISE Simulator. Every ISE
BaseX and ISE Foundation customer has access to a limited version called ISE Simulator
Lite. ISE Foundation customers can upgrade to the ISE Simulator.

13.3.2 Configuration

The Xilinx ISE 11.1 software release offers three design configurations, all delivered
under the Integrated Software Environment (ISE) design family.
ISE Foundation 11.1: ISE Foundation is the industry’s most complete programmable
logic design performance. This ISE configuration supports all of Xilinx ‘lead’ logic families
and provides everything needed to complete any Xilinx design, seamlessly integrating
with the industry’s most advanced verification products. Xilinx also offers optional
productivity tools designed to work together with ISE Foundation.
Modelsim Xilinx: Modelsim is a complete PC VHDL simulation environment that
enables designers to verify the VHDL source code and functional and timing models of
their designs. Modelsim includes a complete HDL simulation and debugging environment
providing VHDL and Verilog language coverage, a source code viewer/editor, waveform
viewer, design structure browser, list window, and a host of other features designed to
enhance productivity.
Generator: System Generator for DSP is the industry’s premier software tool for
designing, simulating, and implementing high-performance FPGA-based DSP systems.
Using System Generator greatly shortens the path from design concept to working
hardware through simplicity, flexibility, speed, power, and accuracy.

13.3.3 Support

Xilinx support services offer an extension of a company’s design team. Xilinx delivers
comprehensive support services including:
s Support.xilinx.com: a designer-centric website that is available 24 hours a day,
seven days a week
s Worldwide phone-based support during working hours
s XPERTS Certified Third Party Consultants Program
s Customer Education Services
s The IP Center: a web-based resource for Cores IP
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ619

13.3.4 Steps for Simulation


There are four fundamental steps in all digital logic design. These consist of:
1. Design – The schematic or code that describes the circuit.
2. Synthesis – The intermediate conversion of human readable circuit description
to FPGA code (EDIF) format. It involves syntax checking and combining of all
the separate design files into a single file.
3. Place and Route – Where the layout of the circuit is finalized. This is the translation
of the EDIF into logic gates on the FPGA.
4. Program – The FPGA is updated to reflect the design through the use of
programming (.bit) files.
There are two sections of ‘design’ for this lab. The first is the VHDL program design of
what the project has to do, where the circuit in question will be implemented. The second
step is the ‘testbench’ simulation. As its name implies, it is used for testing the project
by simulating the result of driving the inputs and observing the outputs to verify your
design. The software package to be used is the Xilinx ISE 11.1. ISE has the capability of
implementing a variety of different design methodologies including Schematic Capture,
Finite State Machines, and Hardware Descriptive Language (VHDL or Verilog). ISE also
provides its own simulation tool to test your designs before setting them on the FPGA.

13.3.5 Implementation
Open the Xilinx ISE Project Navigator by selecting it from the start menu or the desktop
icon (Fig. 13.36).
Step-1

Figure 13.36 To write and run the VHDL program into the Xilinx, project navigator
620ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step-2

Figure 13.37 First go to FILE and select NEW PROJECT

Step-3

Figure 13.38 Select device family and generated simulation language


(In my project, I have selected Sparten-3e and VHDL)
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ621

Step-4

Figure 13.39 A window will appear which mention for the click on finish

Step-5

Figure 13.40 Add source to the project by creating new from the file
622ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step-6

Figure 13.41 Make a text file to write the VHDL code in it

Step-7

Figure 13.42 Add all the text (.vhd) and an ucf (.ucf) file in the project
then synthesize, implement it and generate a bit file
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ623

13.3.6 Example

Given below is a small VHDL program


entity XNOR2 is
port (A,B: in std_logic; z: out std_logic);
end XNOR 2;
architecture behavioural _xnor of XNOR2 is—signal declaration
(of internal signals X,Y) signal X,Y: std_logic;
begin
X<= A and B;
Y<= (not A) and (not B);
z<= X or Y;
END behavioural _xnor;
Entity XNOR has been defined. Here A and B are defined as input ports, and z is the
output port. The keywords in and out following the colon define it as input and output
ports respectively.
Architecture defines the black box that we described using ENTITY, which in our case
is XNOR2. The architecture can be behavioral or structural models.
The main program starts with begin and describes the implementation of XNOR gate.

13.3.7 Synthesizing the Circuit to the Xilinx FPGA

The ISE WebPACK tool synthesizes the VHDL model to something that can be mapped
to the Xilinx FPGA. That is, the VHDL code will be converted by ISE to some gates that
are on the FPGA.
624ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

ISE will convert the VHDL project description into a set of configuration bits that are
used to program the Xilinx FPGA. Those configuration bits are in a .bit file and are
downloaded to the Xilinx FPGA.
1. The constraints are needed to lay the components mentioned on the Xilinx FPGA
on the Spartan-3E board. It should be set in Processes pane and select I/O Pin
Planning – Presynthesis from the User Constraints tab.
2. With the source file selected, double click the Implement Design process in the
Processes tab. This will translate the design to something that can physically be
mapped to the particular FPGA (xc3s500e-5fg320). A green check mark indicates
that translation process finished successfully.
3. Implement Design process consists of three parts:
s Translate: Translate is the first step in the implementation process. The Translate
process merges all of the input netlists and design constraint information and
outputs a Xilinx NGD (Native Generic Database) file. The output NGD file can
then be mapped to the targeted FPGA device.
s Map: Mapping is the process of assigning a design’s logic elements to the specific
physical elements that implement logic functions in a device. The Map process
creates an NCD (Native Circuit Description) file. The NCD file will be used by
the PAR process.
s Place and Route (PAR): PAR uses the NCD file created by the Map process to
place and route your design. PAR outputs an NCD file that is used by the bit
stream generator (BitGen) to create a .bit file. The .bit file is used actually to
program the FPGA.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ625

4. Generate Programming File: This will generate the actual configuration bits into
a .bit file.
5. Now the Spartan-3E board can be programmed using the iMPACT tool and the
USB cable. The configuration options should be correctly set. The configuration
options are at the top of the board near the RS232 interfaces.

The jumpers on the J30 headers must be set for JTAG programming. This means
that only the middle pins of the header should have a jumper on them.
626ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

6. Then power is plugged into the Spartan-3E board and is connected to USB cable
between the Spartan-3E and your PC. As the power is turned ON, the PC
recognizes the Xilinx cable/board and install the drivers.
7. The Process Configure Target Device to start up the iMPACT tool to program the
FPGA.
8. A message is shown on the screen to be clicked OK.

9. Then a window for the iMPACT tool is generated.

10. Boundary Scan in the iMPACT Flows pane is selected. Right click for initiating
the chain and configuration file (.bit file) is assigned to each of the programmable
chips on the Spartan-3E board.
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ627

Each of the chips can be chosen to open a file (attach a .bit file to that chip) or
to bypass. You should choose bypass for the other two chips.
11. In the iMPACT screen, the following window is seen which shows the
programmable chips and the associated bit files or bypasses configurations.

12. Spartan-3E (the xc3s500e) is selected and right click to get a dialog Select Program
in this dialog to program the FPGA.
628ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

There is an indication on the screen that the programming has succeeded. The
xc-done LED (a little yellow LED underneath the J30 jumper on the board) light
up.
13. The circuit is ready to be run on the Spartan-3E board.
Note: You may read industrial implementation of FPGA using LabVIEW in Chapter 19.

REFERENCES

1. httpl://www.xilinx.com
2. http://www.altera.com

REVIEW QUESTIONS

1. What is a synthesis in FPGA?


2. Explain what are Synthesis, Map, and Implement in FPGA?
3. What is bit file in FPGA?
4. Do you think you can implement a UART in FPGA?
5. Draw the four clocking modes in SPI and explain.
6. Give introduction about FPGA.
7. Give the architecture of FPGA.
8. Write the features of XC3S500E FPGA.
9. Write merits and demerits of FPGA over microcontroller?

ANSWERS

1. Synthesis is the process of converting the algorithm in the RTL code into a set of
realizable hardware components like AND, OR gates, etc. In the case of FPGA
synthesis, these components are called primitives supplied along with FPGA
tools, and in the case of asic synthesis these components are called asic library
components developed by a particular asic library developer. So in effect, the
synthesis tool uses these libraries or primitives and RTL code and turns it into a
standard gate level netlist which is, in turn, fed to an FPGA PAR (place and route)
tool or asic par tool to do the actual physical synthesis.
2. A field-programmable gate array (FPGA) is an integrated circuit designed to be
configured by a customer or a designer after manufacturing—hence ‘field-
programmable’. The FPGA configuration is generally specified using a hardware
description language (HDL), similar to that used for an application-specific
integrated circuit (ASIC). The FPGA is a semiconductor device that can be
programmed after manufacturing. Instead of being restricted to any predetermined
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ629

hardware function, an FPGA allows you to program product features and


functions, adapt to new standards and reconfigure hardware for specific
applications even after the product has been installed in the field—hence the
name ‘field-programmable’. You can use an FPGA to implement any logical
function that an application-specific integrated circuit (ASIC) could perform, but
the ability to update the functionality after shipping offers advantages for many
applications.
Programming FPGA: To define the behavior of the FPGA, the user provides a
hardware description language (HDL). Synthesis is the process of converting RTL
language into gate level language, and hence, into a field programmable gate
array. Then, using an electronic design automation tool, a technology-mapped
netlist is generated. The netlist can then be fitted to the actual FPGA architecture
using a process called place-and-route, usually performed by the FPGA Company’s
proprietary place-and-route software. The user will validate the map, place and
route results via timing analysis, simulation, and other verification methodologies.
Once the design and validation process is complete, the binary file generated
(also using the FPGA company’s proprietary software) is used to (re)configure
the FPGA. This file is transferred to the FPGA/CPLD via a serial interface (JTAG)
or an external memory device like an EEPROM. The most common HDLs are
VHDL and Verilog, although, in an attempt to reduce the complexity of designing
in HDLs, which have been compared to the equivalent of assembly languages,
there are moves to raise the abstraction level through the introduction of alternative
languages. National Instrument’s LabVIEW graphical programming language has
an FPGA add-on module available to target and program FPGA hardware.
To simplify the design of complex systems in FPGAs, there exist libraries of
predefined complex functions and circuits that have been tested and optimized
to speed up the design process. These predefined circuits are commonly called
IP cores and are available from FPGA vendors and third-party IP suppliers (rarely
free and typically released under proprietary licenses). Other predefined circuits
are available from developer communities such as Open Cores (typically released
under free and open source licenses such as the GPL, BSD or similar license),
and other sources. In a typical design flow, an FPGA application developer will
simulate the design at multiple stages throughout the design process. Initially,
the RTL description in VHDL or Verilog is simulated by creating test benches to
simulate the system and observe results. Then, after the synthesis engine has
mapped the design to a netlist, the netlist is translated to a gate level description
where simulation is repeated to confirm the synthesis proceeded without errors.
Finally, the design is laid out in the FPGA at which point propagation delays can
be added, and the simulation runs again with these values back- annotated onto
the netlist.
630ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

3. FPGA is the acronym for Field Programmable Gate Array. It is an array of


configurable logic blocks that can be connected together through vast inter-
connection matrix to form complex digital circuits. One of the primary advantages
of the FPGA is its ability to load different hardware personalities depending upon
the needs of specific applications. It can be designed and configured by the
customer or a designer after manufacturing and hence they are called field
programmable.
The bit file contains all of the information necessary to properly configure the
device that was created by the implementation tools for the design. The output
of an FPGA project will be a configuration bit file that can be used to program
an FPGA. The bit file generates the programming file that is required for
downloading the design to the physical device.
The FPGA goes through a compilation process that eventually generates a bit file
which when downloaded in the FPGA configures it to function. If an FPGA is
modified it must be recompiled which overwrites the bit file that is stored on the
development machine. As a result, it is important that a versioning system is in
place to account for both the FPGA as well as the bit file. The bit file cannot be
opened to reference the logic of the application, but it should also be included
in a versioning system because it provides a compiled static file that can be
referenced back to throughout the software development process. If bit file
versioning is implemented the bit file should be renamed to a meaningful value
before it is submitted to source code control for ease of reference. The bit file is
located in a folder called FPGA bit files. Once the development phase of the
FPGA application is complete, the generated bit file needs to be deployed to the
system.
4. YES. A universal asynchronous receive/transmit (UART) is an integrated circuit
which plays the most important role in serial communication. It handles the
conversion between serial and parallel data. A UART is a 40-pin serial chip on
the PC motherboard. During transmission, the UART converts the bytes from the
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ631

PC parallel bus to the serial bit stream. During receiving, the UART builds the
serial bits into a parallel byte and either sends the parallel byte to the CPU or
places it in its buffer. Serial communication reduces the distortion of a signal,
therefore, makes data transfer between two systems separated by great distance
possible. In some complex systems, communications between the master controller
and slaver controllers are implemented by the serial or parallel port. Parallel
communication needs a lot of multi-bit address bus and data bus and it is only
convenient for short distance transmission. Serial communication is another way
of communication used extensively because of its simple structure and long
transmission distance. But sometimes a common serial port could not meet
requirements of complex systems with different baud rates equipment even some
special baud rate equipment. It is impossible to implement this multi-baud rate
communication system without a special baud rate converter. To solve these
problems described as above, we design a multi-channel UART controller based
on FIFO techniques and FPGAs. It can receive data with a UART block at a certain
baud rate and transmit data to sub-equipment with a UART block at the same
baud rate or at another kind of baud rate, which is different from the receiving
baud rate. And it also can be used to reduce time delay between sub-controllers.
FPGA is being used extensively and playing more and more important roles in
the designing of a digital circuit. Its programmable characteristics make circuit
design much more flexible and shorten the time to market. Serial communication
is essential to computers and allows them to communicate with low-speed
peripheral devices, such as the keyboard, the mouse, modems, etc., thus, the
UART or universal asynchronous receiver/transmitter is most important component
required for serial communication.
5. The SPI bus protocol includes four modes. These modes determine the relationship
between the serial clock and the data bits. Many common microcontrollers contain
built-in hardware SPI ports. Some of these controllers make the SPI mode fully
programmable; others allow a more limited selection. In order to have direct
compatibility with the FM25160, the user should select Mode 0. In the SPI
configuration register (if any) for the controller, this requires setting the CPOL
bit to 0 and the CPHA bit to 0. The four modes are illustrated below. In some
cases, users will be emulating the SPI protocol in software using general-purpose
port pins. In this case, the software can be written to manipulate the port pins
to achieve the correct relationship. The correct relationship is shown in the figure
for Mode 0 below.
Note: in the case of a microcontroller host that has port pins with a default high
state, it will be necessary to set the SCK pin to low state manually prior to
beginning a transaction.
The desired relationship for Mode 0 is illustrated below. In order to highlight the
differences, Modes 1 through 3 are also shown.
632ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

6. Field-programmable gate arrays are pre-fabricated silicon devices that can be


electrically programmed to become almost any kind of digital circuit or system.
They have many advantages over application specified integrated circuits.
7. The most common FPGA architecture consists of an array of logic blocks (called
configurable block, LAB, depending on vendor), I/O pads, and routing channels.
Generally, all the routing channels have same width. Multiple I/O pads may fit
into the height of one row or the width of one column in the array.
8. Features of XC3S500E FPGA
’Ž•Ȭ›˜›Š––Š‹•Žȱ ŠŽȱ››Š¢œȱ ǻ œǼȱ ǭȱ  ȱ Šœ’Œœȳ633

s Very low cost, high performance logic solution for high volume, consumer-oriented
application
s Multi voltage, multi-standard select I/O interface pin
s Up to 376 I/O pins or 156 differential signal pairs.
s Enhanced double data rate (DDR support)
s DDR SDRAM up to 333 mbps.
9. Merits of FPGA
s FPGA-based design has a very short turn-around time.
s No physical manufacturing step is necessary for customizing the FPGA chip.
s FPGA offers a very valuable option.
s Easy to learn and use.
Demerits of FPGA
s The typical price of FPGA chips is usually higher than other alternatives of the
same design, but for small volume production of chips and fast prototyping.
s FPGA chip is volatile.
GENERAL PURPOSE INTERFACE
14 BUS (GPIB)

OBJECTIVE

After going through this chapter, the students will be able to understand:
s Talker
s Listener
s GPIB controller
s GPIB read and write
s LabVIEW & GPIB
s EXAMPLE PROJECT

14.1 IEEE-488 INTERFACE BUS (HP-IB/GP-IB)

In the early 1970s, Hewlett-Packard came out with a standard bus (HP-IB) to help support
their own laboratory measurement equipment product lines, which was later adopted
by the IEEE in 1975. This is known as the IEEE Std. 488-1975. The IEEE-488 Interface
Bus (HP-IB) or general purpose interface bus (GP-IB) was developed to provide a means
for various instruments and devices to communicate with each other under the direction
of one or more master controllers. The HP-IB was originally intended to support a wide
range of instruments and devices, from the very fast to the very slow.

14.1.1 Description

The HP-IB specification permits up to 15 devices to be connected together in any given


setup, including the controller if it is part of the system. A device may be capable of
any other three types of functions: controller, listener, or talker. A device on the bus
may have only one of the three functions active at a given time. A controller directs
which devices will be talkers and listeners. The bus will allow multiple controllers, but
only one may be active at a given time. Each device on the bus should have a unique
address in the range of 0-30. The maximum length of the bus network is limited to
20 m of total transmission path length. It is recommended that the bus is loaded with
at least one instrument or device every 2-meter length of cable (4 m is maximum). The
use of GP-IB extenders may be used to exceed the maximum permitted length of 20 m.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ635

14.1.2 Electrical Interface

The GP-IB is a bus to which many similar modules can be directly connected as is shown
in see Fig. 14.1. A total of 16 wires are shown in the figure -- eight data lines and eight
control lines. The bus cables have 24 wires, providing eight additional for shielding and
grounds.

Figure 14.1 IEEE-488 (HP-IB/GP-IB) Bus configuration

The GP-IB defines the operation of a three-wire handshake that is used for all data
transfers in the bus. The bus operation is asynchronous in nature. The data-transfer rate
of the GP-IB is 500 kHz for standard applications and can go up 1 MHz if special
conventions are followed. Each transaction carries 8 bits; the maximum data bandwidth
is of the order of 4 to 8 megabits (1 MB) per second. The bus is a two-way communications
channel and data flows in both directions. Figure 14.2 illustrates the structure of the
GP-IB bus and identifies the 16 connections of the interconnecting cable.

GPIB GPIB GPIB GPIB


Listner Listner Listner Listner
and / or and / or and / or and / or
T alker T alker Talker T alker
DAV
NRFD Handshake Bus
NDAC
IFC
ATN
SR Management Bus
REN
EOI
DIO-1

Data Bus

DIO-8

Figure 14.2 GP-IB instrumentation bus structure


636ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The cabling limitations make it a less-than-ideal choice for large separation between
devices. These limitations can be overcome with bus extenders. Those attempting to use
bus extenders should be aware that a few extenders are as transparent as claimed. This
is especially true in the handling of continuous data and interrupts. In non-extended
environments, it provides an excellent means for high-speed computer control of multiple
devices.
The following table shows the various interface functions, the mnemonics, and the
descriptions.

Table 14.1 GP-IB interface functions


Interface Function Mnemonic Description
Talker (extended talker) T (TE) Device must be able to transmit
Listener (Extended
L (LE) Device must receive commands and data
listener)
Source Handshake SH Device must properly transfer a multiline message
Device must properly receive remote multiline
Acceptor Handshake AH
messages
Device must be able to operate from front panel and
Remote/Local RL
remote information from bus
Device can asynchronously request service from the
Service Request SR
controller
Upon controller request, device must uniquely
Parallel Poll PP
identify itself if it requires service
Device Clear DC Device can be initialized to a predetermined state
A device function can be initiated by the talker on
Device Trigger DT
the bus
Device can send addresses, universal commands,
Controller C
address commands, and conduct polls
This code describes the type of electrical drivers in a
Drivers E
device

The cabling specifications of the GP-IB interface system permit interconnecting all
devices together in a star or linear configuration. The GP-IB connector is a 24-pin ribbon-
type connector.
In summary, see Table 14.2 shows the complete description of the GP-IB data bus.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ637

Table 14.2 GP-IB Data Bus Description


IEEE-488, GP-IB, HP-IB, or IEC-625
Descriptor 8-bit parallel, Arbitration Token passing: the 24-pin Amphenol
Mono- controller Female connector on
directional, addresses equipment
multi-master the next controller Connector chassis.
(token SRQ Service DIO1 1€ €13 DIO5
passing) request DIO2 2€ €14 DIO6
One controller, when the DIO3 3€ €15 DIO7
one controller DIO4 4€ €16 DIO8
talker, several assigns modes
listeners
Sponsor Hewlett-Packard Error handling Parity bit DI07 EOI 5 €17 REN
when
DAV 6€ €18 Gnd
7-bit ASCII
NRFD 7€ €19 Gnd
characters
NDAC 8€ €20 Gnd

Standard IEEE 488, IEC Bus length 15 m


IFC 9€ €21 Gnd
625
SRQ 10€ €22 Gnd
ATN 11€ €23 Gnd
Address 31 devices Driver Special 24 mA
space drivers Shld 12€ €24 Gnd

Data 8-bit parallel Speed 1 MByte/s


format
Transfer Write only, The 488 is most
type talker commonly
toward listener(s) used for data acquisition
or of H-P
commander Remarks peripherals.
toward Programmable
all others interfaces and drivers
exist and
Timing Handshaken References IEEE Computer simplify the
3-wire Society development of
broadcast microprocessor
transfer: interfaces.
DAV data valid
NDAC Not data
accepted
NRFD Not ready
for
data
638ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

14.1.3 HP-IL Variation

Since the introduction of the IEEE-488, technology has produced a generation of medium-
speed, low-power, instrumentation which need to operate in an automatic test system
such as the GP-IB. The HP-IL (Hewlett-Packard Interface Loop), was introduced to meet
this need. The HP-IL is a low-cost, low-power alternative to the GP-IB system. The HP-IL
and GP-IB provide the same basic functions in interfacing controllers, instruments, and
peripherals, but they differ in many other respects. HP-IL is suitable for use in low-power,
portable applications (typically used for the interface of battery-power systems). The
GP-IB is not practical to operate from battery power. The HP-IL maximum data rate is
20 KBPS. This is a high rate compared to the RS-232C, but much slower than GP-IB.
The HP-IL can operate over distances of up to 100 m between any two devices. Since
it is a loop environment, there is no maximum system cable restriction. The basic device-
addressing scheme allows for up to 30 devices on a loop.

14.2 HISTORY AND CONCEPT

The General Purpose Instrument Bus (GPIB) was developed by Hewlett-Packard


Corporation in 1974 to simplify the interconnection of test instruments with computers.
At that time, computers were bulky and did not have standard interface ports. Instruments
were lucky to have a connector with parallel BCD output lines that could be connected
to a 10 to 20 column printer. Remote control of an instrument was a limited number of
input lines on a rear panel connector that selected a few functions or conversion ranges.
A special computer interface had to be designed and built for each instrument that the
engineer wanted to add to his test system. Even the simplest automated test systems
were several month long projects.
As conceived by HP, the new Hewlett-Packard Instrument Bus (HP-IB) would use a
standard cable to interconnect multiple instruments to the computer. Each instrument
would have its own interface electronics and a standard set of responses to commands.
The system would be easily expandable; so multi-instrument test systems could be put
together by piggybacking cables from one instrument to another. There were restrictions
on the number of instruments that a driver could drive (14) and the length of the bus
cable (20 m).
Hewlett-Packard proposed the concept to the US and international standards bodies
in 1974. It was adopted by the IEC committee in Europe in 1975. In the US, other
instrument companies objected to the HP-IB name and so a new name, the General
Purpose Instrument Bus (GPIB) was created and was formally adopted as the IEEE-STD
488 in 1978.
The IEEE-488 concept of controllers and devices is shown in Fig. 14.3. Controllers
have the ability to send commands, to talk data onto the bus, and to listen to data from
devices. Devices can have ‘talk’ and ‘listen’ capabilities. The control can be passed from
the active controller (Controller-in-Charge) to any device with a controller capability.
One controller in the system is defined as the System Controller and it is the initial
Controller-in-Charge (CIC) (Fig. 14.3).
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ639

Controller Device #1
Control, T alk,
T alk, Listen Listen

Pi ggyback
Cables Device #n
T alk,
Listen

Figure 14.3 IEEE 488 bus concept

Devices are normally addressable and have to have a way to set their addresses. Each
device has a primary address between 0 and 30. Address 31 is the ‘unlisten’ or ‘untalk’
address. Devices can also have secondary addresses that can be used to address device
functions. An example is ICS’s 4896 GPIB-to-Quad Serial Interface, which uses secondary
addresses to address each channel. Although there are 31 primary addresses, IEEE 488
drivers can drive only 14 physical devices (see Fig. 14.4).

INSTRUMENT

GPIB Interface Device


Interface Functions Functions

Figure 14.4 IEEE-488 instrument

14.2.1 Interface Messages

Table 14.3 lists the GPIB interface messages and addresses with their common mnemonics.
MLA, LAD, and UNL are listen addresses with hex values of 20 to 3F. MTA, TAD, and
UNT are talk addresses with hex values of 40 to 5F. A device normally responds to both
talk and listen addresses with the same value, i.e., LAD 4 and TAD 4. Secondary addresses
have hex values of 60 to 7F (see Table 14.3).
Devices are designed with different IEEE-488 capabilities, so not all devices respond
to all of the interface messages. Universal messages are recognized by all devices
regardless of their address state. Address commands are only recognized by devices
that are active listeners.
640ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Table 14.3 488.1 Interface Messages and Addresses


Command Function
Address Commands
MLA My listen address (controller to self)
MTA My talk address (controller to self)
LAD Device listen address (0-30)
TAD Device talk address (0-30)
SAD Secondary Device address
(device optional address of 0-31)
UNL Unlisten (LAD 31)
UNT Listen (TAD 31)
Universal Commands (to all devices)
LLO Local Lockout
DCL Device Clear
PPU Parallel Poll Unconfigure
SPE Serial Poll Enable
SPD Serial Poll Disable
Addressed Commands (to addressed listeners only)
SDC Selected Device Clear
GTL Go to Local
GET Device Trigger
PPC Parallel Poll Configure
TCT Take Control

The IEEE-488 Standard defined an instrument with interface and device partitions as
shown in Fig. 14.4. Interface messages and addresses are sent from the CIC to the device’s
interface function. Instrument particular commands such as range, mode, etc., are data
messages that are passed through the interface to the device.

14.2.2 Physical Bus Structure

Physically, the GPIB bus is composed of 16 low-true signal lines. Eight of the lines are
bidirectional data lines, DIO1-8. Three of the lines, NRFD, NDAC and DAV, are
handshake lines that transfer data from the talker to all devices who are addressed to
listen. The talker drives the DAV line; the listeners drive the NDAC and NRFD lines.
The remaining five lines are used to control the bus’s operation.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ641

ATN (attention) is set to ‘true’ by the CIC while it sends interface messages or device
addresses. ATN is ‘false’ when the bus transmits data.
EOI (end or identify) can be asserted to mark the last character of a message or
asserted with the ATN signal to conduct a parallel poll.
IFC (interface clear) is sent by the system controller to unaddress all devices and
places the interface function in a known quiescent state.
REN (remote enable) is sent by the system controller.
The Standard also defined a Status Byte in the instrument that could be read with a
Serial Poll to determine the device’s status. Bit 6 of the Status Byte is defined as the
Service Request (SRQ) bit that could be set when other bits in the Status Byte are set.
The other bits are user defined. The Service Request pulls the SRQ line low to interrupt
the controller. The Service Request is reset when the device is Serial Polled or when the
service request cause is satisfied.

14.3 THE 488.2 STANDARD

The GPIB concept expressed in IEEE-STD 488 made it easy to interconnect instruments
physically, but it did not make it easy for a programmer to talk to each instrument.
Some companies terminated their instrument responses with a carriage return; others
used a carriage return-linefeed sequence or just a linefeed. Number systems, command
names, and coding depended on the instrument manufacturer. In an attempt to
standardize the instrument formats, Tektronix proposed a set of standard formats in
1985. This was the basis for the IEEE-STD 488.2 standard that was adopted in 1987. At
the same time, the original IEEE-488 Standard was renumbered to 488.1.
The new IEEE-488.2 Standard established standard instrument message formats, a set
of common commands, a standard Status Reporting Structure, and controller protocols
that would unify the control of instruments made by hundreds of manufacturers.
The standard instrument message format terminates a message with a linefeed and
or by asserting EOI on the last character. Multiple commands in the same message are
separated by semicolons. Fixed point data became the default format for numeric
responses.
The common command set defined a subset of ten commands that each IEEE-488.2
compatible instrument must respond to, plus additional optional commands were defined
for instruments with expanded capabilities. The required common commands simplified
instrument programming by giving the programmer a minimal set of commands that
he or she can count on being recognized by each 488.2 instrument. Table 14.4 lists the
488.2 Common Commands and their functions. Probably the most familiar Common
Command is the *IDN? query. This is a good first command to use with an instrument
as its response shows what the instrument is and demonstrates that you have
communication with the instrument. Most of the remaining commands are used with
the Status Reporting Structure.
642ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The IEEE-488.2 Standard Status Reporting Structure is shown in Fig. 14.3. The new
Status Reporting Structure expanded on the 488.1 Status Byte by adding a Standard
Event Status Register (ESR) and an Output Queue. Enable Registers and Summation
Logic were added to the Status Register so that a user could enable selected bits in any
Status Register.
The ESR reports standardized device status and command errors. Bit 6 in the ESR is
not used and can be assigned for any use by the device designer.

14.4 SCPI COMMANDS

The 488.2 Standard had made it easier to communicate with a GPIB instrument, but
each instrument still had a unique command set. Even in a family of instruments from
the same manufacturer, different instruments often had different command sets,
reflecting the ideas of the instrument designer. The US Air Force recognized this problem
in the early 1980s and initiated Project Mate to try to overcome this problem. The Mate
project concept was to create Translation Module Adapters (TMAs) to convert unique
instrument commands into the Air Force’s CIIL language. The TMAs could be external
hardware adapters or internal firmware converters. The Air Force’s CIIL language was
a subset of Atlas. Its drawback was that it did not address the instrument model, and
it had very clumsy construction. The other part of the problem was that CIIL language
instruments, when developed, did not sell well enough to justify the development costs.
Hewlett-Packard worked on the problem, and in 1990, proposed a Test Measurement
Language (TML) that was based on an instrument model. It was a tree-branch type of
language that allowed the same commands to be used for instruments from different
manufacturers. TML included major command branches that could control virtually all
of an instrument’s subsystems. It was an open structure so that other manufacturers
could add commands that they felt necessary. HP offered to license TML to any
instrument manufacturer for a small fee and a pledge to obey the TML specifications.
Almost immediately, Tektronix and a few other companies objected to HP controlling
the TML specification. HP promptly offered it to a consortium which rechristened it as
Standard Commands for Programmable Instruments (SCPI).
The SCPI commands use common command words (keywords) and programming
syntax to give all instruments a common ‘look and feel’. Control of any instrument
capability that is described in SCPI should be implemented exactly as specified.
Guidelines are included for adding new commands in the future without causing
programming problems.
The obvious benefit of SCPI for the ATE programmer is in the reduction of the learning
time for programming multiple SCPI instruments since they all use a common command
language and syntax. The second benefit of SCPI is that its English-like structure and
words are self-documenting, eliminating the need for comments explaining cryptic
instrument commands. The third benefit is the interchangeability of newer SCPI
instruments for older models or another manufacturer’s instrument with the same
capabilities, and a reduction in programming maintenance when devices wear out.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ643

14.4.1 SCPI Command Structure and Examples

A typical response to the last command example in Fig. 14.6 would be 9600;8; XON<nl>.
The response includes three items because the command contains three queries. The
first item is 9600 which is the baud rate; the second item is 8 (bits/word) which is the
current setting. The third item XON means that XON is active. It is always a good idea
to check the device’s error light or read its ESR register with the *ESR? query when first
using a compound command with a device to be sure that it was accepted by the device’s
parser.

14.4.2 SCPI Variables and Channel Lists

SCPI commands are based on a hierarchical structure that eliminates the need for most
multi-word mnemonics. Each keyword in the command steps the device parser out
along the decision branch -- similar to a squirrel hopping from the tree trunk out on
the branches to the leaves. Subsequent keywords are considered to be at the same branch
level until a new complete command is sent to the device. SCPI commands may be
abbreviated as shown by the capital letters in Fig. 14.5 or the whole keyword may be
used when entering a command. (see Fig. 14.5) shows some single SCPI commands for
setting up and querying a serial interface.
SYSTem:COMMunicate:SERial:BAUD 9600 <nl>

‘Sets the baud rate to 9600 baud


SYST:COMM:SER:BAUD? <nl> ‘Queries the baud rate

SYST:COMM:SER:BITS 8 <nl> ‘Sets 8 data bits


Figure 14.5 SCPI Command Examples

Adventurous users may concatenate multiple SCPI commands together on the same
line using semicolons as command separators. The first command is always referenced
to the root node. Subsequent commands are referenced to the same tree level as the
previous command. Starting the subsequent command with a colon puts it back at the
root node. IEEE 488.2 common commands and queries can be freely mixed with SCPI
messages in the same program message without affecting the above rules. see Fig. 14.6
shows some compound command examples.
SYST:COMM:SER:BAUD 9600; BAUD? <nl>

SYST:COMM:SER:BAUD 9600; :SYST:COMM:SER: BITS 8 <nl>


SYST:COMM:SER:BAUD 9600; BAUD?; BITS 8;
BITS?; PACE XON; PACE?<nl>
Figure 14.6 Compound SCPI examples
644ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

SCPI variables are separated by a space from the last keyword in the SCPI command.
The variables can be numeric values, Boolean values or ASCII strings. Numeric values
are typically decimal numbers unless otherwise stated. When setting or querying register
values, the decimal variable represents the sum of the binary bit weights for the bits
with a logic ‘1’ value, e.g., a decimal value of 23 represents 16 + 4 + 2 + 1 or 0001 0111
in binary. Boolean values can be either 0 or 1 or OFF or ON. ASCII strings can be any
legal ASCII character between 0 and 255 decimal except for 10 which is the Linefeed
character.
Channel lists are used as a way of listing multiple values. Channel lists are enclosed
in parentheses and start with the ASCII ‘@’ character. The values are separated by
commas. The length of the channel list is determined by the device. The range of values
is indicated by the two end values separated by a colon. There is a space between the
‘@’ and the first value, e.g. (see Fig. 14.7)

(@ 1,2,3,4) ‘lists sequential values

(@ 1:4) ‘shows a range of sequential


values
(@ 1,5,7,3, 4) ‘lists random values
Figure 14.7 Channel List Examples

14.4.3 SCPI Error Reporting

SCPI provides a means of reporting errors by responses to the SYST:ERR? query. If the
SCPI error queue is empty, the unit responds with 0, ‘No error’ message. The error
queue is cleared at power turn-on, by a *CLS command or by reading all current error
messages. The error messages and numbers are defined by the SCPI specification and
are the same for all SCPI devices.
Now that you have a background on the GPIB bus, you might want to know how to
use the GPIB bus to get things done. This chapter deals with some general suggestions
for putting the system together.

14.4.4 Bus Controllers

Most GPIB bus controllers now are PCs with add-on GPIB Controllers. These add-on
controllers take the following forms:
1. Cards installed in PCs
2. Parallel port to GPIB controllers
3. Serial port to GPIB controllers
4. USB to GPIB controllers
Cards installed in PCs have the benefit of being the lowest cost form of the GPIB
controller. This category includes ISA, AT, and PCI bus cards as well as PCMCIA cards
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ645

for portable computers. GPIB controller cards are also available for the PC/104 bus.
Cards can be obtained from CEC, Computer Boards, Hewlett-Packard, ICS Electronics,
IO-tech, and National Instruments.
Parallel-to-GPIB controllers were popular a couple of years ago but have faded now
that PCMCIA cards are available. Parallel-to-GPIB controllers can still be obtained from
IO-tech and National Instruments.
Serial-to-GPIB controllers can be connected to a computer’s COM port or run at a
remote location by being connected to a modem and phone line. Some Serial-to-GPIB
controllers have RS-422/RS-485 interfaces and can be run at the end of a very long serial
cable. These Serial-to-GPIB Controllers are convenient for adding a GPIB controller to
an older portable computer that does not have a PCMCIA slot. Serial-to-GPIB controllers
can be obtained from Computer Boards, IO-tech, ICS Electronics, and National
Instruments.
ICS and National Instruments make GPIB-to-Serial Converters that can be turned
around and used in a Serial-to-GPIB (S) mode to control a single device. This converter
is not recommend for general use since it has only limited control over only one GPIB
device. They are okay for one-on-one use or in an embedded applications.
USB to GPIB controllers can be connected to the USB connector on the newer PCs.
Requirements are that the computer must run on Windows 98 or Windows 95B (an
OEM version of Windows 95). USB controllers will be available from Computer Boards,
ICS Electronics and National Instruments in 1999.
Whichever GPIB controller you have selected, now is the time to install it. Install and
test it in accordance with the manufacturer’s instructions.

14.4.5 GPIB Cables

Standard GPIB cables can be obtained from a number of sources including your GPIB
controller card manufacturer. They are available with the standard piggyback connectors
at both ends or with a straight-in cable connector on one end of the cable. Use good
quality cables to avoid EMI/RFI problems. If in doubt, ask your GPIB cable provider if
the cables have passed a CE test. If so, they should be able to provide you with a CE
certificate. The total GPIB cable length in a system should not exceed 20 m. For maximum
data transfer rates, cable length should not exceed 2 m between devices.
GPIB cables are often shipped with a ‘brightener’ on the connector contracts. This
‘brightener’ is a waxy organic substance to keep the contacts bright. If you start getting
bad data, clean the cable contacts. Use a mild soap solution (a couple of drops of a dish
detergent in a cup of water) to wash off the brightener. Clean the contacts with alcohol
and blow dry the connector.

14.4.6 Device Addresses

GPIB devices can be assigned any primary address between 0 and 30. Assign a different
address to each GPIB device. Avoid using addresses 0 and 21 as these may be used by
the GPIB controller. GPIB controllers have their own GPIB address. (The GPIB address
646ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

is a software set and is not the GPIB controller card’s internal PC bus address). National
Instruments’ controllers typically use GPIB address 0. HP and ICS Electronics controllers
typically use GPIB address 21. Also don’t use address 31 as a GPIB device address as
31 is the ‘unlisten’ or ‘untalk’ address.
GPIB devices typically use a dip switch with five rockers to set the GPIB address.
The rocker bit weights are 16, 8, 4, 2, and 1. Other rockers may set talk-only or listen-
only modes and should be left off for auto-addressing. Reset the instrument or switch
off the power and back on after changing its address setting.
Some GPIB devices use front panel controls to set their GPIB addresses. These devices
save the GPIB address in a nonvolatile memory. Follow the manufacturer’s instructions
while changing their GPIB address setting.
Some newer GPIB devices like ICS’s Minibox interfaces use SCPI commands to change
and set their GPIB bus address. Use the SYST:COMM:GPIB:ADDR aa command where
aa is the new GPIB address to change the address setting. The address change is
immediate. Next, send the device the *SAV 0 command at its new GPIB address to save
the new address.

14.4.7 Interactive Keyboard Control Programs

Keyboard control programs are programs that let you interactively control and query
a GPIB device by entering device-related commands on the PC keyboard. The better
programs do most of the work for you, so you do not have to know the GPIB command
syntax to use them. Some GPIB controllers are supplied with these kind of programs.
If you have one, use it to check out your GPIB controller and device before writing your
program.
ICS’s GPIBKybd program is a graphical Windows program that let the user control
GPIB devices by simply entering a device-specific message in a text box and by clicking
on buttons to send the message and/or perform a simple command like Serial Poll or
Device Clear. ICS’s GPIBKybd program runs the 488.2 Findlstn protocol to find your
GPIB device(s) when the program is started. The found devices are listed in the Response
box, and the program sets the device address to the lowest found device address. ICS’s
GPIBKybd program interfaces with the GPIB32.DLL so that it can operate GPIB controller
cards from Computer Boards, ICS Electronics, National Instruments and any other
manufacturers who supply an equivalent DLL. You can download a free copy of ICS’s
GPIBKybd program from ICS’s website at http://www.icselect.com/prgupdates.html.
Older control programs like National Instruments’ ibic program are low level, DOS
command line programs that use NI’s older ib commands to control GPIB devices.
National Instruments’ ibic program requires you enter the controller card’s ib type
command to communicate with the device.

14.4.8 Using a Keyboard Control Program

The best way to start with a keyboard controller program is to start with a known good
device. It works best if it is an IEEE-488.2 compatible device.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ647

1. Turn on the device and start the program.


2. Set the program to the same address as the test device. ICS’s GPIBKybd program
should have found the device when it was started. For NI’s ibic, do an ibfind to
get the device handle.
3. Send the device an IFC to clear the GPIB interface by clicking the IFC button. For
NI’s ibic, do an ibsre(0,1) and a SendIFC(0).
4. Send the device the *idn? query and read back the device response. If there is no
response, the device is probably not 488.2 compatible.
5. Perform a Serial Poll to see if the device can respond the GPIB controller. Repeat
the Serial Poll one more time if the first response was not 0.
6. Once you have proved that you have communication with the GPIB device, you
can send to it the device specific commands and read back its responses. The
device specific commands are found in the programming section of the device’s
instruction manual.

14.5 WRITING GPIB PROGRAMS

GPIB programs are simple programs with three major sections: initialization, main body,
and the closing. Most programs use just 6 to 8 commands, so it is not necessary to learn
all of the GPIB commands to develop a good GPIB program. The program complexity
increases as the number of devices being controlled and the number of tests increase.
This chapter provides directions for initializing the GPIB controller and bus, and for
sending data to or reading data back from a GPIB device. Program examples are shown
in BASIC syntax with ICS Electronics and with National Instruments’ style commands.
(NI commands include their original 488 command set and the newer 488.2 command
set.) The directions given can be applied to other manufacturer’s command sets.

14.5.1 GPIB Command Concept

GPIB commands in a program are like the layers of an onion. The inner layer is the
device specific command that you want the device to have, i.e.,
*RST, *IDN? or SYST:COMM:SERIAL:BAUD 9600
The next layer is the command required by your GPIB controller card to send or receive
data or carry out some action on the GPIB bus. Examples are:
ieOutput(DevAddr%, “*RST”) ieEnter(DevAddr%, Rdg$) or
ieTrigger(DevAddr%)
The third layer is the calling convention that your programming language or
programming style dictates. Some commands can be called with the standard CALL
command. Other commands or languages equate an error variable to a return value that
indicates if the command was successfully executed. Some examples are:
CALL ieOutput(DevAddr%, OutputStr$, Len) ioerr% = ieOutput(DevAddr%,
OutputStr$, Len)
648ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

14.5.2 Error Processing

Most GPIB command libraries have a way of determining whether the command was
successfully executed by the GPIB controller. This does not mean that the device did
what you wanted. It was just that the GPIB controller got the command to the device.
The error variable is set when the command is executed. The variable can be set by
equating it to the command because the command returns the error variable. In other
cases, the error is a separate variable that can be checked. It is a good plan to test the
error variable after every command to be sure there were no problems with the command
or with the device. This is done by adding a conditional test to the program after each
instruction.
CALL ieOutput(DevAddr%, OutputStr$, Len) ioerr% = ieOutput(DevAddr%,
OutputStr$, Len) Call ProcessError(ioerr%)
In the above example, the subroutine ProcessError tests the variable. If ioerr% is not
zero, ProcessError will display the appropriate error message in a box to the user.
Examples of the ProcessError routine are found in ICS’s example Visual Basic programs.
Call = Send(Bd, Addr, OutString$, EOTMode) If (ibsta AND EERR)
then
Call ReportError(Addr, “ Did not respond”) End If
In this example, the test was done in the program. If the error variable, ibsta, was
true, then ReportError was called to display the error.

14.5.3 GPIB Controller Initialization

The GPIB controller card is initialized to be sure that it is the system controller and
Controller-in-Charge of the bus. The bus is initialized to be sure that all of the devices
are in a non-addressed state after their power is turned on. This is done by having the
GPIB controller issue an Interface Clear command (IFC pulse) and assert the REN line.
It is also a good idea to check or set the bus timeout. The bus timeout is the amount of
time that the program will wait for a device to respond to a command before proceeding.
In the 488-PC2 command set, this is done with the following commands:
ioerr% =ieInit(IOPort, MyAddr, Setting) ‘initializes the Driver
ioerr% =ieAbort ‘sends IFC, sets REN on ioerr% = ieTimeOut (Time)
‘sets bus timeout
The 488-PC2 command set returns an error status value in the ioerr% variable when
it is finished. If the value is zero, the command was successfully executed. A nonzero
value means the command was not executed correctly and that the device probably was
not there and/or did not receive the output string. When error variables are used, each
command should be followed by a step that calls a routine to check the error variable,
i.e.
ioerr% =ieAbort ‘sends IFC, sets REN on
Call ProcessError (ioerr%) ‘checks the error variable
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ649

In the NI 488.2 command set, the initialization is done with the following commands:
Call SendIFC(Bd%) ‘sends IFC
Call ibsre(Bd%, 1) ‘sets REN on
Call ibtmo(Bd%, T3s) ‘sets Timeout to 3 seconds
EOTMode is a flag that tells the Send command how to terminate the command
string. All IEEE 488 command strings need to be terminated with a linefeed character
or by asserting the EOI line on the last character. If the output data is binary data,
terminate the output by only asserting EOI on the last character. NLend is a predefined
constant that sends a linefeed with EOI asserted after the last data character. The above
command then becomes:
Call = Send(Bd, Addr, OutString$, NLend)

14.5.4 Reading Data from a Device

The NI 488 command ibsre is used to set REN because there does not exist an equivalent
NI 488.2 command. The NI 488 command ibtmo is used to set the timeout because there
does not exist an equivalent NI 488.2 command. T3s is a predefined constant for 3
seconds. If timeout is set to 0 (or TNONE), the GPIB bus (and your program) will be
held as long as it takes for a device to complete its instruction. The 0 setting is not
recommended except when debugging hardware.
NI 488 commands can be included in an NI 488.2 program when there does not exist
an equivalent NI 488.2 function. The NI 488.2 command set returns errors in the command
status in iberr and sets ibsta. ibsta should be checked after every command to be sure
the command was executed correctly.

14.5.5 Sending Data to a Device

Data or device commands are normally sent to a device as strings of ASCII characters.
Typical device commands are DVM setup commands, baud rate commands to a GPIB-
to-Serial converter, or digital data to a parallel interface.
In the 488-PC2 command set, ASCII data is sent by first specifying the string and then
calling the ieOutput command:
Outstring$ = “Command to be sent” L = Len(Outstring$)
ioerr% = ieOutput(DevAddr, OutString$, L)
In the NI 488.2 command set, ASCII data is sent by specifying the output string and
then calling the Send command.
Outstring$ = “Command to be sent”
Call = Send(Bd, Addr, OutString$, EOTMode)
You can also embed the command string in the call line, e.g.
Call = Send(Bd, Addr, “Command to be sent”, EOTMode)
ASCII data strings are read from a device by first specifying an empty string and
then reading the data into the string. Data is read until a terminator is found or the
defined input string is full. Typical terminators are linefeed or EOI asserted on the last
character. An example in the 488-PC2 command set is:
650ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Instring$ = String$(Lin, 32) ‘fills the string with spaces ioerr%


= ieEnter(DevAddr, Instring$, Lin)
where Lin is the length of the input buffer. The 488-PC2 Command Set uses the ieEOL
command to set the input terminator. The ieEOL command defaults to LF or EOI sensed.
In the NI 488.2 command set the input example is:
Instring$ = String$(Lin, 32) ‘fills the string with spaces ioerr%
=Receive(Bd, Addr, Instring$, Term)
Term or termination is the flag used to signal the end of the data. Term can be set to
any ASCII character between 0 and FF HEX, and the Receive process will stop when
that character is detected. If Term is set to the predefined STOPend constant, the Receive
process stops when EOI is detected.

14.5.6 Clearing a Device

Some devices have buffers that accumulate unwanted data, and it occasionally becomes
necessary to clear out the old data or return a device to a known condition. This is done
by sending the device the Device Clear command. In the 488-PC2 command set this is
done with:
ioerr% = ieDevClr(DevAddr)
In the NI 488.2 command set, this is done with:
Call DevClear(Bd, Addr)

14.5.7 Reading the Device Status, Device Addresses

Sometimes it is desirable to read the device’s status register to see if it has data, has a
problem or has completed some task. Devices report their status (status register contents)
in response to Serial Polls. 488.2 devices also report their status in response to the *STB?
query. Consult the device’s instruction manual for the meaning of the bits in its status
register.
In the 488-PC2 command set, the status register is serial polled and the value placed in
the DevStatus variable by:
DevStatus = ieSPoll(DevAddr)
For the NI 488.2 command set use:
Call ReadStatusByte(Bd, Addr, DevStatus)

14.5.8 Sending Bus Interface Messages and Addresses to a Device

Sometimes it is necessary to send bus interface messages or address commands to a


device to address a device as a talker or as a listener or to enter a special configuration
mode. Interface messages or addresses are sent to a device with ATN on. They can be
represented by an equivalent ASCII character. Refer to Chapter 1 for a list of these
commands.
The 488-PC2 command set uses the interface message mnemonics. The user specifies
the command string and then calls the ieSend command. The ieSend command interprets
the mnemonics and converts them into GPIB bus bytes. In the following example,
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ651

CmdStr$ is set to the escape sequence used with some of ICS’s Miniboxes to put them
in their command mode. Consult the GPIB controller’s command reference section for
the ieSend command mnemonics.
CmdStr$ = “UNL LISTEN 4 UNL LISTEN 4 UNL” L = Len (CmdStr$)
ioerr% = ieSend(DevAddr, CmdStr$, L)
In the NI 488.2 command set, the interface messages and addresses are sent by specifying
the equivalent ASCII characters, i.e.,
CmdStr$ = Chr$(&H3F) + CHR$(Addr + 32)+ Chr$(&H3F) + CHR$(Addr
+ 32) + Chr$(&H3F)
Call SendCmds(Bd, CmdStr$)
The format of the device address in ICS’s command set depends on the operating
system. In DOS, the device address format is pp or ss where pp is a primary address
and ss is a secondary address. Valid address is:
0 to 30 for pp
In Windows, the device address also includes the card number. The format becomes
cardno pp or cardno pp ss. ICS adopted the Hewlett-Packard convention and numbered the
first card as 7. Subsequent cards are numbered 6 down to 4. Valid device addresses are:
700 to 730 for cardno pp
70000 to 73030 for cardno pp ss
To address a device at primary address 4,
Address = 7 & 04 = 704
To address a device with a primary address of 4 at secondary address 2,
Address = 7 & 04 & 02 = 70402
The NI 488.2 commands use two variables, Bd and Address to express the device address.
Bd contains the Card number and is 0 for the first card. Address is a 16 bit variable with
the secondary address in the upper byte and the primary address in the lower byte.
Address = [ss + 96]*256 + pp
To address a device at primary address 4,
Address = 0 + 4 = 4
To address a device with a primary address of 4 at secondary address 2,
Address = [ 02+96 ] *256 + 4 = [ 98 ] *256 + 4
= 25088 +4 = 25092

14.5.9 Program Closing

Where Addr is the device’s address, the NI 488.2 SendCmds command outputs the bytes
passed to it in CmdStr$ without the interpretation done by ICS’s ieSend command.
Some GPIB controller DLLs require that you issue a close command when exiting the
program to clean up the computer’s memory and/or to unlock the GPIB controller card
for use by another application. Follow the program rules for your GPIB controller card
to end your GPIB program.
652ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

14.6 GPIB INSTRUMENT CONTROL AND LABVIEW®


14.6.1 Overview of GPIB
For more than 40 years, the IEEE 488 bus, also known as the general-purpose interface
bus (GPIB), has provided a standard, high-speed interface for communication between
instruments and controllers from a multitude of vendors. GPIB is used across a wide
variety of industrial instrument control applications. For more information see section
‘History of GPIB’.
14.6.2 Assembling GPIB Instrument Control System
A basic GPIB instrument control system consists of four parts:
1. PC
2. GPIB controller
3. GPIB cable
4. GPIB instrument
Setting up the PC: PCI-based GPIB controller boards offer a simple, seamless bridge
between the PC and the GPIB instrument. Additionally, stand-alone GPIB controllers
communicate via serial, USB, or Ethernet/LXI. As a result, GPIB instruments can transmit
their data across the room or around the world. Additionally, the National Instruments’
Instrument Driver Network has more than 7000 instrument drivers to choose from, as
well as tutorials on how to use them to control your instrument.
Configuring the controller: Depending on the GPIB controller manufacturer, some kind
of instrument control software driver will need to be installed before the device can
function. National Instruments’ GPIB controllers come with their own GPIB driver and
Measurement & Automation Explorer (MAX). The MAX scans for connected instruments,
confirms communication, and creates the necessary handles for programming.
Connecting GPIB controller to instrument: Once the controller is installed and it works
properly, the GPIB cable can be connected from the controller to the instrument. In
accordance with the IEEE 488.2 standard, with a single controller, you can control up
to 15 different instruments connected in either a daisy-chain or star topology.

14.6.3. How to Create a VISA Resource for an Instrument in MAX


If you are using a GPIB controller from Agilent/HP (HPIB) and want to use LabVIEW
or another National Instruments’ program to control it, please refer to Can I Use Both
National Instruments (GPIB) and Agilent/HP (HPIB) Controllers in the Same System?
If you are using a National Instruments’ controller, the MAX utility comes with the
NI-488 driver for your controller. The MAX makes GPIB instrument detection and control
easy by providing you tools to search for connecting instruments, and send and receive
communication with your device.
Open MAX by going to Start>>Programs>>National Instruments>>Measurement &
Automation.
This document gives a brief history of the origins of GPIB and includes some general
information regarding National Instruments’ GPIB-related hardware and software.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ653

14.6.4 Origin of GPIB

The original GPIB was developed in the late 1960s by Hewlett-Packard (where it is called
the HP-IB) to connect and control programmable instruments that Hewlett-Packard
manufactured. With the introduction of digital controllers and programmable test
equipment, the need arose for a standard, high-speed interface for communication
between instruments and controllers from various vendors.

14.6.5 History of National Instruments GPIB Products

National Instruments was founded in 1976, and was dedicated to producing software
and hardware compatible with the IEEE Standard 488-1975. In 1977, NI released its first
GPIB interface for the DEC-PDP-11. Since then, NI has developed GPIB interfaces for a
wide variety of minicomputers, microcomputers, and workstations. NI also has developed
its own IEEE 488.2-compatible controller chipset that sets the standard for GPIB
performance. In addition to developing a variety of GPIB hardware solutions, NI has
extensive software solutions for a wide range of applications. Today, NI has established
itself as a leader in GPIB interfaces and instrument control software. see Fig. 14.8 shows
the timeline of NI GPIB interface development.
)
3.1

PIB

004
00
in

PIB

S
88. (W

S-H
t/1
dG

T5
CIG

488
ene
/s

E 4 8.2

TN

-U
pee

HS
2

P
yte

IEE -48

BIP
ard

IB-
.0/

.0/
)
S

03/
NT
Mb

-
I

GP
gh

bit
nd

&N

r.1

r.2
8

(A

-20
Fac I-48

IB/
Hi
Sta

/1

64
Ve

Ve
e/
ITE
882

1
488

882

GP
vic
N

8. 2
88.
to

8.2

8.2
T4

I-M
-De

Le-
T4

E4
rbo

-48

-48

-48
NA

IEE
PC

PC
TN
De

NI

NI

NI

NI
Tu

1984 1987 1990 1993 1996 1999 2000 2002 2003 2004 2008

Figure 14.8 National Instruments’ GPIB Innovations

14.6.6 Hardware and Software Options


There are many GPIB hardware options available from National Instruments. The options
as listed within the following categories:
s Plug-In GPIB Controllers
s External GPIB Controllers
s GPIB Support Products
s ASICs
654ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

NI GPIB hardware also gives you the advantage of utilizing the accompanying
NI-488.2 software. This software has been a de facto industry standard application
programming interface (API) for GPIB instrument control for more than 30 years and
has consistently increased in performance and efficiency while remaining unchanged in
user experience. NI-488.2 is available for multiple operating systems.
s Windows
s Real-Time
s Linux
s Macintosh
s Solaris
For more information on compatibility of the operating system, hardware, and software
version, please reference the following links:
s Developer Zone Tutorial: GPIB Driver Versions for Microsoft Windows and DOS
s Developer Zone Tutorial: GPIB Driver Versions for non-Microsoft Operating
Systems
For information on all NI GPIB products, please refer to the official National
Instruments GPIB Home page.

14.7 PROJECT: TO CREATE AN RT MEASUREMENT SETUP


14.7.1 Part 1: The R-T Measurement -- Program Coding

Figure 14.9
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ655

Figure 14.10

The LabVIEW RT Measurement Program: Some Explanation

Figure 14.11 First sequence


656ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The first program ‘Create or replace’ will open up a dialog box which will ask for a
data file name and it will check whether it is already existing or create a fresh one. If
you give the same file name as of an existing one, it will simply go into replace mode.
Build XY graph will open up an XY screen, where X & Y are arrays.

Figure 14.12

The first part of the second sequence will open up the temperature controller (Make
Lakeshore model) in the GPIB port (click on VISA resource name to select the GPIB
port) and send a string *IDN? to read the device identification. The return string can
be up to 10000-byte count which is usually not necessary but is a default value.

Figure 14.13

The same is tried for the source meter which is Keithlay XXX as shown above for
device identification.

Figure 14.14
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ657

The same is tried out for a nanovoltmeter Make KEITHLEY XXX device identification.

Figure 14.15

The above program will send two commands via VISA write. The first one is CLEar
and the other is CURRent:RANGe:AUTO ON.
The meaning of CLEar: Open the manual of the source meter
The meaning of CURRent:RANGe:AUTO ON. Open the manual of source meter and
the commands can be traced there. The above program will write a particular current
to current source meter Source Meter- Keithlay.

Figure 14.16
Figure Source meter ON.
Read nanovoltmeter

Figure 14.17
658ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Current reverse (below)

Figure 14.18

Read temperature (below).

Figure 14.19
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ659

Resistance calculation.

Figure 14.20

14.7.2 Part 2: How to run this program


Copy the .vi file on desktop. Double click on the file. LabVIEW will open the file its
own, and you can run the program by a click on the right arrow.

14.8 GPIB AND RS-232 INTERFACING USING LABVIEW


14.8.1 LabVIEW
An acronym for Laboratory Virtual Instrument Engineering Workbench, it is a graphical
programming language named as a ‘G language’. It is a design platform for data
acquisition, instrument interfacing, and automation.

Figure 14.21 Snapshot of the front panel


660ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

LabVIEW Is highly intuitive because it uses wires to connect functions and program
elements, and the data flow through the wires can be tracked at any time which makes
debugging very easy. However, LabVIEW can be tricky when writing conventional
programs like calculation of the sum of Fibonacci numbers to the nth term. LabVIEW
incorporates VISA, which is a software architecture which is used for instrumentation,
troubleshooting, interfacing and device communication of instrumentation systems
which include GPIB, Ethernet, RS232, RS485 and many others. VISA acts as a programming
interface between LabVIEW and the hardware. It is possible to read and write certain
commands from a computer and make the device take respective actions according to
their hardwired firmware with devices that have remote capability. These commands
are hardwired into the device in the device firmware.
Front panel: LabVIEW has a front panel where the GUI of the program can be developed
as easily as a click of the mouse. There are various buttons, controls, arrays, clusters,
sliders, graphs, etc., to choose from. Controls are elements in the GUI that take in input
from the user. For example, a slider could be a control. When the user sets the slider to
a certain value say ‘A’, the slider then returns the value ‘A’ . There are a lot of data types
to choose from. There are various types of controls such as Numeric, Floating point,
double integer, string, Boolean, etc. There are also decorative options in the front panel
to make the program aesthetically more pleasing.
Block diagram: The block diagram is the component where the actual programming takes
place by connecting the programming elements with wires and determining the flow
of information and data through various functions and operations, and, finally, returning
the resultant data into some sort of indicators. Indicators serve the purpose of displaying
the data at a particular point within the program. The block diagram is actually the
representation of the program itself. An indicator can be created anywhere in the program,
and data is wired into it from any existing point on the wire in the program.

Figure 14.22
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ661

Connector panel: The programs developed in LabVIEW are usually called VI(s) or virtual
instruments. Each VI could be an individual program or a subprogram used in another
larger program. When used as a subprogram or a Sub VI, for the subprogram to run it
needs to take input data. It could be either done by using global variables or the controls
within the sub VI need to take input from the larger VI through terminals that are
created by using the connector panel. By selecting a control from the front panel within
the sub VI and clicking on one of the blank terminals on the connector panel, we create
a terminal in the sub VI. Also, the resultant data that needs to be returned to the parent
program needs to exit the sub VI through a terminal which is also created in the same
manner by clicking an indicator and subsequently clicking the blank terminal on the
blank output terminals on the connector panel.

Figure 14.23 Connector panel in the marked square

Powerful programs of industrial standards can be written in LabVIEW to automate


multiple instruments and the graphical architecture makes it achievable and advantageous.
A powerful interface can be created. NI provides driver support for numerous devices
and interfaces.

14.8.2 Functions and VIs

Functions are elementary nodes in the G programming language. They are analogous
to operators or library functions in conventional languages. Functions are not VIs and,
therefore, do not have front panels or block diagrams. When compiled, functions generate
inline machine code. You can select functions from the Functions palette in the block
diagram.
When the block diagram window is active, select Windows»
662ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Show Functions palette: You also can access the Functions palette by popping up in
the area in the block diagram window where you want to place the function.
The following illustration shows the functions and VIs available from the Functions
palette.

Figure 14.24

Function and VI overviews: The following functions and VIs are available from the
Functions palette.

Structures

G Structures include While Loop, For Loop, Case, and Sequence Sturctures.
This palette also contains the global and local variable nodes, and the formula
nodes.

Numeric Functions

Numeric functions perform arithmetic operations, conversions, trignometric,


logarithmic, and complex methematical functions. This palette also contains
additional numeric constants, such as S

Boolean Functions

Boolean functions perform Boolean and logical operations.


ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ663

String Functions

String functions manipulate strings and convert numbers to and from strings.
This palette also includes Additional Strings To Number functions and String
Conversion functions.

Array Functions

Array functions assemble, disassemble and process array.

Cluster Functions

Cluster functions assemble, access, and change elements in a cluster.

Comparison Functions

Comparision functions compare data (greater than, less than, and so on)
and operations that are based on a comparision, such as finding the minimum
and maximum ranges for a group or array of values.

Time and Dialog Functions

Time and Dialog functions manipulte time functions and display dialog boxes.
This palette also includes the VIs that perform error handling.

File I/O Functions

File I/O functions manipulate files and directories. This palette also contains
the subpalettes Advanced File Functions, Binary File VIs, and File Constants.

Application Control

The Application Control palette includes the Help functions, Menu functions,
Print VIs, and VI server VIs.

14.8.3 Interfacing Devices Using LabVIEW

One of the most exploited uses of LabVIEW is to interface electronic devices. A number
of scientific instruments can be interfaced using this development software. Some of the
typical devices that can be interfaced are as follows:
s Keithley 2612 A source meter
s Lakeshore335 temperature controller
s Agilent 34420A nanovoltmeter
s Oxford ITC 502 temperature controller
s Oxford ITC 503S temperature controller
The two modes of communicating with the devices used were RS232 and GPIB bus.
664ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Writing a GPIB communication program:


Simple GPIB communication

1. If this is the first command to be sent or the previous command was an error,
initialize the GPIB board [send interface clear and set remote enable, set the DMA
mode or programmed I/O mode to 0, assert remote enable (1)].
2. Clear the device you want to talk to (device clear). Wait for 100 ms.
3. Write the command to the instrument. This command follows the normal
command structure [append a carriage return (CR) to the string and send end of
instruction (EOI) with a carriage return (CR)]. Wait for 50 ms.
4. Read from the device [end of string (EOS) character is carriage return (CR), read
terminated on end of instruction (EOI), requested byte count, or carriage return
(CR)].

Advanced robust GPIB communication:

1. If this is the first command to be sent or the previous command was an error,
initialize the GPIB board (send interface clear and set remote enable, set the DMA
mode or programmed I/O mode to 0, assert remote enable).
2. Clear the device you want to talk to (device clear). Wait for 100 ms.
3. Read the Serial Poll byte.
4. Write the command to the instrument. This command follows the normal
command structure. Append a carriage return (CR) to the string and send end
of instruction (EOI) with a carriage return (CR).
5. Repeat reading of the Serial poll byte until bit 4 [message available (MAV)] of
the byte is high, i.e., 1 (make sure this times out after n seconds).
6. Read from the device [end of string (EOS) character is carriage return (CR), read
terminated on end of instruction (EOI), requested byte count, or carriage return
(CR)]
7. For completeness, repeatedly read the Serial Poll byte until bit 4 of the byte is
low (0).
8. Take the reply from the instrument and check that all the individual characters
are not corrupted.
9. If at any point an error has occurred, display a dialog informing you that there
is a problem for say 5 s. Then reinitialize the GPIB card, clear the device, and
issue the command from the beginning of this sequence once more.
10. If the reply is OK, for the next command, there is no need to reinitialize the GPIB
card or clear the device. Start from step 3 by reading the Serial Poll byte.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ665

RS232/serial port /com port initialization for software:

Baud Rate 9600


Stop Bits 2
Data bits 8
Parity None
Flow Control None

Writing an RS232/ISOBUS communication program:

Simple RS232 communication

1. Initialize the port as per the setup parameters.


2. Write the command you want to send [terminated with a carriage return (ASCII
13)] to the com port, e.g., ‘C3’.
3. Read characters received at the com port until you receive a carriage return (which
marks the end of the reply). Put all the characters you received together to get
the complete reply.
4. Interpret the reply.

Advanced, robust RS232/ISOBUS communication:

1. Initialize the port as per the setup parameters. This must be done once initially,
or if there is an error reading or writing or there is a timeout from the previous
command.
2. Read any parameters present on the com port. If there are characters present,
wait for 5 ms, then read any characters present again until there are no characters
present. This ensures that there are no characters present on the com port which
could be misinterpreted.
3. Write the command you want to send [terminated with a carriage return (ASCII
13)] to the com port, e.g., ‘C3’.
4. Read characters from the com port – store them in a variable. Does the reply
contain a carriage return (ASCII 13)? If it does, you have the complete reply from
the instrument. If not, read from the com port again until you receive a reply
which contains a carriage return. Check when waiting for the reply if the response
from the instrument takes longer than a given time, e.g. 5 s. If the instrument
does not respond within say 5 s, then there is a problem.
5. For complete robustness, once you have a complete reply check that each character
in the reply is a true character and not corrupted.
6. If the reply is OK, interpret the response as necessary for your program.
666ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

7. This is only a suggestion. If there is a problem (command timed out, or you did
not receive a reply, or the reply was corrupt, or you were not able to write or
read to/from the com port), display a dialog on the screen informing you that
you have an error and a message telling you what the error was. Display this
dialog for say 5 s, then reinitialize the com port and reissue the command to try
again.
8. If the reply was OK and everything worked with no errors, start the next command
at step 2, i.e., do not initialize the com port (it is not necessary).

14.8.4 Connecting Instruments via GPIB


Configuring in Windows:

1. Open MAX by going to Start»Programs»NationalInstruments»Measurement&


Automation. To confirm that your GPIB device is connected properly, expand
the Devices and Interfaces subdirectory below My System.

Figure 14.25 NI MAX

2. Then select your GPIB controller and click on Scan for Instruments (Fig. 14.26).
This tutorial uses a USB-GPIB-HS controller.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ667

Figure 14.26 Scanning for Instruments in MAX

3. If your GPIB device is SCPI-compliant, the name and address appear in the lower
main window once the instrument name in the configuration tree has been clicked.

Figure 14.27 Attributes Tab for an Instrument

4. MAX creates the necessary resources for VISA communication with your GPIB
instrument. By selecting the instrument from the subdirectory on the left and
then selecting the VISA Properties tab, you can change the VISA Resource Name
of the device and communicate with it by clicking on Communicate with
Instrument (SCPI commands) or Open VISA Test Panel (non-SCPI commands).
668ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 14.28 VISA Properties Tab for an Instrument

Using the VISA Interactive Control to Confirm Communication and More: The VISA
Interactive Control (VISAIC) is a standard software utility included with NI GPIB
controller products. Using your computer, you can take advantage of this powerful
development and debugging tool to interactively communicate (read, write, serial poll,
and so on) with your GPIB instruments. With the VISAIC utility, you can speed up
application development by learning how to automate measurements with your
instruments, uncover GPIB problems, and avoid headaches by identifying malfunctioning
instruments. For Windows platforms, the VISAIC utility comes with online help that
describes the applicable NI-488 functions and NI-488.2 routines, syntax, error codes, and
status variables that offer the debugging information you need to solve problems.
To access the VISAIC in MAX go to Tools»NI-VISA»VISA Interactive Control. You can
also expand the Software tab within MAX, expand the NI-VISA subdirectory, right-click
NIvisaic.exe, and left-click the Launch button.

Figure 14.29 NI-VISA»VISA Interactive Control.


ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ669

Quickly Determining GPIB Addresses: When VISAIC initially runs, it automatically


finds all of the available resources in the system and lists the instrument descriptors for
each resource under the appropriate resource type. Figure 14.31 shows the VISAIC
opening window.

Figure 14.30 VGA Interactive Control window

Establishing communication with your instruments: Once you have determined the
GPIB address of your instruments, it is easy to establish communications to verify that
you can send and receive data to and from the instrument. Because most instruments
are compliant with 488.2, you can query the instrument for its identification by sending
it the *IDN? Command. Instruments typically respond with the manufacturer’s name,
model name, and various alphanumeric characters that the manufacturer uses to track
firmware revisions.
To communicate with your instrument at Address 4, follow these instructions:
s First, double-click the instrument in the VISAIC that you want to communicate
with. In this case, GPIB0::4::INSTR.This opens a VISA Test Panel for your instrument.
s With this Test Panel, you can set properties for your instrument communication
as well as read and write to the instrument.

Figure 14.31 VISA Test Panel


670ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

s From the Basic I/O tab, select the *IDN?\n command, which is the 488.2 instrument
identification command *IDN? followed by the termination character \n.
s Next, press the Write button to send this command to the instrument.
s Finally, press the Read button to read back the response from the instrument. Your
instrument should return an identification string that appears in the window. You
also can perform both a write and a read automatically by pressing the Query
button.
s Now from the viRead tab, select a count of 100, the length of our expected response,
then click Execute. Our instrument should return an identification string.
s You have just confirmed communication with your instrument. Repeat this process
to confirm communication with all of your connected instruments.

Figure 14.32 VISAIC viREAD

An easy way to troubleshoot instrument, cable, and power problems: Many times,
systems are powered down, and cables are disconnected from instruments for maintenance
or system configuration changes. Alternatively, system power may be disrupted for a
variety of reasons, or the actual instrument may begin to malfunction. VISAIC is also
convenient for verifying that your instruments are still ‘alive’ on the bus.
s Simply use Refresh (View Refresh) to check if a particular instrument is listening
at its assigned GPIB address.
s If it is not, then you know to check cables, confirm power, and verify that the
instrument is working properly.
s If there is a problem, you no longer see your device. This indicates that you should
check for loose or disconnected cables, power disruption, or a malfunctioning
instrument.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ671

The basic functions and concepts described above may seem simple; however, they
can be invaluable in troubleshooting and getting your GPIB system up and running.
These productivity tools help you focus on developing your test applications instead of
trying to track down obscure problems or establishing communications with your
instruments.
Once you have completed these steps, you need a fast way to progress from interactive
mode to programming mode so you can immediately begin writing your tests without
a tedious transition process. The best way to achieve this is by using instrument drivers.

14.8.5 Creating a Sub VI to Write and Read commands using VISA


Write and VISA Read Functions

Figure 14.33

Figure 14.34

The VISA functions are daisy chained together.


s Make sure that your messages consist of commands that the instrument understands.
s Check your device’s user manual for a list of possible commands.
672ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

s Check the user manual to see if your instrument needs to be in a GPIB or 488.2
modes in order to be a GPIB Listener. Often instruments will only respond to the
standard commands after they have been placed in this mode, and otherwise, they
will give an error despite being sent a valid command.
s Verify that you are using the correct termination method for your instrument. Byte
count (where you expect to receive a certain number of bytes in a message) is
always used, but some instruments use EOS and byte count, some use EOI and
byte count, and some use only byte count.
s Check your device’s user manual for the possible termination methods to use with
your instrument.
LabVIEW also has GPIB functions in the instrument I/O functions in the Functions
Palette. Both perform the same task; however, using VISA functions has a few advantages.
Almost all of the GPIB functions have an equivalent VISA function. For what you do
99% of the time, there is no difference. For example, the VISA Write is equivalent to a
GPIB Write except that the VISA Write returns a VISA Reference Out that is much easier
to use. You pass that to the next VISA function instead of wiring a GPIB address to all.
It makes way for a cleaner wiring.
This VI performs simple GPIB communication with an instrument using the NI-VISA
API, which is recommended for most new designs. The VI sends the user specified
command and returns a number of bytes equal or less than the byte count specified.
VISA gives you portability. VISA supports GPIB, Serial, Ethernet, USB, PXI, VXI, and
PCI. So, with a single piece of code, you can support all of the interfaces and even GPIB
controllers from different vendors. This has been enormously helpful in many situations.
For example:
s A GPIB instrument in a production test rack goes bad. The spare is out for
calibration. The line is down, and you’ve got to get it back up RIGHT NOW.
There’s an identical instrument in the lab, but it has a USB interface. Because the
test program used VISA, the station was backed up in a manner of minutes.
s I inherited a batch of GPIB controllers from another division. They purchased
them from Agilent. I needed new test stations and instead of buying new controllers,
used the Agilent ones. No changes were required in the existing test programs.
s As a cost savings measure, I decided to switch to USB and Ethernet interfaces on
the test equipment. No changes were required to any of the existing test programs.
s A test program is using a PC’s dedicated serial port. It went bad. I connected a
USB RS-232 adapter, changed the VISA alias for the com ports and was backing
up and running within minutes.

14.8.6 Termination Characters and Byte Count

The best default termination character is none. GPIB (IEEE 488.1) defines a special
hardware line, EOI, which is asserted with the last byte to signify the end of a transfer.
You should rely on this method to terminate a GPIB transfer, as opposed to a termination
byte that is stuffed into the byte stream. Some older devices (primarily those that were
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ673

initially RS-232) use only an EOS character, and that can be CR, LF, or CR-LF, which is
why the option exists to terminate a read transfer on EOS with NI-488.2.
Most devices (such as those following the IEEE 488.2 protocol) use both (they send an
LF at the end with EOI asserted). Even in that case, however, you should only really be
concerned with the EOI since that is the native termination of the GPIB.
You can specify a count less than the actual number of bytes returned, but you would
not get a complete response. Even if the instrument returns a smaller byte count than
what you request, the VISA Read terminates as soon as the EOI is detected, so you are
never reading more bytes than what is required. See if there is an option with the
instrument to change the precision, or if you are reading data as ASCII see if there is a
method to send binary.
If the instrument appends a control character at the end of each response, then you
should wire a True to the Enable Termination Character and set the termination character
to that. You are appending a \r or hex D. If the instrument appends this, then you can
set the number of bytes to read to be some high number. The VISA Read will automatically
terminate when it detects the termination character. If the instrument does not append
something, then next to best is to use the function VISA Bytes at Serial Port. It’s right
below the VISA Configure Serial Port on the palette. This will return the number of
bytes in the serial port buffer. You can wire the output of this to the VISA Read. You
have some delays in your program, and this may work just fine if the delay is long
enough for the instrument to send everything before you check to see how many bytes
are available. However, it would be more efficient to use a loop to check to see when
byte count is greater than 0 and then another loop to keep reading until the number of
bytes is zero. This way you won’t have to tweak the delays.
Why do I receive timeout error -1073807339 on VISA Read or Write? When I perform
a VISA Write or VISA Read operation, I receive ‘Error -1073807339. Timeout expired
before operation completed’, shown in the following dialog:

Figure 14.35
674ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Why do I receive this error and how do I resolve it?


Solution: There are several reasons why you might receive this error message, the most
common of which are detailed below:
1. A timeout error is indicative of a different problem. Check the command strings
sent to the VISA Read and Write calls and ensure that they are written in the
proper syntax for your instrument.
Note: A newline or carriage return is often required at the end of a command. A
good way to test this in LabVIEW is to right-click the command string control
on the front panel and change the display to ‘\’ Codes Display mode. In this
mode, a carriage return is \r, a line feed is \n, and an end of the line is \r\n.
Verify that the command being sent to the serial device has the termination
character that the device requires.
2. The port’s communication settings may not be configured correctly. Verify that
the baud rate, data bits, parity, stop bits, and flow control are set correctly to
correspond with your hardware requirements.
3. This error may be induced by attempting to read more bits than are available at
the serial port.
4. The VISA Property Node for Bytes At Port should be implemented to ensure that
the data read by VISA is limited to exactly the amount of data available.

Figure 14.36

5. Additionally, you can verify that you are not trying to read too many bytes by
reading only 1 byte at a time. If you do not get the error when doing so, increase
the number of bytes you read until you get the timeout error again. This tells
you how many bytes that command sends back.
Note: If you still receive the error while reading only 1 byte, verify the command
to make sure it has been written correctly and that you have also terminated the
command string correctly (as brought up in Solution 1).
6. Older instrumentation may not respond rapidly to commands written to the port,
causing a large delay between VISA Write and VISA Read. Applications designed
to interface with this type of instrumentation should anticipate this delay, and
implement a Wait function between VISA Write and Read to effectively avoid a
potential timeout error.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ675

Figure 14.37

7. Timeouts can also occur when you read or write large amounts of data since
large data sets often take longer than the default timeout period of 2000 ms
to transfer across the serial port. You can manually designate the VISA Session
Timeout in different ways, depending on your development system. Please see
below for instruction on setting the VISA Timeout:
LabVIEW: You can use VISA Set Timeout located in the Functions palette
under Instrument I/O»VISA»VISA Advanced.

Figure 14.38

8. LabWindows™ /CVI: You can use the viSetAttribute function with its Attribute_
Nameparameter is set to VI_ATTR_TMO_VALUE.
Note: Changing the Timeout value for your VISA session will affect all VISA
Writes and Reads in your session. However, you can set this property/attribute
at any point during the session, allowing you to configure it as needed.
NOTE – For some devices, certain Write commands do not generate a read back from
the device and VISA Read function will generate a consequent timeout error. In such
cases, only VISA Write function is used. This information about the commands can be
found in the device’s manual.
676ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

14.8.7 Creating nodes on the Sub VI for the Read and Write Switches

Figure 14.39

In the front panel of the sub VI (Named as GPIB execcmd.vi), Select the Connect Wire
tool from the tools palette and click on the controls in the GUI and connect them the
terminals in the connector panel as shown in the following figure.

Figure 14.40

Now the Sub VI can be used in other VI(s) and the terminals have been created which
take inputs into the controls of the sub VI by wiring data into them from the main VI(s).
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ677

Figure 14.41

Creating terminals for the Read and Write Switch enables us to toggle on and off the
read and write sections by creating Boolean constants in the block diagram in the context
of the program being a writer of the sub VI depending on our requirement (e.g., for
some Write commands there is no read commands sent back by the device. Also, while
reading, VISA Write must not be executed).

14.8.8 Basic Framework of the Agilent 34420A Nanovoltmeter VI

Figure 14.42

The string array is holding the commands to be written into the device.
The following steps are to be followed:
1. Build an array of N elements (N being the number of commands to be written
into the device). Creates an n-dimensional array in which every element is
initialized to the value of the element. Put an array size block which returns the
no of elements in each dimension of the array. Put an indicator for the array.
678ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Array of 15 elements Array size Index array (fill all elements to 0)


Figure 14.43

Figure 14.44 The array with valid command in element 1

2. Insert a While loop, which repeats the subdiagram inside it until the conditional
terminal, an input terminal, receives a particular Boolean value. The Boolean
value depends on the continuation behavior of the While loop. Add a shift register
to the while loop.
Shift registers pass values from previous iterations through a loop to the next
iteration. A shift register appears as a pair of terminals, shown below, directly
opposite each other on the vertical sides of the loop border. The terminal on the
right side of the loop contains an up arrow and stores data on the completion of
an iteration. LabVIEW transfers the data stored in the right terminal of the shift
register to the left terminal. The loop then uses the data from the left terminal as
the initial values for the next iteration. This process continues until all iterations
of the loop execute. After the loop executes, the terminal on the right side of the
loop returns the last value stored in the shift register.
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ679

while loop

stop button on front panel (stops the execution


of the whole program)
Figure 14.45

3. Create a local variable of array for parallel processing of data in other terminal.
4. Insert a case structure. It has one or more subdiagrams, or cases, exactly one of
which executes when the structure executes. The value wired to the selector
terminal determines which case to execute. Here we have a reset button which
is set to false.

Reset button on the front panel case structure having a reset button on
block diagram panel
Figure 14.46

With this Reset button, we can stop and restart the execution of the program.
680ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

5. A For loop is created counting from 0 to N where N is defined by array size.This


for loop consists of a comparator (greater?) which compares the value of array
element with a constant 3 and generates an error if value is greater than 3; so the
error LED will glow.

Figure 14.47

It checks each element of the array to read data and at the place in the array
where data is present a zero is written, and all other are made one.
6. Now create a for loop containing stacked sequence structure from 0 to 3 which
executes sequentially for each data element it gets from the local variable array.
Add a shift register to the For loop.
Put an indicator Numeric for the value of i.

Figure 14.48
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ681

7. In Stacked sequence 0 array is connected to an index array which, in turn, is


connected to a comparator comparing the values of each element of the array
with a constant 5 and output goes into the case structure. Index array returns the
element or subarray of n-dimension array at the index. Here the index is i of the For
loop.
If the output of the comparator is FALSE it will analyze the whole array to get
the desired value. It will read each element and accordingly Boolean is set to true
or false. If it is TRUE it will simply pass to a Boolean indicator, means after the
desired number of the count which is 5 here it will not check all data it only
reads the data where it gets a zero and executes commands from the array.

Figure 14.49

Here the Read terminal of the sub VI ‘GPIB execcmd.vi’ is wired as FALSE as
the Activate channel 1 command is a Write command which does not generate
any read back from the device (there is a different command to check the Active
channel status for Agilent 34420A nanovoltmeter).
8. In Stacked sequence 2 a Boolean value of FALSE is deliberated and connected to
a case structure. If the condition is TRUE, it will simply pass the array element
by adding 1 to it using an incrementer. It uses an index array to get the element
of an array. If the condition is FALSE, it will Execute the code in the False case
of the Case Structure.
682ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 14.50
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ683

9. In stacked sequence 3 and Boolean (local variable) is set to False.

Figure 14.51

10. The output of the stacked sequence is connected to the shift register of the For
loop which is further connected to the shift register of the While loop.
After the execution of this one complete cycle the While loop is incremented by
1. Then it again checks each array element and increments it by 1 keeping 0 at
the place of the correct data element.
This completes the block diagram to execute the given program.
Result: This program is successfully executed to read the data from an input device and
Execute the commands from the string array and take data from the device and display
it. An array of N elements is initialized to 0. For 0 count of the While loop each element
in the array is compared to a value 3 in the case structure one by one. This 3 determines
the no of times it checks the devices to get data after that it generates an error. At the
array element where data is present, a zero is written rest all are 1 which gets incremented
with the loop count.
The array elements are passed to the For loop and with the count of i each element
passes through all the four stacked sequences. In the first stacked sequence it reads the
data. If it gets the data then there is no error; so it executes the command in stacked
684ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

sequence 2 and then again a time delay is introduced, and the error is set to the False
mode in stacked sequence 3. If it does not get any data an error is generated which is
passed to the stacked sequence 2 and so instead of executing the command it simply
passes it incrementing it by 1. As soon as all the N elements are checked and the For
loop is executed once it comes out and the While loop is incremented by 1 and the
whole procedure is repeated.

14.8.9 Interfacing Keithley 2612A Source Meter Using LabVIEW

s The Keithley 2612A source meter interfacing and programming was started.
s Understood more in-depth concepts of programming in LabVIEW.
s Made the program in the block diagram

Figure 14.52 Snapshot of a part of the program (depicting the GUI).

Figure 14.53 Snapshot of a part of the program (depicting the code for
communicating with the source meter and reversing the current).
ޗޛЕȱ ž›™˜œŽȱ —Ž›ŠŒŽȱ žœȱ ǻ  Ǽȳ685

Basic framework of the Keithley 2612A source meter VI: The framework remains the
same; however we did not use the local variable of the string array to wire in commands
into the sub VI. Instead we used commands directly by daisy chaining the VISA Write
and VISA Read functions in the case structures as per the requirement owing to the
large number of commands used.

Figure 14.54
14.8.10 List of Commands Used
Table 14.4 Keithley source meter interfacing commands
S.NO. COMMAND FUNCTION
1. smua.source.rangei = 100e-3 10 mA measure range
2. smua.source.leveli = 0.1 100 mA measure range
3. smua.source.limitv= 20 20 A compliance.
4. smua.sense=smua.SENSE_REMOTE Turn on Remote mode
smua.measure.autorangev=smua. Turn on Auto Range on channel A
5.
AUTORANGE_ON voltage
6. smua.source.output = smua.OUTPUT_ON Turn on Output on Channel A
7. smub.source.func = smub.OUTPUT_DCAMPS Set the source function to current
8. smub.source.rangei = 100e-3 10 mA measure range
9. smub.source.leveli = %g Set current source level.
10. smub.source.limitv= 20 Set compliance value of i=20 mA
11. smub.sense=smub.SENSE_REMOTE Turn into Remote mode
smub.measure.autorangev=smub. Turn on Autorange on Channel B
12.
AUTORANGE_ON voltage
13. smub.source.output = smub.OUTPUT_ON Turn on Channel B voltage
14. smua.source.func = smua.OUTPUT_DCAMPS Set the source function to current
686ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Table 14.5 Agilent 34420A nanovoltmeter


S.NO. COMMAND FUNCTION
1. ROUTe:TERMinals\sFRONt1 Selects input channel 1 for voltage measurement
2. ROUTe:TERMinals\sFRONt2 Selects input channel 2 for voltage measurement
3. ROUTe:TERMinals? Checks the active channel
4. READ? For measuring the voltage
5. PID For Setting PID values
6.
7.

Table 14.6 LAKE SHORE 335 temperature controller


S.NO. COMMAND FUNCTION
MODE (value) To change mode.
1.
MODE? - For mode query 0= local, 1= remote, 2= remote with lockout
2. SETP\s2.(value) Set Point for B
3. SETP? Set Point Query
4. TEMP? Thermocouple Junction temp query
5. RAMP\s1,\s(value) RAMP Set point
6. RAMP? (output) RAMP Query

REVIEW QUESTIONS

1. Briefly explain GPIB bus technology?


2. How do you perform following tasks using visa libraries.
ȱ ȱ ǻŠǼȲŽȱŠȱGPIB device in local mode
ȱ ȱ ǻ‹ǼȲŽȱŠȱGPIB device in remote mode
ȱ ȱ ǻŒǼȲŠȱGPIB bus interface clear.

ANSWERS

1. GPIB stands for general purpose interface bus, used to communicate with
instruments from a PC.
2. (a) One can program the devices using its GPIB address & message strings.
(b) One can program the devices using its GPIB address & message strings.
(c) One can program the devices using its GPIB address & message strings.
8-BIT ATMEL MICROCONTROLLER-BASED
WEB SERVER AND Qt INTERFACING:
15 A WEB I/O SERVER

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ To Design a Graphical User Interface (GUI) for an embedded system using Qt.
Ȋȱ GUI design using Qt for a web i/o server having DI,DO,AI,AO
Ȋȱ Digital Input: GUI can check whether the device is ON or OFF
Ȋȱ Digital Output: GUI can switch ON or OFF a device
Ȋȱ Analog Input: GUI can read the current values of the devices connected
Ȋȱ Analog Output: GUI can change the voltage value of the devices

15.1 DI/DO/AI/AO

The objective of this chapter is to design a Graphical User Interface (GUI) for an embedded
system using Qt.
Four types of devices can be connected to the system and, hence, following modules
need to be added to the GUI:
1. Digital Input: GUI can check whether the device is ON or OFF
2. Digital Output: GUI can switch ON or OFF a device
3. Analog Input: GUI can read the current values of the devices connected
4. Analog Output: GUI can change the voltage value of the devices

15.2 HARDWARE DESCRIPTION

We have used Atmega 168 which is interfaced with Ethernet controller Microchip ENCJ60
to build this web server circuit [see Fig. 15.1] which can be populated for (refer www.
tuxgraphics.org)
Ȋȱ 8-channel Analog Input
Ȋȱ 16-channel Digital Input
Ȋȱ 16-channel Digital Output
Ethernet remote device controller/sensor, version 2007/1
RAWDC U4
3V3 CONN2 Vdd
Vcc 1 IN OUT 3
1

Vcc
Vcc 3V3
3V3 GND C1
2 C9 C2
2 LM2937_33
100nF 100nF or 47nF
ATMEGA88/168 U1 C10 C11 RawDC-IN (5-12V) 10uF

10K
100nF 100nF
R1 1 Rst(PC6) 28
(SCL)PC5
J1
2 PD0 (RXD) 27 3V3 ENC28J60 U2
IO-port (SDA)PC4 Vcc CONN4
1 R17 Analog-IN

C5
3 PD1 (TXD) (ADC3) PC3 26 1K 1 1 Vcap Vdd 28
2

Vcc
3V3
2 A=Green
3 4 PD2 (INT0) R13 27 R4
(ADC2) PC2 25 1K 2 Vss LEDA
3 270

10uF
4 R12 R3 B=Yellow
5 PD3 (INT1) (ADC1) PC1 24 1K 3 CLKout LEDB 26
4
5 270
6 PD4 (T0) R11 5
6 (ADC0) PC0 23 1K 4 INT Vddosc 25

Vcc
3V3
C4

3V3 6
7

TP1
7 Vcc AGND 22 5 WOL OSC2 24

Vcc
18pF
25MHz

C8
688ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

8
U3

8 GND AREF 21 6 SO OSC1 23


C3

9 100nF
9 PB6(XTAL1) AVcc 20 7 SI Vssosc 22 18pF

Vcc
Vcc
10 PB7(XTAL2) (SCK) PB5 19 8 SCK Vsspll 21 3V3 T1
Vdd
RAWDC
CONN3 11 PD5 (T1) R2
(MISO) PB4 18 270 9 CS Vddpll 20 7 Yellow
3V3
1
D1 12 PD6 (AIN0) (MOSI) PB3 17 R15 10 Reset Vddrx 19
L1

MagJack
Vcc Vcc

2 3V3 8

BAY69
13 PD7 (AIN1) (OC1B) PB2 16 11 Vssrx Vsstx 18 10nF-100nF 2

10K
external
1 50

TP2
R8

relay 14 PB0(ICP1) (OC1A) PB1 15 12 TPIN- TPOUT+ 17 C7


2 1
Q1 R14 13 TPIN+
CONN1 TPOUT- 16
BC547 ATMEGA88 or ATMEGA168
R9

1K 50

R10
3 firmware_IN
or BC548 14 RBIAS Vddtx 15 3

10K
R5
Vcc

GND

3V3
D2 5 3V3
SCK

Vcc
4 2K7 4
R16 270 MISO Vcc
3 50
R6

3V3 P8
C6

MOSI
2 6
Reset 10nF-100nF RJ45
1
R7

50
(C) Guido Socher, tuxgraphics.org 5
http://tuxgraphics.org/electronics/ 9 Green

10

11

Figure 15.1 ATMEGA168, ENCJ60 RJ45 hardware interface to work as embedded web server
ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ689

Figure 15.2 Web analog input front-end (analog for 0-10V dc) accessed through a server
as temperature at browser

Figure 15.3 Web digital o/p accessed through server at browser


[Refer: tuxgraphics.org/electronics/201008/10-web-server.shtml for details/firmware etc.]
690ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 15.4 The web i/o server http client from browser
[Refer: tuxgraphics.org/electronics/200904/embeded_webserver_equipment-control.shtml for details/
firmware etc.]

15.3 SOFTWARE: Qt
15.3.1 What is Qt?

Qt is a cross-platform application and UI framework that is widely used for developing


application software with a graphical user interface (GUI) and also for developing
non-GUI programs such as command-line tools and consoles for servers. It includes a
cross-platform class library, integrated development tools and a cross-platform IDE.
Using Qt, you can write web-enabled applications once and deploy them across many
desktop and embedded operating systems without rewriting the source code. Distributed
under the terms of the GNU Lesser General Public License (among others), Qt is free
and open source software.
Developer : Nokia
Qt community Initial release : 1992
Stable release : 4.7.3 / May 4, 2011
Development status : Active
Written in : C++
ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ691

Figure 15.5

15.3.2 Platforms

Use Qt Creator IDE to write apps for these platforms:


Ȋȱ Embedded Linux
Ȋȱ Mac OS X
Ȋȱ Windows
Ȋȱ Linux/X11
Ȋȱ Windows CE/Mobile
Ȋȱ Symbian
Ȋȱ MeeGo

15.3.3 What You Can do With Qt?

Write code once to target multiple platforms: Qt allows you to write advanced
applications and UIs once, and deploy them across desktop and embedded operating
systems without rewriting the source code saving time and development cost.
Create amazing user experiences: Whether you prefer C++ or JavaScript, Qt provides
the building blocks — a broad set of customizable widgets, graphics canvas, style engine
692ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

and more that you need to build modern user interfaces. Incorporate 3D graphics,
multimedia audio or video, visual effects, and animations to set your application apart
from the competition.
Do more with less (and faster): With the new Qt Creator cross-platform IDE, or on its
own, Qt is fast to learn and easy to use. And Qt’s modular class library means that you
can spend more time on innovation, and less time on infrastructure coding, getting your
software to market faster.
Blend web and native code in a single application: Qt’s integration with the WebKit
web rendering engine means that you can quickly incorporate content and services from
the Web into your native application, and can use the web environment to deliver
services and functionality.

15.3.4 Who Uses Qt?

Qt is used by thousands of companies in a multitude of leading industries enabling


them to develop software and devices used by hundreds of millions of people every
day.
Digital photo frame: Samsung was able to develop a web-enabled digital photo frame
with the dynamic information with the Qt GUI and application framework.

Barco: The Barco digital projector’s Communicator touch panel was built using Qt
allowing for a strong GUI and one-source code multi-platform deployment.

Samsung SPF-105V: This Roku device provides seamless, direct streaming of video
content from Netflix to consumers' TVs via a Qt-based interface.
ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ693

ASUS EeePC: ASUS has released a comprehensive software developer’s kit (SDK) for
the ASUS’ mobile Internet device, the Eee PC™. The Eee PC™ Linux version uses KDE,
a famous desktop environment based on Qt.

DAZ 3D: DAZ 3D develops powerful 3D software and digital content creation
applications. Qt has helped DAZ 3D simplify cross-platform development and
dramatically shortened their product release cycles via a short developer learning
curve.
Qt is most notably used in Autodesk Maya, Google Earth, KDE, Adobe Photoshop
Elements, OPIE, Skype, VLC media player, VirtualBox, and Mathematica, and by the
European Space Agency, Siemens, Volvo, Walt Disney Animation Studios, Samsung,
Philips, and Panasonic.

15.3.5 Installing Qt

Download Qt from the website [pls. look for latest]


[see: http://linux.softpedia.com/get/Programming/Widgets/Qt-179.shtml]

15.4 HARDWARE: 8-BIT ATMEL-BASED EMBEDDED SERVERS

The hardware used is an expandable and distributed large I/O data acquisition system
based on low-cost microcontroller based web service server boards based on tuxgraphics
tcp/ip stack whose hardware boards use 8-bit RISC processor with Ethernet controller,
and the software platform uses AVR-GCC for firmware [See Fig. 15.1].
This system can measure all kinds of electrical and thermal parameters such as voltage,
current, thermocouple, RTD and so on. The measured data can be displayed on web
pages at different geographical locations and at the same time cab be transmitted through
RJ-45 Ethernet network (using TCP/IP) to remote web based data acquisition and control
(DAC) monitoring system by using HTTP protocol. A central embedded single board
can act as a central CPU to communicate between web servers automatically. The novelty
of this proposed system is a substitute of web PLC for industry application.
694ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Sample contents of the webpage [HTML] of digital devices (at client transmitted from
server):
refer: code: www.tuxgraphics.org
<h2>Digital Input Status Server 2:</h2> <meta http-equiv=”refresh”
content=”1”><pre>
PD0 output: off [<a href=?sw=pd0&a=1>change</a>]
PD1 output: off [<a href=?sw=pd1&a=1>change</a>]
PD2 output: off [<a href=?sw=pd2&a=1>change</a>]
PD3 output: off [<a href=?sw=pd3&a=1>change</a>]
PD4 output: off [<a href=?sw=pd4&a=1>change</a>]
PD5 output: off [<a href=?sw=pd5&a=1>change</a>]
PD6 output: off [<a href=?sw=pd6&a=1>change</a>]
PD7 output: on [<a href=?sw=pd7&a=0>change</a>]
<a href=”./”>[refresh page]</a>
</pre><hr>
<br><small>IUAC<br>
HTML contents of the webpage for analog devices (at client transmitted from server):
<a href=./?g=0>[ADC Graph ]</a> <meta http-equiv=”refresh”
content=”10”> <a href=./>[refresh]</a>
<h2>Helium Plant Monitoring Page</h2><pre>
Voltage on channel 0: 2.115
Level Indicator: 23.0%
Temperature : 0K
Voltage on channel 1: 1.583
Tempreature on channel 5 : 0K
Temperature on channel 6 : 0K
Temperature on channel 7: 0K
Temperature on channel 8: 0K
</pre><hr>

Remote access of embedded servers

Any embedded server can be remotely controlled/accessed through any high-level


language. The program will work as an http client. HTTP get function with suitable
argument can work as an HTTP client for control & data read backs. A Qt C++ based
http client functions are tabulated in the following flow diagrams using QNetwork
Requests for AI/DI/DO/AO.
ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ695

Figure 15.6 A server box with DI/DO/AI daughter board servers built using ATMEL ATMEGA 168

Figure 15.7 Top view of the system over servers [daughter boards]
696ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 15.8 Devices connected to the system over server boards

15.5 FLOWCHARTS OF Qt CLIENT GUI DESIGN FOR DI/DO/AI/AO SERVER


CONTROL/READBACK USING QNETWORK ACCESS MANAGER
[Http client design via Qt]
Digital input Qt GUI design flow
Step Explanation Qt Function Used
1 Read back from the device Qstring readback = reply o
connected using the IP Read all()
address provided by the user
2 Check if the devices If (readback.mid()=="on")
connected to the system are
on or off
3 If the device is ON then gradient set Colour At(0,
change the colour of the LED Qt..red)
to GREEN painter.setBrush(gradient)

Figure 15.9 The flowchart of digital input [DI] GUI (see also GUI in Fig. 15.14)
ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ697

Remote digital output toggle: Qt GUI design flow for remote ON/OFF
Step Explanation Qt Command Used
1 Read back from the device Qstring readback = reply o
connected using the IP Read_all()
address provided by the
user
2 Check if the devices If (readback.mid()=="on")
connected to the system
are on or off
3 If the device is ON then PushButton>set
change the colour of the StyleSheet(background-color.
Push Button to GREEN green;")
4 If the device is OFF then PushButton>set
change the colour of the StyleSheet(background-color.
LED to RED red;")
5 If the button is clicked
then the corresponding
function is executed
6 Check the status of the if(readback_mid()=="on")
device using readback
7 If the device is already get(QNetworkRequest(Q
switched ON then switch Url("http://"+ip+/?sw=
it OFF pd1&a=1")))
8 If the device is already get(QNetworkRequest(Q
switched OFF then switch Url("http://"+ip+/?sw=
it ON pd1&a=1")))
Figure 15.10 The flowchart of digital o/p toggle GUI (see also GUI in Fig. 15.15)

Remote analog input readback Qt GUI


Step Explanation Qt Command Used
1 Read back from the device Qstring readback = reply o
connected using the IP Read_all()
address provided by the user
2 Read the current values of lineEdit>set
the devices and display them Text(readback_mid());
in their respective textboxes. pushButton>setText
The units are displayed in (readback_mid())
the corresponding push
buttons.

Figure 15.11 The flowchart of analog input readback GUI (see also GUI in Fig. 15.16)
698ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step Explanation Qt Command Used


1 It the slider is moved then
the corresponding funciton is
executed
2 Display the corresponding pushButton-
voltage in the pushbutton >set Text(QString..
number(value*5.0/4095,
'g',3))
3 If set is clicked then the
corresponding function is
executed
4 Set the corresponding value function SetBinValue (int)
to the device written

Figure 15.12 The flowchart of analog output [AO] GUI (see also GUI in Fig. 15.17)

15.6 TYPICAL SOURCE CODE IN A TYPICAL Qt PROJECT


15.6.1 Files

GUI.pro: The file contains the code that tells the compiler, the names of all the files that
are present in the project. It integrates all the files.
main.cpp: The file contains the code for the main() function. This is where the compiler
starts execution of the program.
mainwindow.h: The file contains the prototypes of all the functions that are a part of
the mainwindow class.
mainwindow.cpp: The file contains the definitions of all the functions that were declared
in the header file mainwindow.h
qledindicator.h: The file contains the prototypes of all the functions that are a part of
the qledindicator class. The class is used to display LEDs that are being used in the
digital input module.
qledindicator.cpp: The file contains the definitions of all the functions that were declared
in the header file qledindicator.h
ui_mainwindow.h: The file contains the code for the widgets that are displayed on the
GUI.
ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ699

15.7 SNAPSHOTS OF OUTPUT

Figure 15.13 Sample GUI for embedded system (combined DI/DO/AI/AO)

Figure 15.14 Screen for digital input


700ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 15.15 Screen for digital output

Figure 15.16 Screen for analog input


ŞȬ‹’ȱȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ Ž‹ȱ Ž›ŸŽ›ȱ Š—ȱ ȱ —Ž›ŠŒ’—DZȱȱ Ž‹ȱ Ȧȱ Ž›ŸŽ›ȳ701

Figure 15.17 Screen for analog output

REFERENCES

Where and How Qt is used, http://qt.nokia.com


Introduction to Qt, http://en.wikipedia.org/wiki/Qt_(framework)
Qt Coding, doc.qt.nokia.com/latest/tutorials.html

REVIEW QUESTION

1. What is Qt?

ANSWER

1. Qt is a C++ toolkit which has versatile libraries for http clients, GUI which is OS/
platform-independent.
WIRESHARK FOR NETWORK ANALYSIS
16

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ What is Wireshark?
Ȋȱ How to use Wireshark with network analysis?
Ȋȱ How to analyze and troubleshoot network issues in an embedded network?
This chapter deals with the use of Wireshark in network analysis of an Ethernet-based
distributed automation-network built with large number of embedded HTTP servers.
Network implementation and troubleshooting are tedious processes when it comes to
building an automation network of distributed embedded device servers, each with its
own MAC & IP number. The entire network could be distributed across diverse locations
within a building or around the globe. Therefore, data loss could be disastrous as they
are mainly used for measurement and control in any automation network. There could
be multiple problems in one’s network which could be the problem related to the
infrastructure devices, or it may be a rogue switch dropping packets periodically, or it
may be the server’s firmware bugs, or it could be bad cabling which gives rise to loops,
etc. In this chapter, we will describe how we can build an error-free, reliable HTT-based
automation network with a health monitoring watchdog utility and built-in re-booter
idea for each node, how we can troubleshot some of the major causes of poor
network performance of embedded HTTP servers using Wireshark, including data
loss, intercepting devices, gratuitous IP conflicts, network congestion, etc. The system
was built within a private LAN of approximately fifty embedded HTTP device servers,
built out of ARM & ATMEL processors, for automation and control of a working cryogenic
control room set up at the Inter University Accelerator Centre, New Delhi.

16.1 INTRODUCTION

Worldwide, there is a heavy demand for building Ethernet-based distributed device


servers for sensor-based control and data acquisition systems to replace conventional
crate based control systems to crate-less architecture. The backbone of these systems is
a stable error-free network. Interconnection of embedded servers, each with its own IP
& MAC, are a crate-less model of new generation computer control systems where each
device node communicates or takes action without any human intervention. Network
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ703

analysis is very important in the embedded Ethernet domain as we are entering into a
new era of computing technology that many technology giants have already started
investing in -- Internet of Things (IoT). The purpose of this chapter is to use the world’s
most popular packet analyzer, WIRESHARK, as the main tool to study, analyze, and
build an error-free HTTP automation-network. This chapter also introduces how we
used HTTP protocols in a network that ran multiple distributed embedded HTTP servers
and client PC running control software from a cryogenic control room. Network
installation, and a test of Wireshark for filtered capturing and analyzing is also discussed.
Wireshark is a cross-platform toolkit that uses the GTK+ widget in current releases,
and Qt in the development version, to implement its user interface, and uses pcap to
capture packets. It runs on Linux, OSX, BSD, Solaris, some other Unix-like operating
systems, and Microsoft Windows. There is also a terminal-based (non-GUI) version
called T Shark. Wireshark, and the other programs distributed with it such as T Shark,
are free software, released under the terms of the GNU General Public License. Wireshark
is very similar to tcpdump but has a graphical front-end, and additionally some integrated
sorting and filtering options. Wireshark dissects those packets, thus allowing it to analyze
packets captured on a remote machine at the time that they’re captured. We used the
Version 4.3 under Windows 7 for all the tests.
In the late 1990s, Gerald Combs, a computer science graduate of the University of
Missouri, Kansas City, was working for a small Internet service provider. The commercial
protocol analysis products at the time were priced around $1500 and did not run on
the company’s primary platforms (Solaris and Linux). So Gerald began writing Ethereal
and released the first version around 1998. The Ethereal trademark is owned by Network
Integration Services.
Inter University Accelerator Centre, a premier accelerator based research center of
India houses a cryogenic facility for cooling superconducting cavities to liquid helium
temperatures. The entire cryogenic distribution process had to be automated to be
operated from a cryogenic control room. We have built and installed 32 nodes of different
types of instruments, called device servers, running 50 embedded HTTP servers along
beam lines for cryogenic control and data acquisition systems. Now, finally, we have
built a reliable HTTP protocol based control network which is running 24×7 for last
three years. The system was built within a private LAN of approximately fifty embedded
HTTP device servers built out of ARM & ATMEL processors for automation and control.

16.2 DESIGN OF AN EMBEDDED AUTOMATION NETWORK OF HTTP:


CASE STUDY OF A DESIGNED SYSTEM

Device servers are compact embedded devices, with the capabilities of a computer but
built out of 8/32 bit processors for dedicated services like sensing and actuating
applications. Each device has its own IP and MAC address and accepts commands
from a central control PC, called client. The client runs a control software developed in
LabVIEW. The device servers run lightweight HTTP servers, and the commands are
issued from the control PC. RPC over HTTP is the method used for data communication.
704ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

The network traffic is mainly due to the digital communication between PC and device
servers. The traffic is higher in case the loops are external, which means that the closed
loops (like PID) are controlled by the PC program for read-write operations across the
network between two servers via a PC, which acts as a bridge, whereas the traffic will
be low in case all the loops are internal or embedded inside each device.
The devices are grouped into five locations, viz. Buncher, LINAC, Rebuncher, New
Refrigerator, Gas Management system (GMS), etc., as shown in Fig. 16.1. Each group
has its own standalone network switch (Cisco Model 300-28) with a group of servers
attached to it as nodes. The Cisco 300 Series is a broad portfolio of fixed-configuration
managed Ethernet switches. Models are available with 10 to 52 ports of Gigabit Ethernet
connectivity, providing optimal flexibility to create exactly the right network foundation.
We used Cisco Model 300-28 in all locations except LINAC area where it is Cisco Model
300-52.
Each device has three IP nodes. All of them run an independent HTTP server on each
node. All the three nodes are hardwired and interconnected inside one device. Finally,
all the distributed switches are interconnected with one another at the control room
switch.
The following picture shows one such location, LINAC, installed with a 48-port switch,
where connections are as shown in Fig. 16.2.

Figure 16.1 The network architecture


’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ705

Figure 16.2 The wall-mounting of BUNCHER device servers connected


to a switch (replaced with LINAC switch)

16.3 HTTP DATA DROP CHECKER AND AN AUTOMATIC


DEVICE-HEALTH CHECKER

Though HTTP is originally invented by Tim Berners-Lee of CERN for transferring text-
based information between a client and server PC sitting far-off places, the automation
industry has found its potential for control and data acquisition. Consider a simple ON/
OFF application where the automation industry generally uses relays for hardware ON-
OFF operations. Computer control of relays makes it an Internet protocol (IP) relay.
This operation can be achieved by an HTTP GET command which looks similar to
http://IP_NO_OF_DEVICE/rpc/mybulb/write 1. Similarly, any data from a
hardware device can be read by similar commands like http://IP_NO_OF_DEVICE/
rpc/fanspeed/read etc. Therefore, a series of meaningful HTTP commands can be
a firmware coded inside an HTTP server to write and read a device server. This complete
set of commands makes it a full-fledged server-based control system which can even
work like an IoT, where devices can directly post to the IoT cloud and can work to talk
to one another without a central PC.
The LabVIEW-based HTTP data loss checker is a useful and essential software we
developed. In case the command response is ‘blank’ characters instead of real data,
HTTP uses TCP as a transport layer. Certain design features of HTTP interact badly
with TCP, causing problems. So there are ways one can check the reliability of data
communication over HTTP using any language which supports TCP/IP libraries to work
as HTTP client.
706ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Here is a LabVIEW-based data loss checker which works as ‘Alarms’ of control systems.
Alarms are generated whenever any blank data is returned as a response to an HTTP
request. Then the alarm window will display the IP number associated with that defected
HTTP command response along with the complete command. Here, we have given the
condition that if any blank data is returned in response to any HTTP command for n
consecutive times (usually n=3), then the corresponding IP number is trapped inside
the alarms window. The value of n can be set from 1 to any integer number. Once the
alarm is displayed, the user has to acknowledge (by pressing a reset button) or else it
will skip that command forever in order not to avoid further time-out delays in each
SCAN. This means that if the operator doesn’t acknowledge, then that particular IP will
be bypassed forever. Whenever the operator acknowledges by pressing reset (the
operator does it after solving this issue with the server manually or using remote
re-booters), then onwards the alarm window will be cleared for a fresh check from the
beginning.
The basic HTTP drop detector designed for LabVIEW is given below in Fig. 16.3. In
this, the data is read using the block HTTP GET. Whenever there is a data loss, it was
found that the data string returned becomes a blank string. This case also can occur
whenever there are some errors associated with HTTP GET or not. Therefore, the status
code is wired in such a way that only the TRUE or FALSE value of the status parameter
of the error cluster passes to the OR function. If an error occurs, OR blank data is
captured; then the Err flag is set. So the resultant Err flag is generated and stored before
the further command is tested. In the below case, a threshold of n=5 is set to bypass
that IP permanently and trap it into alarms if the Err flag occurs more than n times
consecutively.

Figure 16.3 The basic data drop checker using LabVIEW TCP/IP library
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ707

Figure 16.4 The flow diagram of the working HTTP drop checker with user Ack (RESET) feature

Figure 16.5 shows the output of an alarm window which traps the IPs which face
data drops for more than n iterations. The trapped data could be due to a purposeful
temporary shutdown for maintenance or similar reasons, in such case the operator can
press the RESET button to acknowledge to clear the alarm window.
708ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Figure 16.5 The data drop loss IP trap in alarm window with RESET button

Figure 16.6 below shows a health checker utility which could be run parallel to indicate
if any IP is down during a long experimental run. This is a LabVIEW version which
checks all IPs and this table immediately can report to the operator and display how
that server can be rebooted from the PC remotely. The re-booter card in every device
is a separate, very compact, stable server that is powered from a different power supplies
which has an IP controlled relay to ON/OFF the main board +5 V power feeding the
TCP/IP stack.

Figure 16.6 The health monitoring utility of individual servers


’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ709

The user interface of the re-booter usually runs directly from any browser in the
network by setting and resetting the PD4 bit of an ATMEL processor (as shown in Fig.
16.7), which runs a very stable server powered from a stable, dedicated power supply
for the re-booter.

Figure 16.7 The Re-booter window of individual servers and a ping from
the same PC to ensure it is rebooted properly

16.4 SWITCH CONFIGURATION AND CABLING

We ensured that high-quality CAT/6 STP Molex make Ethernet cables with RJ45
connectors on both ends-(Shielded), Part Code-(P/No. PCD-04005- OE-I) were used, to
ensure no issues from cables.
The main issues which we faced during the commissioning of the embedded network
were due to wrong switch configurations, interconnections and cabling, which gave rise
to data losses across the network thereby some of the servers even crashed once in a
while.
710ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Table 16.1 Default switches (factory set) that were assigned to each Cisco switch
S.NO. SWITCH LOCATION MAC ADDRESS
1. BUNCHER SWITCHD5:CC:6F
2. LINAC AREA SWITCHAA:23:AB
3. REBUNCHER SWITCHEA:06:00
4. NEW REFRIGRATOR SWITCHDA:5D:5A
5. GMS SWITCHDA:5D:5A
6. CONTROL ROOM SWITCHAA:IF:97

16.5 ISSUES AND SOLUTIONS

The following were the two major issues we faced during commissioning due to which
alarms were frequently generated, and the network was highly unstable. Wireshark
played an instrumental role to debug the issues and arrive at the final solution and solve
it.
1. Errors due to poor switch-interconnection-cabling: The server crashing issues
were noticed and we reinstalled the network which initially looked like Fig. 16.8.
We investigated that this was a poor way of doing the cabling as it was introducing
multiple loops between a client and servers, causing data loss. Finally, we modified
it to the star configuration from the central switch as shown in Fig. 16.9, which
improved the situation drastically.

Figure 16.8 Switch interconnections give rise to multiple data paths to be avoided
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ711

Figure 16.9 Switch interconnections: modified proper

Figure 16.10 IOGRAPH: servers, accessed once in 8 s

2. Switch IP conflicts and duplicate address: Further, the network was examined
using Wireshark in detail and was found that there were IP conflicts in the
network. The following were the tests performed at the protocol level for the
network analysis to arrive at the final solutions obtained. The packet sniffer test
setup looks as shown in Fig. 16.12.
712ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Figure 16.11 IOGRAPH: google server

Packet Sniffer

Packet Application (e.g., www


Application
Analyzer browser, ftp client)

Operating
System Transport (TCP/UDP)

Network (IP)
Packet
Capture Copy of all Ethernet
Link (Ethernet)
(pcap) frames sent/rece/ved

Physical

to/from Network
to/from Network

S.No Filters used for analysis meaning


1 ARP Lists all ARP
2 Ip.addr == 192.168.1.11 List all IP
Figure 16.12 Packet sniffer structure
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ713

16.6 HTTP PROTOCOL ANALYSIS USING WIRESHARK

Just after the initial cabling, when we started all the ARM mbed servers for data collection,
it was found that severe data loss was occurring which is a very critical issue. This was
detected at the application layer in the HTTP drop tester.
Therefore, we started examining the complete protocol load in the entire network. In
a typical network of HTTP servers, following are the protocols traffic which are listed
below. We captured the traffic when the data rates were considerably low, as listed in
Fig. 16.13.

Figure 16.13 The protocol hierarchy statistics of the network

To find out the real cause of the issue of losing data in response to an HTTP command,
a network analysis was carried out using Wireshark. We studied and analyzed the TCP,
HTTP, and ARP protocols carefully to make the network error-free. Following are the
results of the analysis.
We captured network traffic using the Wireshark sniffer to analyze the data transfer
between a client PC running IP=192.168.1.249 and one specific server having IP=192.168.1.11.
The analysis is based on sending an HTTP to GET command to read the status of a
solenoid valve 192.168.1.11/rpc/solinoid1_readstatus/read and studied
the command HTTP response, step by step, till we got the result given as follows.

TCP/HTTP webserver

TCP is a protocol where one establishes a connection. For this, a number of packets
were first exchanged, and both sides of the connection went through several states which
are as follows
1. receive SYN
2. send SYN,ACK
714ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

3. receive ACK (the connection is now established)


4. receive ACK with HTTP GET command
5. send ACK
6. send FIN,ACK with HTTP data (e.g., 200 OK)
7. receive FIN,ACK
8. send ACK
The step by step process was verified to read the present status of a valve by sending
an HTTP Get command GET /rpc/solinoid1_readstatus/read till it sent out
the final TCP stream result of ‘0’( means OFF) which looked as follows in Fig. 16.14.

Figure 16.14 TCP stream to verify the correct command response

16.7 TCP ANALYSIS

Wireshark sniffer was ran in the embedded network, with all its servers sending data
continuously to the LabVIEW-based client PC, which was running on a Windows 7 PC
and Wireshark software. A live file was captured for 5 minutes and saved for off-line
analysis. Following is the analysis results.
from Time= 0.00000000 s
Analyzing TCP protocol up to a particular interval of Time = 0 to 0.00087900 s reveals
that TCP states receive SYN, send SYN, ACK is happening properly till the connection
is established (receive ACK) to destination IP= 192.168.1.11 as shown in Fig. 16.15.
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ715

Figure 16.15 TCP traffic capture

From the above, each packet was analyzed separately as shown below. The detailed
packet analysis is shown in subsequent figures, Figs. 16.16 to 16.18, as shown below.

Figure 16.16 Packet 1

At time equal to zero, TCP is trying to establish a connection. For establishing a


connection TCP sends an SYN packet with the corresponding sequence number to open
the connection.
716ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Example: [SYN] seq=0 (SYN packet length =66)


Note: seq=0 because no data has to be sent, TCP is only opening a connection.

Figure 16.17 Packet 2. Time= 0.0008500 s

Now the server (192.168.1.11) is sending an SYN packet along with ACK (Acknowledgement)
to validate the connection.
Example: [SYN ACK] seq=0 (shown in line 2 of the figure)

Figure 16.18 Packet 3


’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ717

After sending ACK to the server, the client is now able to send packets to the server.
Example: [ACK] seq=1

16.8 HTTP ANALYSIS

Figure 16.19 demonstrates how an HTTP client-server communication takes place.

Figure 16.19 HTTP communication

HTTP Capture Analysis

The captured file is further analyzed for the correctness of HTTP communication between
a server and a client.

Starting an HTTP conversation

Packet 1

Time = 0.00093800 seconds


GET command of length=121 : GET /rpc/solinoid1_readstatus/read
HTTP/1/1 indicates the protocol/version used
718ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

Figure 16.20 HTTP conversation

16.9 ANALYZING ERRORS IN HTTP USING HTTP ERROR CODE FILTERS


1. HTTP error responses (code 4xx for client errors, code 5xx for server errors):
http.response.code >= 400
2. HTTP client error responses:
http.response.code >= 400 and http.response.code <= 499
3. HTTP server error responses:
http.response.code <= 599 and http.response.code >= 500
4. HTTP response code 404 (not found):
http.response.code == 404
All above filters were applied into the cryogenic network traffic. No packets were
displayed with error.

16.9.1 HTTP Status Codes


Table 16.2 HTTP status codes
Category Category Name What is it for
1xx Informational Provides general information, without any indication of
failure or success
2xx Success Indicates that the action request by the client was
received, accepted and processed successfully
3xx Redirection Indicates that further action should be taken by the user
agent to fulfill
4xx Client error Indicates a client error
5xx Server error Indicates a server error
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ719

16.9.2 HTTP Success Codes


Table 16.3 HTTP success codes
Code Status Explanation What to do
200 OK Standard OK response –
201 Created The request has been fulfilled and a new –
resource has been created.
202 Accepted The request was accepted and is still in –
process
203 Non-authoritative The request was received with content from –
information another server, and it was understood.
204 No content The request was received and understood, –
and the answer that is sent back has no
content.
205 Reset content This is a server request to the client to reset –
the data that was sent to it.
206 Partial content Response for a partial document request –

Figure 16.21

From the above analysis, it was seen that all the network communication was intact
HTTP success code 200 was obtained.

16.9.3 ARP (Address Resolution Protocol) Analysis

ARP is used by IP to resolve the destination MAC address out of the IP address of the
device that we wish to communicate with. When we send packets to a destination, the
first packet is the ARP request to find the MAC address of the destination. We get it
from the destination and then send the other packets destined for it.
720ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

16.9.4 Issues with Gratuitous ARP and Solution


Gratuitous ARP is used when a node (end system) has selected an IP address and then
wishes to defend its chosen address on the local area network (i.e., to check no other
node is using the same IP address). It can also be used to force a common view of the
node’s IP address (e.g. after the IP address has changed).

Figure 16.22 Troubleshooting ARP protocol problem


Step-1
On capturing network traffic using Wireshark, following problems were identified using
Expert Info option available in Wireshark. The problems were mentioned in Figs. 16.23
and 16.24.

Figure 16.23

With the help of Expert Info, it is found that there are some IP conflicts between some
devices in the network.
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ721

Error 12.942080000 Cisco_aa:1f:97 Cisco_ea:06:00 ARP 64


Gratuitous ARP for 192.168.1.254 (Reply) (duplicate use of
192.168.1.254 detected!) [ETHERNET FRAME CHECK SEQUENCE INCORRECT]

Figure 16.24
Step-2

To find the device from where IP conflict is happening, we had applied a filter arp.
duplicate-adress-detected

Figure 16.25
After applying the filter, we found that the IP conflict happened between 6 Cisco
(Model: Cisco 300-28) network switches which have a common IP 192.168.1.254.
On analyzing one particular packet having IP conflict problem, following messages
were explored.
Duplicate IP address detected for 192.168.1.254 (08:d0:9f:aa:1f:97)
- also in use by (a0:cf:5b:ea:06:00)
722ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

This message is also shown in the figure below.

Figure 16.26

16.9.5 IO GRAPH Analysis for Duplicate IP


Graph-1 = All traffic
Graph-2, Filter-1 = aduplicate-address-detectedrp.
Graph-3, Filter-2 = arp

Figure 16.27
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ723

Plot-1

From the above plot, it was found the number of ARP request is increasing at time=153.75
seconds
The following graphs show the filters ‘aduplicatt-address-detectedrp’ and arp results
Graph-1, Filter-1 = aduplicate-address-detectedrp.
Graph-2, Filter-2 = arp

Figure 16.28

Plot-2

From the above plot, we can observe that ARP request was increasing at certain time
on the plot at
Time= 33 seconds
Time= 93 seconds
Time= 153 seconds
Time= 213 seconds
On applying filter = duplicate-address-detected, it is found that the gratuitous ARP
request was sent across the network which is an indication of duplication of IP addresses.
On analyzing the IO graph, it is clear that ARP requests were increasing at different
intervals of time. To check the number of bytes sent by ARP, we had used the Protocol
Hierarchy option available in Wireshark. It was found that 4928 bytes were sent when
there was a duplication of IP shown in Fig. 16.29. Here we compared when there was
724ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

no IP duplication; it was found only 3468 bytes were sent by ARP shown in Fig. 16.30.
Now it is confirmed that the ARP protocol is flooding the network when there is a
duplication of IP, and an IP duplication is caused by Cisco network switches.

Figure 16.29 Protocol hierarchy (IP duplication)

Figure 16.30 Protocol hierarchy (IP duplication)


’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ725

The Cisco switches’ IP numbers were modified remotely to remove all the IP conflicts
by doing the following.

Changing IP of Cisco (Model: CISCO 300-28) network switches

Ȋȱ Open any browser


Ȋȱ Open Cisco Network Switch Control Panel using default ip= 192.168.254
Ȋȱ Enter login details (Default username= cisco & Password- cisco)
Ȋȱ After logging into control panel, a prompt will open to change the default password.
Our new password= admin
Ȋȱ Now after changing the default password, we successfully login into Cisco network
switch control panel.
Ȋȱ Now look for Change Device IP on the home page of the control panel.
Ȋȱ Click on Change Device IP
Ȋȱ A window will open with options available for changing IP
Ȋȱ By default, dynamic mode is selected
Ȋȱ Select Static mode
Ȋȱ Now insert your desired IP.
The following IP is configured in the network switches as per as their location, details
are given below in Table 16.4.

Table 16.4 IP and MAC table of Cisco network switches


S.NO. LOCATION MAC ADDRESS IP ADDRESS
1. BUNCHER SWITCHD5:CC:6F 192.168.1.230
2. LINAC AREA SWITCHAA:23:AB 192.168.1.231
3. REBUNCHER SWITCHEA:06:00 192.168.1.232
4. NEW REFRIGRATOR SWITCHDA:5D:5A 192.168.1.233
5. GMS SWITCHDA:5D:5A 192.168.1.234
6. CONTROL ROOM SWITCHAA:IF:97 192.168.1.235

LOGIN DETAILS
USERNAME- cisco
PASSWORD- admin
The following final results verification.
The following are some of the Wireshark results, after fixing the IP conflict issue:
726ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—ȱ

1. No IP conflict occurred between the network switches.

2. IO graph, after fixing duplicate IP address problem.

Plot (No IP duplication)

Looking to the above IO graph, unwanted ARP requests due to IP duplication were
removed. The ARP request is somewhat continuous over the time, which is an indication
of a good network working in a normal condition.
’›Žœ‘Š›”ȱ ˜›ȱ Ž ˜›”ȱ—Š•¢œ’œȳ727

16.9.6 Conclusion

The network issues have been resolved step by step and the HTTP packet checker is
running smoothly without any single alarm being generated for the past one month,
round the clock.

REFERENCES

1. https://www.wireshark.org
2. https://www.udemy.com

REVIEW QUESTIONS

1. What is Wireshark?
2. How to use Wireshark with network analysis?
3. Explain HTTP protocol analysis using Wireshark?

ANSWERS

1. Wireshark is a network analysis tool.


2. At its core, Wireshark is designed to breakdown packets of data being transferred
across different networks.
3. Wireshark can capture and analyse—Hyper text transfer protocol (HTTP)
traffic. It can find response codes, http drops, http round trip times, http message
analysis.
NETWORKING BASICS AND 8/32-BIT
MICROCONTROLLER-BASED ETHERNET
17 HTTP SERVER-CLIENT INTERFACING

OBJECTIVE
After going through this chapter, the students will be able to understand, how:
Ȋȱ To create embedded servers to read pressure, temperature and voltage data, and
make remote changes.
Ȋȱ To create GUI using Qt for aforementioned servers to manipulate the server from
any computer with an Ethernet connection.
Ȋȱ To learn and understand hardware designing and port manipulation, with
connections to microprocessors.
Ȋȱ To experiment with multiple embedded systems.

17.1 INTRODUCTION to Qt
17.1.1 Why Qt for web-enabled applications?
Qt is a cross-platform application and UI framework that is widely used for developing
application software with a graphical user interface (GUI), and also non-GUI programs
such as command-line tools and consoles for servers. It includes a cross-platform class
library, integrated development tools and a cross-platform IDE. Using Qt, you can write
web-enabled applications once and deploy them across many desktops and embedded
operating systems without rewriting the source code. Distributed under the terms of
the GNU Lesser General Public License (among others), Qt is a free and open source
software (Fig. 17.1).

17.2 BASIC CONCEPTS: WEB SERVER


17.2.1 Socket Programming (TCP) Using C under Linux

Linux provides a high-level socket API that allows a programmer to easily connect to
any TCP or UDP service. In this section, we will see how this works, by implementing
a simple HTTP client which will request a web page given the hostname and the page
name, then read the server answer, and output the HTML content of the reply.
To be able to connect to a service built on the top of TCP, we first need to create a
socket for the TCP protocol, fill in a network address structure representing our
destination and the port to connect to and use the latter to connect to the remote server.
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ729

Figure 17.1

From there, we will be able to send and receive data over the network. Once we are
done, we will close the connection. Below given is the C code for a simple HTTP client
that will get the host and the page to request from the command line arguments, resolve
the hostname to an IP, connect to this IP on port 80, build the HTTP query, send it and
the retrieve the page content.
Minimum requirements for learning socket programming: First, we require a Linux
operating system. We should have an IP and the port number. At the end, we must
know the server and the client concept.
Major steps that are required at the server side: First, we will create a socket with the
help of socket() function. Then we will bind the socket which we had created by
using bind(); after that we will listen for the connections with listen(). Then we
will accept the connection. At the final stage, we will send and receive data by using
read() and write() system calls.
Major steps that are required at the client side: First, we will create a socket with the
help of socket(). Now we will connect the socket to the address of the server using
the connect() system call. At the final stage, we will send and receive data by using
the read() and write() system calls.
In the ‘server client’ concept, first we will write the server coding. Then the client coding
is written. Last stage comprises running the program.
Header files required at server side to do socket programming:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
730ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Header files required at client side to do socket programming:


#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
What is a server: A computer or computer program which manages access to a centralized
resource or service in a network.
What is a client: A desktop computer or workstation that is capable of obtaining
information and applications from a server.
How many arguments required by a server side: Two arguments are minimum which
are required at the server side.
Example:
./server/4546.
./server: It is used as the first argument.
/4546: It is used as the second argument.
Sockfd has various parts:
1. (AF_INET): It is an Internet address in IP4 format.
2. (SOCK_STREAM): It says it is a TCP socket.
3. (0): Appropriate socket we get from the system.
4. BZERO COMMAND: It is used for clearing the structure of the server address.
5. ATOI COMMAND: It is used to convert the char to int.
6. HTONS (PORTNO): To convert host protocol format into n/w format.
Refresh some basic examples of structure pointers, before beginning server
coding in C language.
struct Student
{
int age;
char *name;
};
int main()
{
Student studentobj;
Studentobj.age=22;
Studentobj.name=”jj”;
printf(“age=%d\n”,studentobj.age);
printf(“name=%s\n”,studentobj.name);
}
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ731

The output of the above code is:


Age =22 Name =jj
What is a typedef: It helps us to define our own identifier in place of a specifier such
as int, float and double. To make the code clear, we do not need to rewrite struct
again and again.
Example illustrating structure using pointers:
#include<stdio.h>
Typedef struct student
{
int age;
char age2;
char *name;
}student;
int main()
{
student studentobj[2];
student *ptr;
studentobj[0].age = 11;
studentobj[0].name = “AA”;
studentobj[0].age2 = ‘a’;
studentobj[1].age = 22;
studentobj[1].name = “BB”;
ptr = &studentobj[1];
printf(“age =%d\n”,studentobj[0].age);
printf(“name =%s\n”,studentobj[0].name);
printf(“age =%d\n”,studentobj[1].age);
printf(“name =%s\n”,studentobj[1].name);
printf(“age =%d\n”,ptr->age);
printf(“name =%s\n”,ptr->name);
}
Output for the above code is:
Age =11
Name =AA
Age =22
Name =BB
Age =22
Name =BB
* /Server & client code
732ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

SERVER CODE FOR SOCKET PROGRAMMING:

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
void error(char *msg)
{
perror (msg);
exit(1);
}
int main(int argc,char *argv[]);
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr cli_addr;
int n;
if(argc<2)
{
fprintf(stderr,”error, no port provided\n”);
exit(1);
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
error(“error opening socket”);
}
bzero((char *) & serv_addr, sizeof(serv_addr));
portno=atoi(argv[1]);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(portno);
if(bind(sockfd,(struct
sockaddr *) &serv_addr, sizeof(serv_addr))<0)
{
error(“error on binding”);
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd
= accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ733

if (newsockfd<0)
{
error(“error on accept”);
}
bzero(buffer,256);
n=read(newsockfd,buffer,255);
if(n<0)
{
error(“error reading from socket”);
}
printf(“here is the message:%s\n”,buffer);
n=write(newsockfd,”i got the message”,18);
if(n<0)
{
error(“error writing to socket”);
}
return 0;
}
Client code for socket programming:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[]);
{
int sockfd,portno,n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc<3)
{
fprintf(stderr,”usage %s hostname port\n”, argv[0]);
exit(0);
}
734ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

portno=atoi(argv[2]);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if (sockfd<0)
{
Error (“error opening socket”);
}
Server =gethostbyname(argv[1]);
If(server == NULL)
{
Fprintf(stderr,”error, no such host \n”);
Exit(0);
}
bzero((char *) serv_addr, sizeof (serv_addr));
Serv_addr.sin_family = AF_INET;
Bcopy ((char *) server-
>h_addr,(char*)serv_addr.sin_addr.s_addr,server->h_length);
serv_addr.sin_port=htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr))<0)
{
error(“error connecting”);
}
printf(“please enter the message:”);
bzero(buffer,256);
fgets(buffer,255,stdin);
n=write(sockfd,buffer,strlen(buffer));
if(n<0)
{
error(“error writing to socket”);
}
bzero(buffer,256);
n=read(sockfd,buffer,255);
if(n<0)
{
error(“error reading from socket”);
}
printf(“%s\n”,buffer);
return 0;
}
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ735

Compiling the code -- at the server side: First we open a terminal in linux. We type
pwd to know where the file is saved. Then cd is used to go to that directory such as in
this case ser_cli. Then we will write ls that denotes the list of files available in
ser_cli. After that we will compile by using this command cc server.c - o server.
out. Finally, the program will be run by using the command ./server.out 4547
Compiling the code -- at the client side: First we will open a new terminal for the client
side on the same computer. We write pwd there to go into the command where the file
is saved. Then cd is used to go to that directory which in this case is cd ser_cli.
Then we will write ls that denotes the list of files available in ser_cli. After that we
will compile by using the command cc client.c - o client.out. Finally, the
program will be run by using the command ./client.out localhost 4547
Output:
At client terminal it will ask to print the message.
At server terminal it will indicate I got the message.

17.2.2 HTTP Client in Python

Here is a small HTTP client program in Python which reads websites.


import httplib
conn = httplib.HTTPConnection(“http://www.worldtimeserver.com/
current_time_in_IN.aspx?city=New_Delhi”)
conn.request(“GET”, “/index.html”)
r1 = conn.getresponse()
print r1.status, r1.reasondata1 = r1.read()
print data1
import httplibconn = httplib.HTTPConnection(“www.iuac.ernet.in”)
conn.request(“GET”, “index.html”)r1 = conn.getresponse()
print r1.status, r1.reason
data1 = r1.read()
print data1
Please refer to Appendix 1 for learning Python script in detail.

17.2.3 Basic Web Server Coding Example

Below is a web server & client code architecture for creating and accessing a tiny web
server [Fig. 17.2].
EXPLANATION -- at the client side: First we will include the various header files. Then
various commands will be used. Then create a socket and bind the socket. Now we will
listen to he connections from the socket.
Port no: 8181
IP address: 127.0.0.1
736ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Explaination with the help of a diagram is given below:

Figure 17.2

17.3 BASIC HARDWARE AND HTML CODING-EMBEDDED SERVER & CLIENT

The hardware used in small distributed I/O data acquisition system is based on low-cost
microcontroller based on web service server boards whose hardware boards use 8-bit
RISC processor with the Ethernet controller, and the software platform use AVR-GCC
for firmware and Python for OS independent human machine interface.
This system can measure all kinds of electrical and thermal parameters such as voltage,
current, thermocouple, RTD and so on. The measured data can be displayed on web
pages at different geographical locations and at the same time can be transmitted through
the RJ-45 Ethernet network (using TCP/IP protocol) to a remote web based data
acquisition and control (DAC) monitoring system by using HTTP protocol. A central
embedded single board can act as a central CPU to communicate between web servers
automatically. The novelty of this proposed system is a substitute of web PLC for industry
applications.
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ737

17.3.1 Contents of the webpage for Digital Devices-HTML inside C++ Code
Here is a sample HTML code embedded in a tiny server in C ++ (Figs. 17.3 & 17.4).

Figure 17.3

Figure 17.4
738ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

17.4 TCP/IP STACK

The TCP/IP stack is a complete set of networking protocols. The OSI Model was meant
to be a standardized way of connecting devices together, and most protocols have some
direct correlation with the OSI Model. The OSI Model has seven layers, but the TCP/IP
stack which is the most common protocol suite in use today has 4. So the easiest way
to look at the TCP/IP stack is to compare them as shown in Fig. 17.5.

Figure 17.5

Table 17.1
Layer No. OSI Model Name TCP/IP Equivalency TCP Protocols at this Level
1. Physical Network Access or Cables and Types of
Interface Layer Transmissions
2. Data Link Layer Network Access or Ethernet
Interface Layer
3. Network Internetwork IP (biggest most important)
4. Transport Transport TCP/UDP, Multiplexing, PAR
5. Session Application
6. Presentation Application
7. Application Application

So what does a model really mean? Well, a model provides a guide to ensure that
everything is considered when communications are constructed. That is why the OSI
Model has come to stay. Generally, when people design applications in TCP/IP they need
to get it down to the IP, and the port level do the encoding and have it handed over to
the TCP that will break it into segments and ensure an end-to-end delivery or UDP that
will just break it down and send it. TCP/IP and the OSI Model go hand in hand, as do
most protocol suites once you understand them, but there is a ton of studies involved in
understanding what they actually are. Topics such as IP sub-netting, and multicast exist
because of TCP/IP, NAT/PAT, IPv6. The Internet exists as a direct result of TCP/IP winning
as the chief protocol. There is no actual manifestation of the OSI Model, just protocols that
were designed to handle same layer communications and adjacent layer communications,
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ739

and deliver your bits around the world. Finally, the US Military originally designed TCP/
IP, and Microsoft chose it as its primary protocol, that should tell you why it became so
big.

Figure 17.6

17.5 TCP/IP IMPLEMENTATION IN MICROPROCESSORS/MICROCONTROLLERS

A wide variety of standards are followed for Ethernet, i.e Address Resolution Protocol
(ARP), Internet Protocol (IP), ICMP (Internet Control Message Protocol), TCP (Transmission
Control Protocol), and DHCP (Dynamic Host Configuration Protocol). Ethernet needed to
be built so that packets could go in and out; ARP was to be built on top of the Ethernet
to allow for other computers to discover the existence of our controller; IP needed to be
built in order to provide transport for our packets; ICMP was to be built so that we could
effectively ping our controller; TCP was to be used as the main transmitter of packets;
DHCP was to be enabled so that a router could dynamically assign an IP address to our
controller.
The standard TCP is a protocol to establish a connection. To do this, a number of packets
needs to be exchanged between two sides first to establish the connection; then data packets
can be exchanged. Usually, a complicated state-machine is needed to implement the TCP
protocol.
Building the Ethernet protocol suite is fairly easy. All that needed to be done is to switch
the source and destination Media Access Control (MAC) address, which is a 12 octet
unique number identifies the two addresses. ARP is a bit more complicated. To implement
ARP, the microprocessor needed to search for a packet that was MAC addressed to
FF:FF:FF:FF:FF:FF and had an IP address that matched its own. Once it found this, it built
a reply that would allow for the computer that sent the request to associate the controller’s
IP address with its MAC address, so that any request to that IP would be sent to that
MAC address. IP implementation is a bit trickier, with the checksum field being notably
740ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

difficult to set up correctly. The checksum consists of the 16-bit one’s complement addition
of the fields of the IP header. Other IP fields were easier to set. ICMP is also a pain to
implement for the same reason: the checksum field did not seem to work properly and
required a litany of recoding before the protocol worked.
TCP is initially to be implemented in order to allow for HTTP, or web pages, to be the
mechanism by which the controller was accessible. This was highly desirable, as nearly
every Internet-connected computer has a web browser, which would make the controller
ubiquitous and require no specialized software for interfacing. The methodology for
connecting via TCP was highly simplified and so was the TCP implementation, which
drastically simplified TCP operations. By treating every TCP request as a single packet
transmission protocol (without delving into the protocol in too much depth, most TCP
connections are left open until all the packets have been sent, which requires some careful
management of states), much of the complex logic and negotiation can hypothetically be
left out. In this case, we attempted to implement the initial response to a TCP request (SYN/
ACK), an intermediate response (ACK), and the final response with data (DATA/FIN/
ACK). During coding, we managed to get the SYN/ACK packet working properly as a
simple protocol.
The replacement protocol was User Datagram Protocol (UDP), an extremely lightweight
protocol that is also omnipresent on the Internet in various forms. The plus side of this
protocol technology is that the implementation is much simpler than TCP.

17.6 MICROPROCESSOR SELECTION FOR TCP/IP STACK

With a microprocessor with 1 KB SRAM, it is impossible to implement the full TCP stack.
Also, the web page that is normally used to control a relay or read a temperature sensor
etc., is very simple. Therefore instead of implementing a full TCP protocol, a single data
packet TCP protocol is used. Your web page contents, including all html tags, must be in
one packet. The length of the packet is limited by the SRAM size. It is sufficient for simple
web pages as shown below. Firmware is usually done in the c language, which can be
coded to create IP and MAC addresses. MAC addresses are usually unique only to
identify the vendor, not otherwise. So one can firmware code MAC of your own in a
private network. The IP address must be a free address with your network range, e.g.,
static uint8_t mymac[6] = {0x54,0x55,0x58,0x10,0x00,0x24};
static uint8_t myip[4] = {192,168,1,15};
static char baseurl[]=”http://192.168.1.15/”; etc.

17.7 TCP VS UDP

The flow of traffic across the Internet takes place on the basis of protocols, which are TCP
(Transmission Control Protocol) and UDP (User Data gram Protocol). While TCP is more
popular across the Internet, UDP cannot be rendered completely. TCP allows error correction
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ741

but UDP does not. In the case of TCP, there is a guarantee of the data delivery at the
download or addressee point. This is made possible by a ‘flow control’, which determines
the requirement for resending the data. Flow control also checks and stops the transmission
of data unless previous packets have been successfully delivered. This is based on the
process in which the client can request resending of a particular packet from the server
until the entire packet has been received in its original form. UDP is also common, but it
cannot be relied upon for sending important data like secure files, important web pages,
etc. It is used mostly for streaming media including audio and video. UDP is faster than
TCP and media players work best with it. There is no flow control or error correction, but
the speed is far greater, so despite streaming media not being of high quality, it can be
viewed properly with UDP. TCP is safer as compared to UDP as the latter serves as an
adequate cover for viruses. TCP also has a complicated frame structure. In case of UDP,
the operating system has to do very little work to translate the data. UDP is connectionless,
while TCP is connection-oriented which requires it to establish a full connection between
the receiver and the sender. The connection needs to be closed after the transfer is complete
to free the system resources that were being used by the protocol. UDP requires no
authorization and allows free-floating dissemination of data.

17.7.1 Difference between TCP and UDP

There are two types of Internet protocol (IP) traffic, and both have different uses.
1. TCP: TCP is a connection-oriented protocol; a connection can be made from a client
to a server, and then onwards on any data can be sent along that connection.
Ȋȱ Reliable: When you send a message along a TCP socket, you know it will get there
unless the connection fails completely. If it gets lost along the way, the server will
re-request the lost part. This means complete integrity -- things don’t get corrupted.
Ȋȱ Ordered: If you send two messages along a connection, one after the other, you
know the first message will get there first. You don’t have to worry about data arriving
in the wrong order.
Ȋȱ Heavyweight: When the low level parts of the TCP ‘stream’ arrive in the wrong
order, resend requests have to be sent, and all the out of sequence parts have to be
put back together -- so it requires a bit of work to piece together.
2. UDP: It is a simpler message-based connectionless protocol. With UDP you send
messages (packets) across the network in chunks.
Ȋȱ Unreliable: When you send a message, you don’t know if it’ll get there. It could get
lost on the way.
Ȋȱ Not ordered: After you send out two messages, you don’t know what order they’ll
arrive in.
Ȋȱ Lightweight: No ordering of messages, no tracking connections, etc. It’s just fire
and forget! This means it’s a lot quicker, and the network card/OS has to do very
little work to translate the data back from the packets.
742ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

TCP/IP is a protocol family that is used world-wide as the de facto standard for network
communications between user processes. It is a collection of protocols that include TCP,
IP, UDP, ICMP, ARP, RARP, and numerous others.
One problem faced by embedded systems that run remotely or unattended is that of
monitoring the system’s status. In the past, this was accomplished through RS-485, RS-232,
or front-panel indicators, and usually required human intervention. Now that almost
everyone has access to a web browser and e-mail, the Internet seems to be an alternate
solution to these problems.
As a designer who must integrate TCP/IP within an embedded application, you must
decide what type of Internet support you will include. Web, e-mail, and port interfaces
are all available to you using a TCP/IP stack. Today, there are numerous stack vendors
that can accommodate your requirements.

17.7.2 UDP

UDP is a simple, datagram-oriented, transport layer protocol: each output operation by a


process produces exactly one UDP datagram, which causes one IP datagram to be sent.
This is different from a stream-oriented protocol such as TCP where the amount of data
written by an application may have little relationship to what actually gets sent in a
single IP datagram. Figure 17.7 shows the encapsulation of a UDP datagram as an IP
datagram.

Figure 17.7 UDP encapsulation

RFC 768 [Postel 1980] is the official specification of UDP. UDP provides no reliability:
it sends the datagrams that the application writes to the IP layer, but there is no guarantee
that they ever reach their destination. Given this lack of reliability, we are tempted to
think we should avoid UDP and always use a reliable protocol such as TCP. After we
describe TCP, we’ll return to this topic and see what types of applications can utilize
UDP.
The application needs to worry about the size of the resulting IP datagram. If it
exceeds the network’s MTU [Maximum Transmission Unit], the IP datagram is
fragmented. This applies to each network that the datagram traverses from the source
to the destination, not just the first network connected to the sending host.
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ743

17.7.3 UDP Header

Figure 17.8 shows the fields in the UDP header.

Figure 17.8 UDP header

The port numbers identifies the sending and receiving processes. We know that TCP
and UDP use the destination port number to de-multiplex incoming data from IP. Since
IP has already de-multiplexed the incoming IP datagram either to TCP or UDP (based
on the protocol value in the IP header), this means the TCP port numbers are looked
at by TCP, and the UDP port numbers by UDP. The TCP port numbers are independent
of the UDP port numbers.

17.7.4 TCP Protocol

TCP is a protocol where one establishes a connection between two Ethernet based
systems. For this, a number of packets are first exchanged and both sides of the connection
go through several states. Once the connection is established, a number of data packets
can be sent. More than one packet, large amounts of data, can be sent. Counters and
the state machine ensure that the actual user data arrives in the correct order and without
data loss.

17.7.5 TCP State Machine

It is the TCP state machine, which a normal TCP stack must implement. A web server,
for example, wait in state LISTEN. When it receives a SYN then it sends a SYN,ACK
packet and go to state SYN RCVD. There it waits until it has received the ACK for the
SYN,ACK and then the connection is established. When the web server has sent all the
data for the requested page, it sends an FIN in order to move to state towards CLOSING.

17.8 HTTP

HTTP functions as a request-response protocol in the client-server computing model.


In HTTP, a web browser, for example, acts as a client, while an application running on
a computer hosting a web site functions as a server. The client submits an HTTP request
744ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

message to the server. The server, which stores content, or provides resources, such as
HTML files, or performs other functions on behalf of the client, returns a response
message to the client. A response contains completion status information about the
request and may contain any content requested by the client in its message body. A
web browser (or client) is often referred to as a user agent (UA). Other user agents can
include the indexing software used by search providers, known as web crawlers, or
variations of the web browser such as voice browsers, which present an interactive voice
user interface.
The HTTP protocol is designed to permit intermediate network elements to improve
or enable communication between clients and servers. High-traffic websites often benefit
from web cache servers that deliver content on behalf of the original, so-called origin
server, to improve the response time. HTTP proxy servers at network boundaries facilitate
communication when clients without a globally routable address are located in private
networks, by relaying the request and response between clients and servers. HTTP is an
Application Layer protocol designed within the framework of the Internet Protocol Suite.
The protocol definitions presume a reliable Transport Layer protocol for host-to-host data
transfer. Transmission Control Protocol (TCP) is the dominant protocol in use for this
purpose. However, HTTP has found application even with unreliable protocols, such as
UDP in methods such as Simple Service Discovery Protocol (SSDP). HTTP resources are
identified and located on the network by Uniform Resource Identifiers (URIs)—or, more
specifically, Uniform Resource Locators (URLs)—using the HTTP or HTTPS URI schemes.
URIs and HTML form a system of interlinked resources, called hypertext documents, on
the Internet that led to the establishment of the World Wide Web in 1990 by the English
computer scientist and innovator Tim Berners-Lee.
The original version of HTTP (HTTP/1.0) revised to HTTP/1.1. HTTP/1.0 uses a separate
connection to the same server for every request-response transaction, while HTTP/1.1
can reuse a connection multiple times, to download, for instance, images for a just
delivered page. Hence HTTP/1.1 communications experience less latency as the
establishment of TCP connections presents considerable overhead.

17.8.1 Embedded Web Server

The whole point of using TCP is that one can send more than one packet of data, but
we don’t need that functionality. We need TCP only because HTTP is based on it and
we want HTTP in order to use our web browser. Under the assumption that you will
never need to send more than one packet with data, the whole TCP protocol and state
handling can be simplified a lot. We can, for example, send the FIN immediately together
with the data. This makes the state handling for the closing of the connection very
simple.
Single data packet TCP/HTTP web-server for embedded applications only: The single
data packet web-server will go through the following TCP states:
1. receive SYN
2. send SYN,ACK
3. receive ACK (the connection is now established)
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ745

4. receive ACK with HTTP GET command


5. send ACK
6. send FIN,ACK with HTTP data (e.g 200 OK)
7. receive FIN,ACK
8. send ACK
Web server branches between UDP and TCP with port 80 (=web-server). Again port
no. 88, etc., can be used depending upon the user preference which is again firmware
codable.

17.8.2 URL

In order to build an interactive web page, the HTML code provides <a href= for
links and HTML forms for more complicated dialogs. The problem with forms is however
that HTML forms are code intensive and difficult to decode. A much easier solution is
to implement virtual folders and files. The password can be one folder. In other words,
you have to type http://IP_or_HOST/password. Behind this URL we can implement
a virtual file which is the command -- in our case, switch on (=1) or switch off (=0). The
full URL would then, for example, look like this.
Switch on:
http://IP_or_HOST/password/1
Switch off:
http://IP_or_HOST/password/0
See the current status and change nothing:
http://IP_or_HOST/password
This is very easy to understand and decode in the microcontroller. If you want to
implement just a thermometer or present some other readings without password protection,
then you can just implement the ‘root’ folder http://IP_or_HOST and delete the /
password/command code in main.c.

17.8.3 Pages

Embedded systems are generally small in size. Not only physically, but also small in terms
of memory and CPU speed. All embedded TCP/IP stacks have therefore a low limit on
the number of parallel users (e.g., 2-5 parallel HTTP connections). The small stack takes a
different approach. The amount of data that we want to display is generally small. Maybe
you would want to display the values of attached sensors or you want to switch on/off
something as in the above example. To display that on a web page requires just a few
bytes of data. We limit the size of the web page to a few hundred bytes. With this limit
in place, we don’t have to have a limit on the number of parallel connections. With TCP/
IP stack on a CPU, we can get really top performance out of this web server. There is no
hard-coded limit to the number of users, and it can serve hundreds of web pages per
second. Some small PC based web servers would have trouble to keep up with it.
746ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

17.8.4 MAC

A MAC (Media Access Control) address, is a 48- or 64-bit address associated with a network
adapter. While IP addresses are associated with software, MAC addresses are linked to
the hardware of network adapters. For this reason, the MAC address is sometimes called
hardware address or burned-in address (BIA) or physical address. MAC addresses are
expressed in hexadecimal notation in the following format: 01-23-45-67-89-AB in the case
of a 48-bit address, or 01-23-45-67-89-AB-CD-EF in the case of a 64-bit address. Colons (:)
are sometimes used instead of dashes (-).
MAC addresses are often considered permanent, but in some circumstances, they can
be changed. A host has one Ethernet address (MAC address) per interface and one or more
IP addresses per interface. Those MAC addresses are unique world-wide, but this is just
to make the hardware distribution easier. They just have to be unique in your local
environment. That is, your PCs, your WI-FI router and the router of your Internet provider
have to have distinct MAC addresses.

17.8.5 Ports

Port numbers distinguish the network applications on the host. Only one port number
can be active at a time. That is, you cannot have two web servers running on port 80
on the same host. When you send a message, a local (random) port number is allocated
and the request is sent to the remote IP and port number (e.g. 80=web). If you have an
application process listening on port X locally for connections (server) then you cannot
start a second application sending on the same port. However, the same program can
send and receive on the same port. The port numbers below 1024 are reserved numbers.
We just pick a port number 1200.

17.8.6 Broadcast

Broadcast is possible also on the underlying Data Link Layer in Ethernet networks.
Frames are addressed to reach every computer on a given LAN segment if they are
addressed to MAC address FF:FF:FF:FF:FF:FF. Ethernet frames that contain IP broadcast
packages are usually sent to this address. Ethernet broadcasts are used by Address
Resolution Protocol to translate IP addresses to MAC addresses; the reply packet is sent
back to the broadcast address FF:FF:FF:FF:FF:FF.

17.8.7 UDP -- Is it Good?

While we experienced an almost 100% accuracy from the UDP Ethernet controller, with
only very rare packets being dropped (less than 1% of the time) UDP is unreliable! That
is not really true. On a local LAN there is almost no packet loss unless you have problems
with the hardware duplex configuration. But that is a different problem and should be
fixed early. The packet loss ratio on a local non-congested LAN is better than 10EE-9 or
one in 100000000. With normal home traffic volumes on a 24/7 Linux network, it is far
less than one packet per month. UDP on a local network is very reliable and all that it
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ747

means is that we must be able to resend the data without causing harm. We must not
implement a ‘toggle’ switch, but use one command to switch on and another to switch
off. If we resend the on command (because it was lost) the result will still be ‘on’.

17.9 FILTERS

As you can imagine there is the problem that Ethernet can supply much more data than
that little microcontroller can process over the serial SPI interface even if that interface
runs with several MHz speed. There is a buffer in the Ethernet controller, but it could fill
up easily with garbage on a noisy Windows network. It has therefore filters.
The traffic we want is UDP traffic with the destination of our MAC address. On the
top of that, we have to process ping (IP/ICMP packets for our MAC address) and ARP
packets to our MAC or to broadcast. No IP networking is possible without ARP. All other
packets, especially broadcast IP packets, can be ignored. It has a number of simple filters
which we will use. There is a unicast filter (only packets with our MAC as the destination).
The only other packets we want are broadcast ARP. There is a packet match filter and we
program it to the destination MAC=FF:FF:FF:FF:FF:FF (broadcast) and only for Ethernet
content-type ARP.

17.10 SWITCHES, HUBS AND WI-FI ROUTERS

Ten years ago, hubs were the state-of-the-art interconnection points on a LAN. A hub
is just an amplifier and it does not look at the data in the packet. Today, it is even
difficult to buy a hub. Most boxes, even for small office applications, are LAN-switches.
A switch looks at the Ethernet frame and sends it only out on the ports with which the
communicating equipment is connected. Switches should send any traffic for which they
don’t know where to send it all the ports but it seems that some manufactures assume
that the only packet traffic is IP. They just drop packets when they don’t know where
to send them to.
Communication on a local LAN in the IP world starts with an ARP request. That is
a ‘search for the MAC address’ of a given IP address. The ARP request is sent to the
broadcast MAC address FF:FF:FF:FF:FF:FF. The IP host owning the IP address replies
with its own MAC address. By looking at the ARP requests and replies, the LAN switches
can learn where the hosts in the network are connected and to which ports send the
packets.
In our case, we don’t use IP addresses. Everything is based on Ethernet and MAC
addresses, but to be able to work with those broken LAN switches (or optimized LAN
switches as the manufacturer would probably call them) we need to let the LAN switch
know what the MAC address of the Ethernet board is before sending the actual traffic.
This is called gratuitous ARP request. This is a spontaneous ARP request and we fill in
some dummy IP address (never used) just to teach the switch what our MAC address is.
The gratuitous ARP is sent at the startup of the board as soon as the link comes up.
748ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

While working with the Ethernet real-time communication software, we also learned
something about WI-FI routers. We always thought that they are just switches inside
the LAN and the routing function comes only in place while sending data to the Internet.
This is not the case at least for our Netgear WI-FI router. It does not switch any traffic
between wired LAN and WI-FI LAN unless those are Ethernet frames containing the
IP traffic. In other words, plain Ethernet communication does not work over WI-FI
networks of this kind. It works only over hubs and LAN switches.

17.10.1 Packet Format

Here we use 3 bytes of data. The actual Ethernet frames are much longer, but the extra
dummy data added automatically by the Ethernet chip is 802.3 compliant and we don’t
have to worry about it.

17.11 IDEA OF A WEB CLIENT

We have seen that a web server makes really sense for displaying data from a
microcontroller. A web page is a great user interface and can be a machine interface at
the same time. Why would we need a web browser inside a microcontroller? The problem
is that most web pages are huge, hundreds of kilobytes each. What do we do with all
those bytes in a chip that has only 1 KB to store the data? Web browsers can also be
used to upload data. You notice this when you go on shopping on the Internet and enter
you address or you use Google to search.
The plan is to use the Ethernet board to upload measurement data and other information
onto a web server. The response from the web server where we upload would then mainly
be ignored. We could read a status code indicating success or failure, and we could read
data or other small pieces of information, but the bulk of the resulting web page would
be discarded.
This idea is especially convenient when you have multiple distributed sensors. Just
plug them into any DSL router and they could report measurement data once a day.
Microcontrollers have inbuilt timers/clocks. To program them to upload data once every
hour or once every day is very easy.

17.11.1 A Simple Web Client in Linux

Linux provides a high-level socket API that will allow a programmer to easily connect to
any TCP or UDP service. We will see how this works by implementing a simple HTTP
client which will request a web page given the hostname and the page name, then read
the server answer and output the HTML content of the reply.
To be able to connect to a service built on top of the TCP, we first need to create a socket
for the TCP protocol, fill in a network address structure representing our destination and
the port to connect to and use the latter to connect to the remote server. From there, we
will be able to send and receive data over the network.
Once we are done, we will close the connection.
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ749

17.11.2 How Web Browsers Work

We should study how web browsers work before we go into the implementation details
of a microcontroller embedded web browser. It is very easy to understand and test by
using telnet. Try this. Open a telnet session to www.ietf.org (where all the internet standards
are) on port 80 and then type:
GET / HTTP/1.0
Host: www.itef.org User-Agent: tgr/1.0

Accept: text/html
After this hit twice return. What happens is this:
telnet www.itef.org 80 Trying 63.119.44.197...
Connected to www.itef.org. Escape character is ‘^]’.
GET / HTTP/1.0
Host: www.itef.org
User-Agent: testing/1.0
Accept: text/html

HTTP/1.1 200 OK
Date: Wed, 29 Apr 2009 11:53:54 GMT
Server: Apache/2.2.3 (CentOS)
Set-Cookie: COOKIE=10.5.16.253.1241006034372969; path=/
ETag: “AAAASDUwzCY”
Last-Modified: Thu, 23 Apr 2009 20:55:43 GMT
Vary: Accept-Encoding,User-Agent
.... the web page continued....
By using telnet on port 80 we connect to the web server. We tell it that we want the root
page GET /. A web server might host many sites. Therefore we need to specify to which
site hosted on that server we would like to get. This is the Host: www.itef.org line.
In User-Agent: we specify what kind of web browser we are using and after that which
data formats we can accept. The web server then responds to our request after the empty
line.
The data should be in a URL encoded format similar to the GET data but in a different
place in the packet. One thing to watch out for is that the packet buffer is only about 500
bytes, so with headers, you can POST a lot of data to Arduino. Once you exceed the buffer,
strange things start happening or it just stops working!

17.11.3 Security Aspects

A tiny embedded web server actually out-performs many other web servers. Even an
Apache server on a small PC will have trouble to keep up with it when it comes to
number of users and speed. This embedded web server does not have hard limit on the
number of parallel users and it can serve hundreds of web pages per second. There is
750ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

no other embedded TCP/IP stack that can do this. This performance comes at a cost. It
can only serve small web pages and it does not do much validation of the received IP
packets. It is therefore recommended to use always a firewall as provided by most home
DSL routers. If you want even more control, especially if you want to log every request
to file, then you can use the proxy-cgi.

17.11.4 Access From Anywhere in the World

The embedded web server, with the possibility to control hardware and read sensors,
can be accessed remotely over the Internet. To do this, you will need a DSL router with
port forwarding. Most DSL routers can do that. To know where your system is you will
either need a static IP address or a DSL router. With ipconfig/all command you can see
what your current IP is in your PC connected to the Internet. You can use this during
the initial testing while you do not yet have a static IP account.

17.12 DHCP SERVER

Dynamic Host Configuration Protocol (DHCP) is a network protocol that enables a server
to automatically assign an IP address to a computer from a defined range of numbers (i.e.,
a scope) configured for a given network. DHCP assigns an IP address when a system is
started, for example:
1. A user turns on a computer with a DHCP client.
2. The client computer sends a broadcast request (called a DISCOVER or
DHCPDISCOVER), looking for a DHCP server to answer.
3. The router directs the DISCOVER packet to the correct DHCP server.
4. The server receives the DISCOVER packet. Based on availability and usage policies
set on the server, the server determines an appropriate address (if any) to give to
the client. Then it temporarily reserves that address for the client and sends back
to the client an OFFER (or DHCPOFFER) packet, with that address information. It
also configures the client’s DNS servers, WINS servers, NTP servers, and sometimes
other services as well.
5. The client sends a REQUEST (or DHCPREQUEST) packet, letting the server know
that it intends to use the address.
6. The server sends an ACK (or DHCPACK) packet, confirming that the client has been
given a lease on the address for a server-specified period of time.
When a computer uses a static IP address, it means that the computer is manually
configured to use a specific IP address. One problem with static assignment, which can
result from user error or inattention to detail, occurs when two computers are configured
with the same IP address. This creates a conflict that results in loss of service. Using
DHCP to dynamically assign IP addresses minimizes these conflicts.

17.13 ADDRESS RESOLUTION PROTOCOL

Address Resolution Protocol (ARP) is a protocol used by the Internet Protocol (IP)
[RFC826], specifically IPv4, to map IP network addresses to the hardware addresses
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ751

used by a data link protocol. The protocol operates below the network layer as a part
of the interface between the OSI network and OSI link layer. It is used when IPv4 is
used over Ethernet. The term address resolution refers to the process of finding an
address of a computer in a network. The address is ‘resolved’ using a protocol in which
a piece of information is sent by a client process executing on the local computer to a
server process executing on a remote computer. The information received by the server
allows the server to uniquely identify the network system for which the address was
required and therefore to provide the required address. The address resolution procedure
is completed when the client receives a response from the server containing the required
address.
An Ethernet network uses two hardware addresses which identify the source and
destination of each frame sent by the Ethernet. The destination address (all 1’s) may
also identify a broadcast packet (to be sent to all connected computers). The hardware
address is also known as the Medium Access Control (MAC) address, in reference to
the standards which define Ethernet. Each computer network interface card is allocated
a globally unique 6-byte link address when the factory manufactures the card (stored
in a PROM). This is the normal link source address used by an interface. A computer
sends all packets which it creates with its own hardware source link address, and receives
all packets which match the same hardware address in the destination field or one (or
more) pre-selected broadcast/multicast addresses.
The Ethernet address is a link layer address and is dependent on the interface card
which is used. IP operates at the network layer and is not concerned with the link
addresses of individual nodes which are to be used. The address resolution protocol
(ARP) is therefore used to translate between the two types of address. The ARP client
and server processes operate on all computers using IP over Ethernet. The processes are
normally implemented as part of the software driver that drives the network interface
card.
There are four types of ARP messages that may be sent by the ARP protocol. These are
identified by four values in the ‘operation’ field of an ARP message. The types of message
are:
1. ARP request
2. ARP reply
3. RARP request
4. RARP reply
The format of an ARP message is shown below:

Format of an ARP message used to resolve the remote MAC Hardware


Address (HA)

To reduce the number of address resolution requests, a client normally ‘caches’ resolved
addresses for a (short) period of time. The ARP cache is of a finite size, and would
become full of incomplete and obsolete entries for computers that are not in use if it
was allowed to grow without check. The ARP cache is therefore periodically flushed of
all entries. This deletes unused entries and frees space in the cache. It also removes any
unsuccessful attempts to contact computers which are not currently running.
752ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

If a host changes the MAC address which it uses, this can be detected by other hosts
when the cache entry is deleted and a fresh ARP message is sent to establish the new
association. The use of gratuitous ARP (e.g., triggered when the new NIC interface is
enabled with an IP address) provides a more rapid update of this information.
Example of use of the Address Resolution Protocol (ARP): The figure below shows
the use of ARP when a computer tries to contact a remote computer on the same LAN
(known as ‘sysa’) using the ‘ping’ program. It is assumed that no previous IP datagrams
have been received from this computer, and therefore the ARP must first be used to
identify the MAC address of the remote computer.
The ARP request message (‘who is X.X.X.X tell Y.Y.Y.Y’, where X.X.X.X and Y.Y.Y.Y
are IP addresses) is sent using the Ethernet broadcast address, and an Ethernet protocol
type of value 0x806. Since it is broadcast, it is received by all systems in the same collision
domain (LAN). This ensures that if the target of the query is connected to the network,
it will receive a copy of the query. Only this system responds. The other systems discard
the packet silently. The target system forms an ARP response (‘X.X.X.X is hh:hh:hh:hh:hh:hh’,
where hh:hh:hh:hh:hh:hh is the Ethernet source address of the computer with the IP
address of X.X.X.X). This packet is unicast to the address of the computer sending the
query (in this case Y.Y.Y.Y). Since the original request also included the hardware address
(Ethernet source address) of the requesting computer, this is already known, and it
doesn’t require another ARP message to find this out.
17.13.1 Gratuitous ARP
Gratuitous ARP is used when a node (end system) has selected an IP address and then
wishes to defend its chosen address on the local area network (i.e., to check no other
node is using the same IP address). It can also be used to force a common view of the
node’s IP address (e.g. after the IP address has changed). Use of this is common when
an interface is first configured, as the node attempts to clear out any stale caches that
might be present on other hosts. The node simply sends an ARP request for itself.
17.13.2 Proxy ARP
Proxy ARP is the name given when a node responds to an ARP request on behalf of
another node. This is commonly used to redirect traffic sent to one IP address to another
system. Proxy ARP can also be used to subvert traffic away from the intended recipient.
By responding instead of the intended recipient, a node can pretend to be a different
node in a network, and therefore force traffic directed to the node is to be redirected to
itself. The node can then view the traffic (e.g., before forwarding this to the originally
intended node) or could modify the traffic. Improper use of Proxy ARP is therefore a
significant security vulnerability and some networks therefore implement systems to
detect this. Gratuitous ARP can also help defend the correct IP to MAC bindings.

17.14 C PROGRAM PRACTICE


Please refer www.tuxgraphics.org/electonics/201008/10-web-server.shtml for the server
and hardware details of a WEB-DAC. The above-mentioned server simply creates
firmware code of web-programmable 12-bit digital outputs. The hardware can use
additional DAC chip (12-bit) at the output of 74hc595 to produce 0 to 5 volts dc.
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ753

17.15 WORKING OF THE PROJECT PROGRAMS OF WEB-DAC


17.15.1 Bit Change
In this program, we connect to a embedded system that has an IP address 10.0.0.70.
The main part of the program is to control the voltage output of the embedded system
through an Ethernet connection. The system by default has 12 bits of switches namely,
e0, e1, e2, e3, e4, e5, e6, e7, s0, s1, s2, s3 that control the voltage output. These 12 bits
can take either one the two states 0 or 1. We first send a query to the server demanding
the HTML content. By doing this we can get the actual status of each bit. Now we
program in such a way to get the input from the user to change the bit value. For
example, we can switch the bit s3 ON or OFF by giving s3-1 or s3-0. The voltage change
can be seen through the multi-meter connected to the system with IP 10.0.0.70. The
system can generate 0 to 5 volts (decimal 0-4095 programable).
17.15.2 Voltage Change
The program is modified in such a way as to get the required voltage from the user
directly instead of using the bits.
Figure 17.9 shows the html content of the WEB-DAC server.

Figure 17.9
754ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

17.15.3 Generation of the Sine Wave Over Web: An Example


The following piece of client code (Fig. 17.10) is used to get a sine wave at the server
level that originates from 0 degrees and goes to 180 degrees to complete the half wave,
that is, it falls back to zero. From here it travels another 180 degrees to come back to zero.

Figure 17.10

The Fig. 17.11 illustrates the sine wave generated at server remotely.

Figure 17.11
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ755

17.15.4 A Sensor Server Using 32-Bit ARM MBED 1768 Microcontroller

RPC (remote procedure call) over http allows to code commands like “http://myipno/
rpc/temperature” at the server which can return present temperature to a browser, using
a T-sensor which is connected to ARM MBED microcontroller.
The client program gets the value of the required string from the server and stores it
continuously. (see Figs. 17.12 & 17.13).

17.15.5 Pressure Server

This server picks five different pressure values from the sensors and displays in the TFT
display that is connected to the embedded system. The main part is the development
of a user interface for the pressure server (Fig. 17.14). A Qt tool is used to develop the
user interface for this system (Fig. 17.15).

Figure 17.12 The server system

Figure 17.13 rpc over HTTP


756ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 17.14 Pressure server working

Figure 17.15 The TFT display values are integrated into GUI

The below program is for the main window of Qt to work as pressure-client (see Fig.
17.15) for the server shown in Fig. 17.14 (digital display).
#include “mainwindow.h”
#include “ui_mainwindow.h”
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ757

#include <QMessageBox>
#include <QCheckBox>
QString sd;
int i;

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(timerupdate()));

timer->start(100);
nam = new QNetworkAccessManager(this);
//connect(ui->GetIpButton,SIGNAL(clicked()),this,SLOT(DoHtt
pGet()));
connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(
QNet
workReply*)));

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::finished(QNetworkReply *reply)


{

if(i==1)
{
if(reply->error() == QNetworkReply::NoError)
{
ui->Pressure1_Text->setText(reply->readAll());
}
}
if(i==2)
758ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

{
if(reply->error() == QNetworkReply::NoError)
{
ui->Pressure2_Text->setText(reply->readAll());
}
}
if(i==3)
{
if(reply->error() == QNetworkReply::NoError)
{
ui->Pressure3_Text->setText(reply->readAll());
}
}
if(i==4)
{
if(reply->error() == QNetworkReply::NoError)
{
ui->Pressure4_Text->setText(reply->readAll());
}
}
if(i==5)
{
if(reply->error() == QNetworkReply::NoError)
{
ui->Pressure5_Text->setText(reply->readAll());
}
}

void MainWindow::timerupdate()
{
// dummyread(nam);
// QMessageBox msg;
// msg.setText(“Hello”);
// msg.exec();

DoHttpGet();

}
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ759

void MainWindow::DoHttpGet()
{

i++;
QString u = ui->Ip_Text->text();

if(i == 1)
{
sd = “pressure1_psi”;
}
if(i == 2)
{
sd = “pressure2_psi”;
}
if(i == 3)
{
sd = “pressure3_psi”;
}
if(i == 4)
{
sd = “pressure4_psi”;
}
if(i == 5)
{
sd = “pressure5_psi”;
}
QString url = “http://”+u+”/rpc/”+sd+”/read”;
nam->get(QNetworkRequest(QUrl(url)));

if (i==6) i=0;

}
The DoHttpGet() function is used to generate the URL so that it can be utilized by the
QNetworkRequest() to get the URL from the embedded system holding the pressure
values. The timerupdate() function includes the DoHttpGet() so that the pressure
values are refreshed every few microseconds and thus any major deviation in the pressure
values can be easily noticed. Both the TFT and the GUI are programmed to refresh
frequently for this purpose.
760ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 17.16 The microprocessor pin diagram

17.16 DESIGNING 8-BIT ETHERNET INTERFACES USING ATMEL


PROCESSORS
Objective of the project: An AVR microcontroller based Ethernet device.

17.16.1 Introduction to the ENC28J60 Ethernet Controller


The ENC28J60 from Microchip is a fantastic chip. It has Tx/Rx, MAC and PHY in one
small chip. There are very few external parts. It is just a crystal and an Ethernet
transformer, aka magnetics. All of this comes in a convenient 28-pin DIP package.

Figure 17.17
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ761

The main purpose is to show the circuit diagram and explain the software. We use
a UDP application to send commands to the microcontroller. Those commands will then
cause the microcontroller to switch on or off the relay.
It will be possible to even implement TCP. The current UDP software is less than 3
KB and that is not even half of the memory on an Atmega88. TCP would then allow us
to control the device via a web browser.

17.16.2 The Circuit Diagram

Given below is the circuit diagram. It is straightforward and standard for ENC28J60.
The polarity of LED-B is important as it determines the duplex operation of the chip.
Standard half-duplex is what makes most sense for a device which will send and receive
only little traffic.

17.16.3 Application 1: Temperature measurement and


equipment control over the internet.

We attach a digital temperature sensors (Maxim Dallas 1-wire sensors) to the TuxGraphics
Ethernet board and we can use that not only to see the current temperature, but also
to plot temperature graphs with a few days of history. To do this, an embedded web
server is running on the Ethernet board along with drivers for the sensors.

Figure 17.18
762ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

A relay attached to the web server board can be used to remotely activate the heating
or the air conditioning. When we are on the road we can use our mobile phone, iPhone,
Blackberry, etc., to see what is going on into the attached sensor into the room/laboratory.
All of that is done with a tiny web server board based on the Atmega168 or the Atmega328
chip.

eth. board
3V3
Voc
Not all components of the eth. board are shown here.

10K ATMEGA 168/328 U1


R1 1 Rst(PC6)
Optional Second Remote Sensor CONN5 (SCL)PCS 28
3V3 2 PD0 (RXD) (SDA)PC4 27

Vcc
1
3 PD1(TXD) (ADC3)PC3 26
2
10K 3 4 PD2 (INT0)(ADC2)PC2 25
4 5 PD3(INT1) (ADC1)PC1 24
5
First Sensor 6 PD4(T0) (ADC0)PC0 23
6
3V3
3 3 7 8 7 Vcc AGND 22
8 >
2 2 8 GND AREF 21
100nF 1 1 9
9 PB6(XTAL1) AVcc 20
DS18s20 DS18s20 10
10 PB7(XTAL2) (SCK)PB5 19
Vdd
RAWDC 100nF
11 PD5 (MISO)PB4 18
C11
D1 12 PD6(AND) (MOSI)PB3 17
CONN3 BAY69
1 13 PD7(AIN1) (OC1B)PB2 16
2
14 PEO(ICP1) (OC1A)PB1 15
external
relay 1 ATMEGA168
Q1 2
3V3

BC547 D2
RELAY 1K R10
Vcc

or BC548 3
R13 270
(C) GuIdo Socher, tuxgraphics.org
http://tuxgraphics.org/electronics/

Figure 17.19 Connection of relay and DSI8s20 sensors to the tuxgraphics ethernet board

The firmware code of this application can be seen at “www.tuxgraphics.org/electronics/


200906/home-climate-control.shtml”

17.17 BUILDING HTTP SERVER USING ARM MBED LIBRARY

17.17.1 Description of the Library

A working hardware circuit of an embedded web server using ARM MBED 1768 is
shown in Fig. 17.16 on earlier page.

17.17.2 Overview of Server Firmware

This part will explain an HTTPServer library using the new MBED EthernetInterface
library. It allows you to :
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ763

Ȋȱ serve files from any file system


Ȋȱ use remote procedure calls
Ȋȱ extend the HTTPServer functionality according to your needs, using the provided
handler classes or writing new classes. The following sections will give you a brief
overview of how to use the library.

17.17.3 Usage Description

You can use the library as file server, as RPC server or a combination of both. You can
even define your own behaviour by deriving from one of the classes provided.

17.17.4 Use as File Server

You may want to look at my sample application which allows you to serve files from
the internal local storage of the mbed with no modifcation of the code:
A Simple Application
1 #include “mbed.h”
2 #include “HTTPServer.h”
3 #include “FsHandler.h”
4 #include “LocalFileSystem.h”

5 // Use LED1 to indicate that the main loop is still executing


DigitalOut myled(LED1);
6 // Use the serial connection ‘pc’ to dump debug information
Serial pc(USBTX, USBRX, “pc”);
7 // Instantiate a HTTPServer to handle incoming requests
HTTPServer svr;
8 // Instantiate a local file system handler named ‘local’ which
will be used later to access files on the mbed.
9 LocalFileSystem local(“local”);

10 int main() {

11 pc.baud(460800);
12 HTTPFsRequestHandler::mount(“/local/”, “/”);
13 svr.addHandler<HTTPFsRequestHandler>(“/”);

14 if (!svr.start()) {
15 error(“Server not starting !”);
16 exit(0);
17 }
764ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

18 while(1) {
19 svr.poll();
20 myled = 1;
21 wait(0.2);
22 myled = 0;
23 wait(0.2);
24 }
25 }

Another alternative is to provide the EthernetInterface library to the HTTPServer


library. This may be useful in case you need to perform other tasks with your internet
connection. In this case, it is necessary that you initialize the EthernetInterface and
perform the connection prior to calling the start() method. Here is the example:

1 #include “mbed.h”
2 #include “HTTPServer.h”
3 #include “FsHandler.h”
4 #include “LocalFileSystem.h”
5 #include “EthernetInterface.h”

6 // Use LED1 to indicate that the main loop is still executing


DigitalOut myled(LED1);
7 // Use the serial connection ‘pc’ to dump debug information
Serial pc(USBTX, USBRX, “pc”);
8 // Instantiate a HTTPServer to handle incoming requests
HTTPServer svr;
9 ,QVWDQWLDWHDORFDO¿OHV\VWHPKDQGOHUQDPHGµORFDO¶ZKLFK
ZLOOEHXVHGODWHUWRDFFHVV¿OHVRQWKHPEHG
10 LocalFileSystem local(“local”);
11 // Create the EthernetInterface. This is optional, please see
the documentation of HTTP Server’s start method.
12 EthernetInterface eth;

13 int main() {

14 pc.baud(460800);
15 HTTPFsRequestHandler::mount(“/local/”, “/”);
16 svr.addHandler<HTTPFsRequestHandler>(“/”);
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ765

17 // Initialize the EthernetInterface and initiate a connection


using DHCP.
18 eth.init();
19 eth.connect();
20 // ***
21 // TODO: Perform other Tasks using the ethernet connection here.
22 // ****

23 // Now start the server on port 80.


24 if (!svr.start(80, &eth)) {
25 error(“Server not starting !”);
26 exit(0);
27 }

28 // The whole server activity is performed in this Loop.


You can also put it into a separate RTOS Task and let it run
there all the time.
29 while(1) {
30 svr.poll();
31 myled = 1;
32 wait(0.2);
33 myled = 0;
34 wait(0.2);
35 }
36 }

17.17.5 Use as Remote Procedure Call (RPC) Server

To access objects or resources via HTTP, you can make use of the RPC functionality.
Each object that shall be accessible via HTTP needs to be registered before use. Here is
an example which registers the DigitalOut class for use over RPC:
#include “mbed.h”
#include “HTTPServer.h”
#include “RpcHandler.h”
#include “mbed_rpc.h”

// Use LED1 to indicate that the main loop is still executing


DigitalOut myled(LED1);
// Use the serial connection ‘pc’ to dump debug information
Serial pc(USBTX, USBRX, “pc”);
// Instantiate a HTTPServer to handle incoming requests
HTTPServer svr;
766ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

int main() {

pc.baud(460800);
RPC::add_rpc_class<RpcDigitalOut>();
svr.addHandler<HTTPRpcRequestHandler>(“/RPC”);

if (!svr.start()) {
error(“Server not starting !”);
exit(0);
}

while(1) {
svr.poll();
myled = 1;
wait(0.2);
myled = 0;
wait(0.2);
}
}
http://<your_mbed_ip>/RPC/myled4/write 1 - - > to switch on the LED4.
Of course it is possible to register your own objects with the standard MBED RPC
functionality.

17.17.6 A Reliable MBED Web Server

Building a reliable embedded web server for an MBED device or other is difficult.
The usual issues with a server are:
1. Handling multiple concurrent requests.
2. Intermittent failure when opening and closing sockets.
3. Handling the limitation of a 1024 byte HTTP buffer and aborted connections
reported by the browser.
Clearly some things will never be possible with a server, for example:
ȱ Ȋȱ ‘Žȱ œ™ŽŽȱ ˜ȱ ŠŒŒŽœœȱ ˜ȱ ŠŠȱ ˜—ȱ Š—ȱ ȱ ŒŠ›ȱ –ŽŠ—œȱ ‘Šȱ ‘Žȱ œŽ›ŸŽ›ȱ ’••ȱ —ŽŸŽ›ȱ ‹Žȱ
very fast at serving files and there is very little RAM memory available on most
MBED hardware, so caching won’t be a solution to this.
However beyond stability, which will determine whether a web server is good, one
thing is how fast a request (e.g., POST) can be handled and how much data can be
transferred in a single request.
To achieve this and to transfer around 5k of data per “frame” of animation (say, there
are around 1700 LEDS and each has an RGB value). But the MBED has limited RAM
and I think I will only be able to send around 1K per REST request so that means 5
packets per “frame”. If one wants a “frame-rate” of say 20 per second one would need
to transfer around 100 x 1 Kbyte packets per second.
Ž ˜›”’—ȱ Šœ’Œœȱ Š—ȱ ŞȦřŘȬ‹’ȱ ’Œ›˜Œ˜—›˜••Ž›Ȭ‹ŠœŽȱ ‘Ž›—Žȱ ȱ Ž›ŸŽ›Ȭ•’Ž—ȱ —Ž›ŠŒ’—ȳ767

17.17.7 A Reliable TCP Connection

Create an echo server like below:


#include “mbed.h”
#include “EthernetInterface.h”
GH¿QH(&+2B6(59(5B3257
int main (void)
{
EthernetInterface eth;
eth.init(); //Use DHCP
eth.connect();
printf(“\nServer IP Address is %s\r\n”, eth.getIPAddress());
// TCP Socket server
TCPSocketServer server;
server.bind(ECHO_SERVER_PORT);
server.listen();
while (true)
{
printf(“Wait for new connection...\r\n”);
TCPSocketConnection client;
server.accept(client);
client.set_blocking(false, 1500); // Timeout after (1.5)s
printf(“Connection from: %s\r\n”, client.get_address());
FKDUEX๱HU>@
while (true)
{
LQWQ FOLHQWUHFHLYH EX๱HUVL]HRI EX๱HU 
if (n &lt;= 0) break;
EX๱HU>Q@ ½?¾
VHQGBDOO EX๱HUQ (FKREDFN
if (n &lt;= 0) break;
}
client.close();
}
}

REFERENCES

http://tuxgraphics.org/electronics/
http://www.fz-juelich.de/portal/home
http://www.halo.dlr.de/
768ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

REVIEW QUESTIONS

1. Why do we need Qt for web-enabled applications?


2. Difference between TCP and UDP?
3. Write short note on:
ȱ ȱ ǻ’ǼȲ 
ȱ ȱ ǻ’’ǼȲ–‹ŽŽȱŽ‹ȱŽ›ŸŽ›
ȱ ȱ ǻ’’’ǼȲ
ȱ ȱ ǻ’ŸǼȲ

ANSWERS

1. Qt is an open source, OS-independent IDE, useful for web-enabled applications


as it supports networking-libraries.
2. TCP is a connection protocol whereas UDP is a connectionless protocol.
3. (i) http stands for hypertext transfer protocol, invented by Tim Berners Lee of
CERN laboratories.
(ii) http servers when deployed in microprocessors/microcontrollers/FPGA, then
they are embedded web servers.
(iii) Uniform resource locator (URL) is a specific character string that is used to
access data from the world wide web.
(iv) Media access control address. A MAC address is given to a network adapter
at the time of manufacturing. It is unique. It is also known as physical address.
For example: 00:0a:95:9d:68:16.
CONTROLLER-AREA NETWORK (CAN)
18

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Basics of CAN and its microcontroller-based implementations using ARM mbed.
Ȋȱ Comparison of Ethernet with CAN.

18.1 INTRODUCTION

Controller-area Network (CAN) is a serial bus system designed to allow microcontrollers


and devices to communicate with each other without a host computer. Transceivers are
essentially required for the use of CAN. Transceivers change the digital signal (RD/TD),
output by the microprocessors into a differential signal, which is transmitted along the
CAN bus to the other nodes, and resistors are used at both the ends of the bus. CAN
is based on the ‘broadcast communication mechanism’, which is based on a message-
oriented transmission protocol. It defines message contents. CAN cable connects wired
devices together to the local network. This chapter will explore the design features of
a PC board which has been designed to multi-drop several 0-10 V generators over CAN
along with its readbacks over Ethernet.
CAN, by itself, is not necessarily a complete network system. It consists of only the
physical layer (the two wires), the priority scheme (highest priority message always gets
through first) and some error detection and handling circuitry. This allows simple
messages of zero to eight bytes to be passed on the system. CAN, like most modern
networks, is serial based. This means that the information travels along the network one
bit at a time. CAN network needs one to two lines depending on the design. Parallel
networks usually require more than 8 wires plus several handshaking lines to facilitate
the data transfer. Most network systems using CAN will employ a higher level protocol
such J1939, CANopen or a proprietary scheme to create and process messages over the
basic CAN network.
CAN is a network protocol which allows multiple nodes in a system to communicate
efficiently with each other. It is a serial communication bus for real-time applications
and operates at a data rate of 1 Mb/s. CAN is event-triggered and not time-triggered
and is more suitable for a periodic communication. Communication through CAN is
very reliable and robust, thus is used in noisy environments. CAN is widely used for
770ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

automotive applications to replace the complex wiring problems. Nowadays, CAN bus
is used in in car electronics, aerospace, ships, medical electronics and also in textile
machinery. We are implementing a RS232 based CAN bus network analyzer, based on
ARM7 using the acceptance filter concept.
The LPC2129 microcontroller has two interconnected CAN interfaces with advanced
acceptance filters. By using LPC2129 microcontroller, we receive the data CAN bus,
convert the data in serial format and transfer the data to a PC or laptop using RS232
serial port or virtual serial port. The CAN transceiver MCP2551 is a high-speed CAN,
fault-tolerant device that serves as the interface between a CAN protocol controller and
the physical bus. MCP2551 provides differential transmit and receive capability for the
CAN protocol controller and is fully compatible with the ISO11898 standard. The CAN
bus analyzer is a simple to use low cost CAN bus monitor which can be used to develop
and debug a high-speed CAN network. The device supports CAN 2.0b and ISO11898-2
and a broad range of functions which allow it to be used across various market segments
including automotive, industrial, medical and marine.

18.1.1 History of CAN

Robert Bosch introduced CAN to be used in automotive applications in order to reduce


the complex wiring problems inside passenger cars. Most of the cars which have been
manufactured since the 1980s use CAN as a standard for in-vehicle communication.
CAN is documented as an international standard as ISO11898 for high-speed applications
and ISO11519 for low-speed applications. To discuss the growth of CAN, several user
groups have been formed. One of the first is CAN in Automation (CiA). Now in its 20th
year, CAN is still enhanced. In the future, CAN would be used in every type of embedded
systems and machines.
The reasons for the vehicle manufactures using the CAN bus are:
(a) Significant reduction in wiring leading to:
(1) significant reduction in manufacturing cost and hence retail cost, and
(2) reduction in weight resulting in an improved fuel consumption.
(b) Reduced number of interconnections improve reliability. It is easy to identify the
wiring as it is just a twisted pair of thin wires. This is found all over the vehicle
– sometimes in with a conventional main loom. The wires are called ‘CAN High’
and ‘CAN Low’ and it is important that an interface is connected correctly to
these wires.
Controller-area network (CAN or CAN-bus) is a vehicle bus standard designed to allow
microcontrollers and devices to communicate with each other within a vehicle without
a host computer.

18.1.2 How Does CAN Work

Architecture: CAN is a multi-master serial bus standard for connecting electronic control
units (ECUs) also known as nodes. Two or more nodes are required on the CAN network
to communicate. The complexity of the node can range from a simple I/O device up to
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ771

an embedded computer with a CAN interface and sophisticated software. The node
may also be a gateway allowing a standard computer to communicate over a USB or
Ethernet port to the devices on a CAN network.
The CAN communication protocol ISO11898:2003 explains how information is passed
between devices on a network. CAN follows the OSI model that is defined in terms of
different layers. CAN uses only physical and data link layer of the OSI model as shown
below. The physical layer of the CAN and OSI model explains the actual communication
between the devices connected. Two nodes are connected to each other via a physical
wired connection. The ISO11898 architecture defines the lowest two layers of the seven-
layer OSI/ISO model as the data-link layer and physical layer in the figures below. Figure
18.1 shows which all layers of OSI are used in CAN and which all are not used, and
Fig. 18.2 shows the usage of DLL and physical layer in CAN in detail.

Application Layer: Not used in CAN


Presentation Layer: Not used in CAN
Session Layer: Not used in CAN
Transport Layer: Not used in CAN
Network Layer: Not used in CAN
Data Link Layer: LLC and MAC
Physical Layer: PLC, PMA and MDI
Figure 18.1

Figure 18.2

18.2 CAN BUS NODE

Each node requires a:


Central processing unit, microprocessor, or host processor: The host processor decides
what the received messages mean and what messages it wants to transmit. Sensors,
actuators and control devices can be connected to the host processor.
772ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

CAN Controller MCP2510: Microchip Technology’s MCP2510 is a stand-alone CAN


controller that implements the CAN specification, version 2.0B. It is capable of transmitting
and receiving both standards and extended data and remote frames. The MCP2510 has
two acceptance masks and six acceptance filters that are used to filter out unwanted
messages, thereby reducing the host MCUs overhead. The MCP2510 interfaces with
microcontrollers (MCUs) via an industry-standard serial peripheral interface (SPI).
CAN Transceiver (MCP2551): The MCP2551 is a high-speed CAN, fault-tolerant device
that serves as the interface between a CAN protocol controller and the physical bus.
The MCP2551 provides differential transmit and receive capability for the CAN protocol
controller and is fully compatible with the ISO11898 standard, including 24 V
requirements.

Figure 18.3
18.2.1 Operation of CAN

CAN is a bit stream oriented communication protocol through which the complete
transmission of message is carried stand alone by the CAN controller. CAN is a broadcast
communication system in which the message frames which are transmitted on the bus
do not have any source or destination addresses. Instead, the frames have identifiers
with which the nodes which receive the messages can run an acceptance test (filtering)
to make sure whether to accept the corresponding message or to ignore it. The identifier
has information about the content of data inside the frame and also the priority of the
message. Higher the priority, lower the number. The length of the identifier is normally
11 bits (standard CAN) and the second generation CAN have an identifier of 29 bits
(extended CAN).
It is easy to add stations to an existing CAN network without making any hardware
or software modifications to the present stations as long as the new stations are purely
receivers. This allows for a modular concept and also permits the reception of multiple
data and the synchronization of distributed processes. Also, data transmission is not
based on the availability of specific types of stations, which allows simple servicing and
upgrading of the network.
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ773

Figure 18.4 Sends the counter from CAN 1 and Listens from CAN

Figure 18.5 Example showing the working of CAN

18.2.2 Bus Arbitration

CAN uses Carrier-Sense Multiple Access with Collision Avoidance (CSMA/CA) for the
bus to access. Every node in the network can access the bus when the bus is free for a
3-bit period. In the case of collision, the message with a higher priority wins the bus
access and transmits. If more than one node tries to send data through the bus, then
the bus access is decided by a bit-wise arbitration. The nodes which need to send the
message transmits the message bits at the same time. The node which sends a dominant
(0) bit will gain access on the bus there on. The other node which sends a recessive (1)
bit changes its state to a receiver and starts receiving the message frame which is on
the bus. The transmission of a lower priority message is stalled and transmitted again
automatically when the bus is free. The message contains 0-8 bytes of data which is
specified as Data Length Code (DLC) in the control bits of the message frame. For the
error detection a 15-bit checksum is transmitted along with the message.
774ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

18.2.3 CAN Bus Description

The controller area network specification defines the data link layer. ISO11898 defines
the physical layer. A number of different data rates are defined, with 1 Mbps being the
top end, and 10 Kbps the minimum rate. All modules must support 20 Kbps. The cable
length depends on the data rates used. The maximum line length is 1 km, 40 meters at
1 Mbps. Termination resistors are used at each end of the cable. The worst-case
transmission time of an 8-byte frame with an 11-bit identifier is 134 bitimes.
The CAN bus interface uses an asynchronous transmission scheme controlled by start
and stop bits at the beginning and end of each character. This interface is used, employing
serial binary interchange. The data frame is composed of an arbitration field, control
field, data field, and CRC feedback field. The frame begins with a ‘Start of frame (SOF)’,
and ends with an ‘End of frame (EOF)’.
The receiving node synchronizes itself with every start bit of the message. CAN uses
a technique called bit stuffing for proper communication of the messages. After every
consecutive bit levels, the transmitter will automatically stuff a bit of opposite polarity
into the bit stream. The receiver of the message will automatically destuff (delete)
this stuff bit. So, if any receiving node detects six consecutive bits of the same level,
then a stuff error is flagged. Theoretically, for every 5 bits, a stuff bit is sent by the
sender. On an average, every message has 3 to 4 stuff bits.
The nominal bit timing is the time needed to transmit a bit across the network. All
the nodes in the network should have the same bit rate. That is why synchronization
is done in several ways. Maximum transmission time for a message with 8 data bytes
and of a higher priority is 225 micro-seconds. And with 29 bit identifier, it is 260 micro-
seconds. Therefore, the maximum data rate is 35 KBps for an 11-bit identifier and 30
KBps for a 29-bit identifier.
The CAN bus analyzer tool is a simple to use low-cost CAN bus monitor which can
be used to develop and debug a high-speed CAN network. The tool supports CAN 2.0b
and ISO11898-2 and a broad range of functions which allow it to be used across various
market segments including automotive, industrial, medical and marine. The toolkit
comes with all the hardware and software required to connect a CAN network to a PC.
The GUI makes it easy to quickly observe and interpret bus traffic.
CAN was developed for the automotive market to reduce the weight and cost of
wiring harnesses and add additional capabilities. It is also used in factory automation,
medical, marine, military and wherever a simple yet robust network is needed.
CAN Analyzer is an RS232 to CAN PC based port adapter to monitor, and it analyzes
the CAN bus data on a CAN network. This universal CAN tool can be used in
development, production, quality control, service department prototype build shops and
other areas. Next to the targeted automotive application field, this tool provides a
powerful test tool for all fields and areas of CAN networks. Diagnostic functionality for
on-line and off-line states is implemented. The main component of the CAN Analyzer
is a central communication server, which acts as an interface between the CAN bus
(CAN board) and the analysis modules. The actual analysis functions are provided by
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ775

separate function modules, which can be connected to the communication server in any
combination. In addition to the modules, specific modules created by the user can also
be used. Due to the open programming interface of the CAN Analyzer, customized
functionalities in the form of individual modules can easily be integrated. This unique
concept guarantees almost unlimited extendibility.

RS232
LPC2129 to USB
Converter

MCP2551

SG SG SG
1 2 3
CHH
120W

120W

CAN BUS

CHH
Figure 18.6 Block diagram of CAN bus

18.2.4 CAN Bus Cabling

CAN is a two-wire differential serial communication protocol for real-time control.


CANopen amplifiers use the CAN physical layer as defined by the DS-102 V2.0 and the
cabling and connector pin assignments as defined by DR-303 V1.0. To quote a senior
applications engineer, “Network problems are often caused by not using proper
termination at both ends of the CAN bus, wrong bit rates for cable lengths, and poor
cabling. This technical note will help make efficient use of network bandwidth and
achieve an error-free operation.”
Physical medium (bus line): The bus line must be terminated at both the ends by
resistors that represent the characteristic impedance of the line. Copley supplies standard
’ŠȬ‹’ȱ ȱ ǻ—œ‘’Ž•Žȱ  ’œŽȱ Š’›Ǽȱ ŒŠ‹•Žȱ ’‘ȱ œŠ—Š›ȱ ŗŘŗȱ ̛ȱ Œ‘Š›ŠŒŽ›’œ’Œȱ
’–™ŽŠ—ŒŽǯȱ ‘žœǰȱ ŗŘŗȱ ̛ȱ ›Žœ’œ˜›œȱ –žœȱ ‹Žȱ ’—œŠ••Žȱ Šȱ ‹˜‘ȱ ‘Žȱ Ž—œȱ ˜ȱ ‘Žȱ —Ž ˜›”ǯȱ
Copley provides termination plugs for RJ-45 connectors and a jumper for development
kits. Most manufacturers do not ship CAN cards with termination installed. Thus, for
the CAN card at the end of the bus line, line termination must be installed.
776ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The maximum CAN bus length is 1 kilometer at 50 Kbps. The bus line should be as
close as possible to a straight line to keep reflections to a minimum. To extend the cable
length (or to provide galvanic isolation) a bridge-device or the repeater can be used.
The diagram below represents a typical network implementation. However, it is not the
only one. It is also possible to have the master connected in the middle with no
termination, with termination at the amplifiers at the end of the bus line. If a cable stub
(unterminated cable) or T-connector is used to tap into the bus line, then the stub distance
should not exceed 0.3 m at 1 Mbps rate as per DS 102 Version 2.0.

Can Bus Length


Can Card Can Open Amps
Can Cable

Master

S L A V E

Terminate Both Ends


121

Figure 18.7

18.2.5 CAN with Ethernet Backbone

The term backbone has a different meaning in each of the two environments in which
it is used. Within the structured cabling environment, the term backbone refers to the
cable used to connect a main or intermediate cross-connect to a telecommunications
closet. It also refers to the cable used to connect the main cross-connect to the intermediate
cross-connect. Therefore, in this context, the term backbone refers to a physical portion
of the structured cabling system.
In networking environments, a backbone, or more specifically, a backbone network
refers to connection services provided to multiple individual LANs. In this mode, a
backbone may be defined as, “a backbone is a means of connecting two or more LANs.
It provides a transmission channel for packets being transmitted from one LAN to
another. After connection to a backbone, a LAN may remain distinct or be merged with
another.”
Ethernet: Ethernet is the most widely-installed local area network (LAN) technology.
Specified in the standard, IEEE 802.3, Ethernet was originally developed by Xerox from
an earlier specification called Alohanet (for Palo Alto Research Center Aloha Network)
and then developed further by Xerox, DEC, and Intel. An Ethernet LAN typically uses
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ777

a coaxial cable or special grades of twisted pair wires. Ethernet is also used in wireless
LANs. The most commonly installed Ethernet systems are called 10BASE-T and these
provide transmission speeds up to 10 Mbps. Devices are connected to the cable and
compete for access using a Carrier Sense Multiple Access with Collision Detection
(CSMA/CD) protocol.
Fast Protocol or 100BASE-T provides transmission speeds up to 100 Mbps and is
typically used for LAN backbone systems, supporting workstations with 10BASE-T
cards. Gigabit Ethernet provides an even higher level of backbone support at 1000 Mbps
(1 gigabit or 1 billion bits per second). 10-gigabit Ethernet provides up to 10 billion bits
per second.
Ethernet was named by Robert Metcalfe, one of its developers, for the passive substance
called ‘luminiferous (light-transmitting) ether’ that was once thought to pervade the
universe, carrying light throughout. Ethernet was so-named to describe the way that
cabling, also a passive medium, could similarly carry data everywhere throughout the
network.
Ethernet as Network Backbone: A network backbone interconnects various sub-networks
with different protocols and/or operating speeds. With a 1500-byte payload limit and
speeds up to 100 Mbps, Ethernet is suitable to aggregate multiple messages in a single
packet. You can aggregate multiple CAN messages from a subnet sent across gateways
in a single Ethernet message. As an asynchronous protocol, Ethernet’s sheer speed
overcomes the need for strict timing tolerances. Message buffers reduce timing jitters
and increase latency tolerance.

Figure 18.8 Ethernet backbone topology

Carrier Ethernet is making progress as a backbone transport technology, but there


are challenges that must be addressed. The main issues, including maintaining scalability
in large Ethernet networks, providing QoS to applications, and improving resiliency are
discussed in this tip. The key issues in Ethernet backbone deployment are maintaining
scalability with very large Ethernet networks, providing QoS to applications that need
it, and improving resiliency to ensure that failures in the core do not generate tens of
thousands of customer complaints. As network traffic has evolved from time-division
778ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

multiplexed (TDM) to packet, providers have become more committed to backbone or


‘core’ networks built on packet technology. In the 1990s, the growth of the Internet
created a wave of interest in ‘convergence’ on IP as the universal network technology.
But IP networks have proved costlier than what is expected to operate.
CAN to Ethernet port: The circuit can take 5 analog voltage inputs and can be connected
to CAN and Ethernet simultaneously, depending on the active firmware put. mbed
LPC1768 microcontroller acts as the main MCU.

×
×

---- ----

×
× ×
×

×
×
×
× ×
× ×
×
× ×
×
×
×
×
×
×
×
×
× ×
× ×
×
×
×
×
×
×
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ779

+ + +

+ + +

+ + +

+ + +

Figure 18.9 5 CH analog input via CAN

18.2.6 CAN Benefits

Low-cost, lightweight network: CAN provides an inexpensive, durable network that


helps multiple CAN devices communicate with one another. An advantage of this is
that Electronic Control Units (ECUs) can have a single CAN interface rather than analog
and digital inputs to every device in the system. This decreases overall cost and weight
in automobiles.
Broadcast communication: Each of the devices on the network has a CAN controller
chip and is therefore intelligent. All devices on the network see all transmitted messages.
Each device can decide if a message is relevant or if it should be filtered. This structure
allows modifications to CAN networks with minimal impact. Additional non-transmitting
nodes can be added without modification to the network.
Priority: Every message has a priority; so if two nodes try to send messages simultaneously,
the one with the higher priority gets transmitted and the one with the lower priority
gets postponed. This arbitration is non-destructive and results in non-interrupted
transmission of the highest priority message. This also allows networks to meet
deterministic timing constraints.
Error capabilities: The CAN specification includes a cyclic redundancy code (CRC) to
perform error checking of each frame’s contents. Frames with errors are disregarded
by all nodes, and an error frame can be transmitted to signal the error to the network.
Global and local errors are differentiated by the controller, and if too many errors are
detected, individual nodes can stop transmitting errors or disconnect themselves from
the network completely.
780ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 18.10

18.2.7 CAN Applications

CAN was first created for automotive use (see Fig. 18.11). So its most common application
is in vehicle electronic networking. However, as other industries have realized the
dependability and advantages of CAN over the past 20 years, they have adopted the
bus for a wide variety of applications. Railway applications such as streetcars, trams,
undergrounds, light railways, and long-distance trains incorporate CAN. You can find
CAN on different levels of the multiple networks within these vehicles, for example, in
linking the door units or brake controllers, passenger counting units, and more. CAN
also has applications in aircraft with flight-state sensors, navigation systems, and research
PCs in the cockpit. In addition, you can find CAN buses in many aerospace applications,
ranging from in-flight data analysis to aircraft engine control systems such as fuel
systems, pumps, and linear actuators.

Figure 18.11 CAN in automotive electronics


˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ781

Medical equipment manufacturers use CAN as an embedded network in medical


devices. In fact, some hospitals use CAN to manage complete operating theaters.
Hospitals control operating theater components such as lights, tables, cameras, X-ray
machines, and patient beds with CAN-based systems. Lifts and escalators use embedded
CAN networks, and hospitals use the CANopen protocol to link lift devices, such as
panels, controllers, doors, and light barriers, to each other and control them. CANopen
is also used in nonindustrial applications such as laboratory equipment (Fig. 18.12),
sports cameras, telescopes, automatic doors, and even coffee machines.

Figure 18.12 Use of CAN to measure cryogenic gauges

18.2.8 Distributed vs Central Control

Over the years, CAN, due to its economical implementation combined with an extremely
high level of reliability, has proven and established its dominance as a fieldbus system
for embedded solutions.
Conventional industrial controls, especially PLC, are based on central control, where
a single CPU is responsible to control the application tasks, resulting in high performance
requirements for the CPU. Another downside is the great amount of wiring resulting
in a considerable impact on service and maintenance.
782ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

18.2.9 Advantages and Disadvantages of CAN

CAN, used as fieldbus systems for embedded solutions, combines a number of advantages
that cannot be matched by Ethernet TCP/IP. They are:
Ȋȱ Extreme reliability and robustness
Ȋȱ No message collision
Ȋȱ Very low resource requirements
Ȋȱ Low-cost implementation
Ȋȱ Designed for real-time applications
Ȋȱ Very short error recovery time
Ȋȱ Support of device profiles (CANopen only)
However, there are some disadvantages of using CAN and CANopen, the biggest
being the limited network length (~120 feet at a 1 Mbps baud rate). The disadvantages
are:
Ȋȱ Limited network length (depending on baud rate)
Ȋȱ Limited baud rate of 1 Mbps
Ȋȱ Limited bandwidth
The current excitement about new Ethernet technologies is based on a mere marketing
hype. The matter of fact remains that more than 95% of all industrial control applications
are sufficiently covered by technologies that were established many years ago. It is
nevertheless also the case that these new Ethernet technologies are developing steadily
closer toward the lower price level of conventional components, and “why buy a compact
car when you can get a large hybrid SUV with four-wheel drive and better gas mileage
for nearly the same price?”
While it is true that the costs for Ethernet technologies show a tendency to lower
prices, the statement “nearly the same price” can only be regarded as another marketing
statement. A tough reality check will reveal that the costs are currently several times
higher than those of a conventional system such as CANopen (the estimated factor is
somewhere between 3 and 20). However, the technological advantages of Ethernet based
fieldbus systems, whether needed or not, are compelling, and they contribute to a higher
acceptance level worldwide. The advantages are:
Ȋȱ Speed! (currently 100 Mbps)
Ȋȱ Unlimited network length
Ȋȱ Use of established HW components (RJ-45, switches, hubs, etc.)
Ȋȱ Increased system performance
Note: There is currently no information on how Ethernet based fieldbus technologies
compare with the high level of reliability and robustness as provided by CAN.

18.3 ETHERNET CHALLENGE

There are currently more than 20 different industrial Ethernet solutions available. All
with their distinctive advantages and disadvantages make a pro/con decision for the
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ783

end-user difficult. The major question, besides the technical aspect, is which of these
technologies will survive in the market, and how do they support the current need for
control components. As a matter of fact, the battle between these technologies is not
necessarily based on technological advantages; it is a mere marketing battle.
Out of the 20+ Ethernet based industrial protocols remains a much shorter list of
candidates that realistically have a chance to penetrate the American market significantly.
They are:
Ȋȱ EtherCAT
Ȋȱ Powerlink
Ȋȱ Ethernet/IP
Ȋȱ Modbus/TCP
Ȋȱ ProfiNet
Especially Modbus/TCP – basically Modbus over Ethernet -- with a cycle time between
5 and 10 milliseconds must be considered too slow for real-time control. It is nevertheless
extremely easy to implement, which explains its wide usage.
There are only three protocols that provide a direct hardware connection between
the physical layer and the application, i.e. they require a specific controller chip. These
protocols are:
Ȋȱ EtherCAT
Ȋȱ Sercos III (limited presence in North America)
Ȋȱ ProfiNet V3 (current status unknown)
EtherCAT and Powerlink also support CANopen device profiles to provide a certain
level of portability for existing CANopen applications.

18.4 FUTURE OF CAN

For many years, CAN and CANopen, a higher-layer protocol based on CAN, represented
the best choice for low-cost industrial embedded networking. However, since the official
introduction of CAN in 1986, there has been a quest to replace CAN and CANopen to
overcome the most obvious shortcomings such as limited baud rate and limited network
length.
Industrial Ethernet technologies are currently the most formidable challenge to
CANopen as the low-cost industrial networking technology of choice. Ethernet
technologies will eventually replace the majority of CANopen applications, at least with
regard to new developments, starting at this very moment in certain areas such as
industrial control including motion control and, especially, robotics. Ironically, CAN,
the underlying hardware layer of CANopen, has a far greater lifetime expectancy than
CANopen as a higher layer protocol.
This section will elaborate on the future of CAN and CANopen. It will also address
the need for faster fieldbus systems and narrow the field of potential winners in the
Ethernet race.
784ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

18.4.1 Further Aspects

There are several important advantages of CAN compared to others which makes CAN
especially interesting for many applications, of course, when its message rate is sufficient.
Collision-free bus arbitration: Standard Ethernet can suffer bus arbitration collisions
due to the underlying CSMA/CD bus arbitration scheme. Therefore, to limit the amount
of bus collisions we can use Standard Ethernet only to a limited bus load, or we have
to use additional protocols of the Ethernet protocol (like EthernetPowerLink or ProfiNet).
Additional protocols (e.g., time deterministic protocols), of course, cause additional
software overhead and specific hardware feature.
Multi- and broadcasting: Even if it is also possible with Ethernet to send broadcast
messages, these messages are not reliable. This means that it is not guaranteed that all
nodes of a network get a specific broadcasting frame. For some applications, like robotic
control, this can be a serious problem. With CAN, any message is a broadcast frame
and it is assured by the protocol that the transmitted data is consistent all over the
network due to the inherent error signaling mechanism.
Response time limited by protocol software processing time: In spite of the high overall
frame rate with 100 Mps Ethernet, the maximum frame rate accepted by a node is limited
by the time necessary for processing of a frame (TCP/IP protocol processing time). If
we also consider that a TCP/IP message needs to be confirmed (there is a request and
a response frame) and we neglect the frame transmission time, the time for processing
the IP/TCP frame is in the magnitude of almost 1 ms for a common microcontroller.
This means that the maximum frame rate of a node is limited to about 1000 frames per
second. Or, expressed in terms of response time, the response time even for a 100 Mbps
network is limited to about 1 ms (if we do not consider specific protocols like PowerLink).
Data integrity: Due to the different data securing mechanism (especially bit monitoring
and CRC) and the short message length of CAN frames, CAN provides an unexcelled
level of data integrity. The remaining error probability is given by:
Remaining error probability = frame error rate × 10 –13
This means that transmission errors will be detected with a very high probability by
the integrated error detection mechanism of the CAN protocol. This capability is essential
for any application which involves high risks.

18.5 SUMMARY

CAN is ideally suited in applications requiring a large number of short messages with
high reliability in rugged operating environments. Because CAN is message-based and
not address-based, it is especially well suited when data is needed by more than one
location and system-wide data consistency is mandatory. Fault confinement is also a
major benefit of CAN. Faulty nodes are automatically dropped from the bus, which
prevents any single node from bringing a network down, and ensures that the bandwidth
is always available for critical message transmission. This error containment also allows
nodes to be added to a bus while the system is in operation, otherwise known as
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ785

hot-plugging. Among the applications finding solutions with CAN are automobiles,
trucks, motorcycles, snowmobiles trains, buses, airplanes, agriculture, construction,
mining, and vehicles. In this model, the CAN bus model has been shown along with
the description of its protocol. The CAN board with Ethernet backbone block diagram
shows that Ethernet is a good network backbone.

18.6 CAN PRACTICAL

The following example sends from one CAN bus (CAN1) a counter while it is ‘listen’
on the other CAN bus (CAN2) to receive a packet. Each bus controller should be
connected to a CAN bus transceiver. These should be connected together at a CAN
bus (this project uses mbed 1768 microcontroller with mbed online compiler).

Microprocessor with two


CAN ports

CAN1 CAN2
port port

CAN1 CAN2Transceiver

120E Transceiver 120E

Pin9TX Pin10RX Pin30Rx Pin29Tx

#include “mbed.h” //MBED firmware example program of CAN node.

Ticker ticker;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
CAN can1(p9, p10);
CAN can2(p30, p29);
char counter = 0;

void send() {
printf(“send()\n”);
786ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

if(can1.write(CANMessage(1337, &counter, 1))) {


printf(“wloop()\n”);
counter++;
printf(“Message sent: %d\n”, counter);
}
led1 = !led1;
}

int main() {
printf(“main()\n”);
ticker.attach(&send, 1);
CANMessage msg;
while(1) {
printf(“loop()\n”);
if(can2.read(msg)) {
printf(“Message received: %d\n”, msg.data[0]);
led2 = !led2;
}
wait(0.2);
}
}

18.6.1 CAN Feedback Test

Two CAN transceivers (MCP2551’s) are used and made sure it’s wired up properly. We
modified the test code slightly to blink LEDs when messages are sent by CAN1 and the
other LED should show when CAN2 receives the message.
#include “mbed.h”
#include “CAN.h”

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);

CAN can1(p9, p10);


CAN can2(p30, p29);

Serial pc(USBTX,USBRX); //tx. rx


˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ787

int main() {

char count = 0;
CANMessage msg;

pc.baud(9600);

can1.frequency(125000);
can2.frequency(125000);

/*********Program Starts Here***************/

while(1) {

if(can1.write(CANMessage(0x42, &count, 1))) {


led1 = 1;
pc.printf(“> “);
}

//wait(0.5);

if(can2.read(msg)) {

led2=1;
pc.printf(“In “);

if(count == msg.data[0]) {
//led2 = 1;
count++;
pc.printf(“%02X “,msg.data[0]);

}
}

wait(0.5);
led1 = led2 = 0;
wait(0.2);
led4 = !led4;
//count++;
}
}
788ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

18.6.2 Multiple CAN

The figure below shows multiple messaging by CAN along with firmware code that is
connected to two nodes far off interconnected over CAN cable.
#include “mbed.h”
Serial pc(USBTX, USBRX); // tx, rx
Ticker ticker;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
CAN can1(p9, p10);
CAN can2(p30, p29);
char counter = 0;

void send() {
pc.printf(“send()\n”);
if(can1.write(CANMessage(1337, &counter, 1))) {
printf(“wloop()\n”);
counter++;
printf(“Message1 1337 sent: %d\n”, counter);
}

/*
if(can1.write(CANMessage(1338, &counter, 1))) {
pc.printf(“wloop()\n”);
counter++;
counter++; // two times increment
pc.printf(“Message sent: %d\n”, counter);
}

*/
/*
if(can1.write(CANMessage(1339, &counter, 1))) {
printf(“wloop()\n”);
counter++;
printf(“Message sent: %d\n”, counter);
}
*/

led1 = !led1;
}
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ789

int main() {
pc.printf(“main()\n”);
ticker.attach(&send, 1);
CANMessage msg;
while(1)
790ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

{
pc.printf(“loop()\n”);
if(can2.read(msg))
{
// printf(“Message received: %d id=%x\n”, msg.
data[0],msg.id);
led2 = !led2;

switch ( msg.id )
{
case 1337:
pc.printf(“Message 1 received: %d
id=%x\n”, msg.data[0],msg.id);
break;
case 1338:
pc.printf(“Message 2 received: %d
id=%x\n”, msg.data[0],msg.id);
break;
case 1339:
pc.printf(“Message 3 received: %d
id=%x\n”, msg.data[0],msg.id);
break;

default:
///printf(“default Message received:
%d id=%x\n”, msg.data[0],msg.id);
}

//wait(0.2);
}
}
˜—›˜••Ž›Ȭ›ŽŠȱ Ž ˜›”ȱ ǻǼȳ791

REFERENCES

Designing and Development of a CAN Bus Analyzer for Industrial Applications Using ARM
and PIC, Gadireddy Srikanth Kumar, ECM Department, K.L.University,Vijayawada, india
Implementation Of ‘CAN’ Protocol In Automobiles Using Advance Embedded System, Vikash
Kumar Singh, Kumari Archana, M.Tech, Lords Institute of Engineering and Technology,
Himayat Sagar, Hyderabad, INDIA
CANopen Network CAN bus Cabling Guide, Copley Control Corp.
Chapter 8, Backbone Design Overview
National Instruments http://www.ni.com/white-paper/2732/en/#toc7
The Future of CAN/CANopen and the Industrial Ethernet Challenge, Wilfried Voss, President
ESD electronics, Inc USA.
CAN-FD and ETHERNET Create Fast Reliable Automotive Data Buses for the Next Decade,
Y.B. Pradeep.

REVIEW QUESTIONS

1. Give introduction about CAN.


2. How does CAN work?

ANSWERS

1. Controller-area Network is a serial bus system designed to allow microcontrollers


and devices to communicate with each other without a host computer. CAN is
based on the ‘broadcast communication mechanism’ which is based on the
message-oriented transmission protocol.
2. CAN is a multi-master serial bus standard for connecting electronic control units,
also known as nodes. Two or more nodes are required on the CAN network to
communicate. The complexity of the node can range from a simple I/O device
upto an embedded computer with a CAN interface and sophisticated software.
The node may also be a gateway allowing a standard computer to communicate
over a USB or Ethernet port to the devices on a CAN network.
LABVIEW FPGA Real Time
19 & cRio Interfacing

OBJECTIVE
After going through this chapter, the students will be able to understand:
Ȋȱ How FPGA can be programmed using RT LabVIEW and also how to use real time
cRio hardware from M/S National Instruments.

19.1 INTRODUCTION

Field Programmable Gate Array (FPGA), being the latest venture in the field of embedded
electronics and the most successful configuration for embedded systems, is in great
demand these days. Compact RIO, a powerful control and acquisition system introduced
by National Instruments, is based upon reconfigurable FPGA technology. Apart from
FPGA, it also incorporates a real-time processor for reliable standalone applications.
Now instrumentation engineers can also benefit from the FPGA technology without any
knowledge of hardware description languages, because the Compact RIO systems can
be developed using LabVIEW development platform.
In this work, I have developed a digitizer used In Cryostat using the NI Compact
RIO. The algorithm for digitizer is implemented in LabVIEW.

19.1.1 Compact RIO Architecture

Compact RIO is a rugged, reconfigurable embedded system containing three components:


a processor running a real-time operating system (RTOS), a reconfigurable FPGA, and
interchangeable industrial I/O modules. The real-time processor offers reliable, predictable
behaviour and excels at floating-point math and analysis, while the FPGA excels at
smaller tasks that require high-speed logic and precise timing. Often Compact RIO
applications incorporate a human machine interface (HMI), which provides the operator
with a graphical user interface (GUI) for monitoring the system’s state and setting
operating parameters.

19.1.2 LabVIEW

LabVIEW is a graphical programming environment to develop sophisticated control


systems using graphical icons and wires that resemble a flowchart. It offers integration
with thousands of hardware devices and provides hundreds of built-in libraries for
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ793

advanced control, analysis, and data visualization—all for creating user-defined systems
more quickly. The LabVIEW platform is scalable across multiple targets and OSs, and,
in the case of Compact RIO, LabVIEW can be used to access and integrate all of the
components of the LabVIEW reconfigurable I/O (RIO) architecture.

19.2 REAL-TIME CONTROLLER

The real-time controller contains a processor that reliably and deterministically executes
LabVIEW Real-Time applications and offers multirate control, execution tracing, on
board data logging, and communication with peripherals. Additional options include
redundant 9 VDC to 30 VDC supply inputs, a real-time clock, hardware watchdog timers,
dual Ethernet ports, up to 2 GB of data storage, and built-in USB and RS232 support.
A Real-Time Operating System (RTOS) is able to reliably execute programs with
specific timing requirements.

19.3 RECONFIGURABLE I/O FPGA

The reconfigurable I/O FPGA chassis is the centre of the embedded system architecture.
It is directly connected to the I/O for high-performance access to the I/O circuitry of
each module and timing, triggering, and synchronization. Because each module is
connected directly to the FPGA rather than through a bus, we experience almost no
control latency for system response compared to other controller architectures. By default,
this FPGA automatically communicates with I/O modules and provides deterministic
I/O to the real-time processor. Out of the box, the FPGA enables programs on the real-
time controller to access I/O with less than 500 ns of jitter between loops. We can also
directly program this FPGA to further customize the system. Because of the FPGA speed,
this chassis is frequently used to create controller systems that incorporate high-speed
buffered I/O, fast control loops, or custom signal filtering. For instance, using the FPGA,
a single chassis can execute more than 20 analog proportional integral derivative (PID)
control loops simultaneously at a rate of 100 kHz. Additionally, because the FPGA runs
all codes in hardware, it provides the highest reliability and determinism, which is ideal
for hardware-based interlocks, custom timing and triggering, or the elimination of custom
circuitry normally required with nonstandard sensors and buses.

19.3.1 I/O Modules

I/O modules contain isolation, conversion circuitry, signal conditioning, and built-in
connectivity for direct connection to industrial sensors/actuators. By offering a variety
of wiring options and integrating the connector junction box into the modules, the
Compact RIO system significantly reduces space requirements and field-wiring costs.
The NI cRio used in our project is NI cRio-9063.
The NI cRio-9063 integrated system, shown in Figure 1, combines a dual-core processor,
a reconfigurable FPGA, and four slots for C series I/O modules within one chassis.
Featuring a 667 MHz dual-core ARM Cortex-A9 processor running the NI Linux Real-
794ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Time OS and an Artix-7 FPGA, this system is well suited for advanced embedded control
and monitoring applications. The device features 256 MB of DDR3 memory for embedded
operation, 512 MB of non-volatile memory for data logging, and a wide range of
connectivity options including Gigabit Ethernet, USB device, USB host, and serial ports.

Figure 19.1

We can use LabVIEW system design software to create, debug, and deploy logic to
both the on-board FPGA and the processor running the NI Linux Real-Time OS.
In this project there is one module attach to the cRio-9063:
1. NI 9381

19.4 WORKING WITH NI 9381

The NI 9381 multifunction I/O module for NI Compact RIO, shown in Fig. 19.2, was
designed to be a single, cost-effective module for general-purpose system I/O system.
By combining common I/O circuitry into a single module, the NI 9381 helps system
designers fit more functionality into a single system.

Figure 19.2
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ795

19.4.1 Analog I/O Timing

The analog circuitry on the NI 9381 is a multiplexed architecture that shares a single
timing engine that can sample up to 20 KS/s. This means the sample rate is a function
of up to 20 KS/s divided by the number of both analog input and output channels used.
The module features an overall update rate of 1,250 S/s when using all eight analog
input and all eight analog output channels together.
The following points are kept in mind when we work with NI 9381.
1. AI and AO operations that are run concurrently may exhibit jitter. Access both
subsystems using a single I/O Node to avoid jitter in our application.
2. This device supports only top-level FPGA target clock rates and single-cycle
Timed Loop clock rates that are multiples of 40 MHz, such as 40 MHz, 80 MHz,
120 MHz, and so on.

19.5 INTRODUCTION TO LABVIEW

LabVIEW programs are called Virtual Instruments, or VIs, because their appearance and
operation imitate physical instruments, such as oscilloscopes and multimeters. LabVIEW
contains a comprehensive set of tools for acquiring, analyzing, displaying, and storing
data. It is also called G-Language.

19.6 INTERFACING cRio WITH LABVIEW

The first step to getting started with NI products is to install the proper software and
drivers for our application.
Software-LabVIEW 32-bit

Drivers

1. NI cRio Device Drivers 15.0


2. LabVIEW Real-time module driver for LabVIEW 15.0
3. LabVIEW FPGA module driver for LabVIEW 15.0
4. LabVIEW 2015 FPGA Module Xilinx Tools Vivado 2014.4 and additional drivers
are installed according to use.

Configure Your Compact RIO Systems

1. Disabling all additional network interfaces ensures that cRio system is easy to
find on the network.
2. Disable secondary network interfaces, such as wireless access card on a Laptop.
3. Open NIMAX from the desktop or start menu
1. Expand Remote systems (Fig. 19.3)
796ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.3

Configure Ipv4 Address to static and change the IP-Address that must be the same
family of Host and ping it using command prompt to know whether cRio is receiving
data from host or not.

cRio and HOST Computer Operation

Host Computer cRIO

Control
LabVIEW RT
TCPAP

Lab VIEW LabVIEW


Data
FPGA
TCPAP

19.7 HOW TO USE LABVIEW IN FPGA

1. Open LabVIEW from desktop or start menu


When opening LabVIEW, you first come to the “Getting Started” window.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ797

Figure 19.4

In order to create a new VI, select “Blank VI” or in order to create a new LabVIEW
project, select “Empty project”, then follow the figures as shown in below.

Figure 19.5
798ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.6

Figure 19.7

When we have created a new VI or selected an existing VI, the Front Panel, shown
in Fig. 19.8, and the Block Diagram for that specific VI will appear, shown in Fig. 19.9.
In LabVIEW, we build a user interface, or front panel, with controls and indicators.
Controls are knobs, push buttons, dials, and other input devices Indicators are graphs,
LEDs and other displays.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ799

Figure 19.8 Front panel

Figure 19.9

After we build the user interface, we add code using VIs and structures to control
the front panel objects. The block diagram contains this code. In some ways, the block
diagram resembles a flowchart. Block diagram objects include terminals, sub-VIs,
functions, constants, structures, and wires, which transfer data among other block
diagram objects.
800ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

To find our cRio device in LabVIEW, right click on project file, select new -> Targets
and devices, as shown in Fig. 19.10.

Figure 19.10

Follow the steps, as shown in below figures

Figure 19.11
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ801

We have to select a programming mode based on our application.

Figure 19.12

If we have LabVIEW Real-Time and LabVIEW FPGA on our development computer,


we are prompted to select which programming mode we would like to use when we
add a Compact RIO target to our LabVIEW project. Upon selecting a mode, we can also
go into Hybrid Mode if we want to use a hybrid of LabVIEW FPGA and Compact RIO
Scan Mode for our application.

19.8 LABVIEW FPGA INTERFACE MODE

With the LabVIEW FPGA Interface mode, we can unlock the real power of Compact
RIO by customizing the FPGA personality in addition to programming the real-time
processor. This helps us achieve performance that typically requires custom hardware.
Using LabVIEW FPGA, we can implement custom timing and triggering, offload signal
processing and analysis, create custom protocols, and access I/O at its maximum rate.
When communicating data between an FPGA VI and Real-Time VI, we have the
option to stream data at very high rates using DMA FIFOs, or to communicate single-
point data using controls and indicators.

19.9 COMPACT RIO SCAN MODE

Using Compact RIO Scan Mode, we can program the real-time processor of your Compact
RIO system but not the FPGA. In this mode, NI provides a predefined personality for
802ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

the FPGA that periodically scans the I/O and places it in a memory map, making it
available to LabVIEW Real-Time. Compact RIO Scan Mode is sufficient for applications
that require single-point access to I/O at rates of a few hundred hertz. It does not support
streaming data at high rates.
Follow the steps, as show in figures below.

Figure 19.13

Figure 19.14
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ803

Figure 19.15

Make the block diagram in FPGA VI, as shown in Figs. 19.16 and 19.17.

Figure 19.16
804ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.17

How to create Digital Input and Output modules?

Digital I/O FPGA

To configure digital input output on 9381 module:


Ȋȱ Right click on the C series module name in the Project Explorer window and open
Properties.

Figure 19.18

Ȋȱ The Module Properties dialog box appears. We can configure the DIO pins
direction—input or output by selecting and changing direction.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ805

Figure 19.19

Figure 19.20

Ȋȱ To use the methods in the Method Node such as Set Output Enable or Set Output
Data we have to allow programmatic DIO line direction change.
806ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.21

Now create a New VI under the FPGA target in the Project Explorer.
Ȋȱ Right click on the Block Diagram and select FPGA I/O functions.
Ȋȱ Place an I/O Method Node in the block diagram.

Figure 19.22
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ807

Ȋȱ To select the desired I/O pin, right click on the method node, click on Select Item,
FPGA target and then select the Mod pin. (say Mod DIO0)

Figure 19.23

Ȋȱ Now select the method by right clicking on the method node and click on Select
Method.
Ȋȱ Select from the available methods. Available methods depend on the C series
module used and the FPGA target.
1. Set Output Data
2. Set Output Enable
3. Wait On Any Edge
4. Wait On Falling Edge
5. Wait On Rising Edge
6. Wait On High Level
7. Wait On Low Level
Ȋȱ Select Set Output Enable to configure the method node.
808ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.24

Figure 19.25

Ȋȱ Now add the I/O Node function by right clicking on the block diagram.
Ȋȱ Build the block diagram by creating appropriate constants, controls and indicators.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ809

Figure 19.26

Figure 19.27
810ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.28

Ȋȱ In the above diagram, we have configured the DIO0 as both input and output.

Figure 19.29

Ȋȱ To view the input and output functionality separately, we use two Mod pins – one
as input and other output as shown in the following block diagram.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ811

Figure 19.30

Figure 19.31

Ȋȱ We used the multi-meter to check the output at 15th pin (3V)


Ȋȱ We applied voltage at 16th pin to make the LED glow using multi-meter.
812ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.32

Ȋȱ How to create FIFO in block diagram?

Figure 19.33

READ FIFO

Figure 19.34
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ813

Ȋȱ To Create READ FIFO, follow the steps, shown in below figures.

Figure 19.35

Figure 19.36
814ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.37

WRITE FIFO

Figure 19.38

Ȋȱ To Create WRITE FIFO, follow the steps shown in below figures.


LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ815

Figure 19.39

Figure 19.40
816ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.41

The front panel, shown in Fig. 19.42 , is the Output of overall FPGA Code.

Figure 19.42

Ȋȱ Run the code and follow the steps, shown in below figures.
Ȋȱ Select use the local compile server and click OK.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ817

Figure 19.43

Figure 19.44

Figure 19.45
818ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Check the compilation status to know whether code is correct or not.

Figure 19.46

Ȋȱ Synthesis report is shown in Fig. 19.47

Figure 19.47
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ819

Ȋȱ Device Utilization report is shown in Fig. 19.48.

Figure 19.48

Ȋȱ Estimated timing report is shown in Fig. 19.49.

Figure 19.49
820ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Final timing is shown in Fig. 19.50.

Figure 19.50

Ȋȱ Xilinx log report is shown in Fig. 19.51.

Figure 19.51
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ821

Check the outputs on the front panel by applying inputs on the 9381 module input
pins using multi-meter.

Compilation

The compilation includes the following processes which are automatically proceeded:
Ȋȱ Synthesizing
Ȋȱ Placing
Ȋȱ Optimizing timing
Ȋȱ Routing
Ȋȱ Generating programming file
Ȋȱ Finalizing programming file
Ȋȱ Creating bit file
Ȋȱ To Know the properties of FPGA Target , right click on FPGA target device and
select properties.

Figure 19.52

Ȋȱ The figures from 19.53-19.57 shown below, represent the properties of FPGA.
822ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.53

Figure 19.54
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ823

Figure 19.55

Figure 19.56
824ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.57

HOST CODE

Figure 19.58

Figure 19.59
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ825

Figure 19.60

Ȋȱ In order to transfer data from FPGA to host , we have to configure open FPGA
VI reference.
Ȋȱ Right click on open FPGA VI reference->configure open FPGA VI reference.

Figure 19.61

Ȋȱ Follow the steps, shown in below given figures in order to configure open FPGA
VI reference.

Figure 19.62
826ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.63

Figure 19.64
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ827

DIGITIZER output:

Figure 19.65

Ȋȱ Here the sampling frequency is 1 kHz and frequency of message signal is 100 Hz.
Figure 19.66 shows the digitizer of sine signal in one cycle.

Figure 19.66
828ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ The data is exported to Excel sheet by right clicking on waveform chart and select
export to excel sheet, shown in Fig. 19.67.

Figure 19.67

Figure 19.68
DIGITIZER USING WAVE FORM REFERENCE LIBRARY
FPGA

Ȋȱ Figures 19.69 & 19.70 represents the FPGA code.

Figure 19.69
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ829
830ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.70
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ831

Ȋȱ Figure 19.71 represents the front panel of FPGA.

Figure 19.71

Ȋȱ Run the code and observe the below figures while compiling.

Figure 19.72

Figure 19.73
832ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.74

Ȋȱ Figure 19.75 represents HOST CODE.

Figure 19.75

Ȋȱ 8-channel Digitizer output waveform using waveform reference library is shown


in Fig. 19.76.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ833

Figure 19.76

Ȋȱ FREQUENCY SPECTRUM graph shown in Fig. 19.77.

Figure 19.77

Ȋȱ Digitizer of sine signal in one cycle (Fig. 19.78).

Figure 19.78
834ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ Frequency spectrum graph shown in Fig. 79.

Figure 19.79

Ȋȱ Data of Digitizer graph exported to excel sheet shown in Fig. 19.80.

Figure 19.80
Now using only one channel we can set the sampling frequency as 20KS/s.
This is possible only if we use one channel. The wave form of digitizer is shown in
Fig. 19.81.

Figure 19.81
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ835

In WAVE FORM REFERENCE LIBRARY

1. VIs combine common acquisition functions into logical blocks, which support
many different acquisition modes. VIs can present data with the NI LabVIEW
waveform datatype to easily integrate with other common LabVIEW software
components. The waveform datatype bundles the acquired data with its sampling
period, timestamp, and channel properties.
2. VIs perform a full complement of error checking including DMA FIFO overflow
(data buffer has filled up causing data to be dropped), module underflow (FPGA
code execution takes too long, causing your module to sample slower than
intended), and start/read/stop timeouts.
3. Included Read functions use a polling architecture, which gives the user control
over CPU usage during data acquisition.
4. Here the output data is more accurate and is similar to Input signal. So better to
use Waveform reference Library.

PRACTICAL ISSUE USING cRio: REINSTALLING


LABVIEW REAL TIME 15.0 MODULE

In case, there was a conflict due to the different versions of LabVIEW on the PC and
different software installed on the cRio device. To check the version installed on the
device o Open NI MAX and discover the device in the Remote Systems o Click on
Software and check which version is installed.

Figure 19.82

We used LabVIEW 2016 and tried implementing VI on the Real-time processor. But
a window of Conflict Resolution appeared as shown.
836ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.83

Open Control Panel and then enter Programs and Features window. Search for
National Instruments and double click to view the programs installed.

Figure 19.84
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ837

Figure 19.85

Reinstalling LabVIEW Real time 15.0 module

Figure 19.86 Delay program in Real time processor of cRio

RT.VI

Open the project in LabVIEW. Add the cRio device by right clicking on Project name
and then Add target and device.
838ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 19.87

View all the elements by clicking on the plus (+) sign in the hierarchy.

Figure 19.88

All the pins on the I/O module NI 9381 are displayed under Chassis.
Now create a new VI by right clicking on the device name as shown.

Figure 19.89
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ839

New -> VI
Three different widows appear– Front panel, Block diagram and Tool palette. Build
the block diagram and Run the VI in the front panel.

Figure 19.90

High Resolution Relative Seconds VI has been used in the block diagram which
functions by returning the current time in seconds.

Figure 19.91
840ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Deployment Progress window appears displaying the processes involved in compiling


the VI.

Figure 19.92

Close the Deployment Progress window after the Deployment is completed successfully.
The Front Panel displays the output of the VI. Observe the output and study the time
delay irregularities.

Figure 19.93

Waveform Chart properties can be explored by right clicking on the Waveform Chart
block and selecting Properties.
LabVIEW FPGAȱ ŽŠ•ȱ ’–Žȱ ǭȱ Œ’˜ȱ —Ž›ŠŒ’—ȳ841

Figure 19.94

Figure 19.95
842ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

REFERENCES

1. www.ni.com
2. https://knowledge.in.com

REVIEW QUESTIONS

1. Write a note on LabVIEW FPGA.


2. Name various drivers which are used to interface LabVIEW with CRIO?
3. What is real-time controller?

ANSWERS

1. The FPGA is a field-programmable gate array. It is a type of device that is widely


used in electronic circuit. FPGA is a semiconductor device which contain
programmable logic blocks and interconnection circuits. It can be programmed
to the required function after manufacturing.
2. NI Compact RIO and NI RIO.
3. Real-time controller combines a real-time processor with a real time OS.
20 Android App Inventor & Interfacing

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ How to build an android application using App inventor.

20.1 INTRODUCTION

Android, Inc. was founded in Palo Alto, California in October 2003 by Andy Rubin(co-
founder of Danger), Rich Miner (co-founder of Wildfire Communications, Inc.), Nick
Sears (once VP at T-Mobile), and Chris White (headed design and interface development
at WebTV) to develop, in Rubin’s words, “smarter mobile devices ...

What is the App Inventor?

App Inventor for Android is an open-source web application originally provided by


Google, and now maintained by the Massachusetts Institute of Technology (MIT). It
allows newcomers to computer programming to create software applications for the
Android operating system (OS).

20.2 TUTORIALS ON APP INVENTOR


Tutorial 1: Installing App Inventor 2 Setup on Windows

Step 1- Installing the Windows software for App Inventor Setup


It has two steps:
1. Installing the App Inventor Setup software package. This step is the same for all
Android devices, and the same for Windows XP, Vista, Windows 7, 8.1, and 10.
2. If you choose to use the USB cable to connect to a device, then you’ll need to
install Windows drivers for your Android phone.
NOTE: App Inventor 2 does not work with Internet Explorer. For Windows users, we
recommend using either Chrome or Firefox as your browser for use with App Inventor.

Installing the App Inventor Setup software package

You must perform the installation from an account that has administrator privileges.
Installing via a non-administrator account is currently not supported.
844ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

If you have installed a previous version of the App Inventor 2 setup tools, you will
need to uninstall them before installing the latest version. Follow the instructions at
How to Update the App Inventor Setup Software.
1. Download the installer.
2. Locate the file MIT_Appinventor_Tools_2.3.0 (~80 MB) in your Downloads file
or your Desktop. The location of the download on your computer depends on
how your browser is configured.
3. Open the file.
4. Click through the steps of the installer. Do not change the installation location
but record the installation directory, because you might need it to check drivers
later. The directory will differ depending on your version of Windows and whether
or not you are logged in as an administrator.
5. You may be asked if you want to allow a program from an unknown publisher
to make changes to this computer. Click yes.

Figure 20.1

Step 2. Launch aiStarter (Windows & GNU/Linux only)


Using the emulator or the USB cable requires the use of a program named aiStarter. This
program is the helper that permits the browser to communicate with the emulator or
USB cable. The aiStarter program was installed when you installed the App Inventor
Setup package. You do not need aiStarter if you are using only the wireless companion.
Ȋȱ On a Mac, aiStarter will start automatically when you log in to your account and
it will run invisibly in the background.
Ȋȱ On Windows, there will be shortcuts to aiStarter from your Desktop, from the
Start menu, from All Programs and from Startup Folder. If you want to use the
emulator with App Inventor, you will need to manually launch aiStarter on your
computer when you log in. You can start aiStarter this by clicking the icon on your
desktop or using the entry in your start menu.
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ845

The aiStarter Icon on Windows


To launch aiStarter on Windows, double click on the icon (shown above). You’ll know
that you’ve successfully launched aiStarter when you see a window like the following:

Figure 20.2

Step 3. Open an App Inventor project and connect it to the emulator


First, go to App Inventor and open a project (or create a new one -- use Project > Start
New Project and give your project a name).
Then, from App Inventor’s menu (on the App Inventor cloud-based software at app
inventor), go to the Connect Menu and click the Emulator option.

Figure 20.3

You’ll get a notice saying that the emulator is connecting. Starting the emulator can
take a couple of minutes. You may see update screens like the following as the emulator
starts up:

Figure 20.4
846ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The emulator will initially appear with an empty black screen (#1). Wait until the
emulator is ready, with a color screen background (#2). Even after the background
appears, you should wait until the emulated phone has finished preparing its SD card:
there will be a notice at the top of the phone screen while the card is being prepared.
When connected, the emulator will launch and show the app you have open in App
Inventor.

Figure 20.5

Figure 20.6
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ847

Tutorial 2: How to use button

1. First drag a button from a user interface to the main screen1 in the developer
mode.

Figure 20.7

2. You can program your button so that it can perform different functions. For this
you have to go to block section.

Figure 20.8

3. In the block section you have to click on the button section to see all the functions
of the button.
848ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 20.9

4. To see the output you have to connect to emulator.

Figure 20.10

Figure 20.11
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ849

OUTPUT

Figure 20.12

Tutorial 3: How to change color of the textbox when button is pressed

1. Select button and textbox from the user interface and drag it to the main screen.

Figure 20.13

2. Now go to the block section to program the button and choose onclock event
from the button1 and select set textbox.background from the textbox section and
select the color from color section.
850ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 20.14

OUTPUT

Figure 20.15 After clicking button


—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ851

Figure 20.16

Tutorial 4: How to make a simple login screen

1. First drag the textbox, password field, two labels for the Name and Password
field and a button from user interface to the main screen.
2. You can change the properties (name of the field, its size, color of the field) of
the button as well as the textbox by going to the properties block.

Figure 20.17
852ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 20.18

PROPERTIES

1. Background-color: This property will specify the background color of the button.
2. Enable: This is a checkbox which when checked enables the button else it disable
the button.
3. Font bold: This property specifies if we want the text of button to be bold .
4. Font size: This property specifies the size of the font.
5. Height: This property specifies the height of the button.
6. Width: This property specifies the the width of the button.
7. Shape: This property specifies the shape of the button .
8. Text : This property specifies the text on the button.
9. After changing the text for the all the fields our main screen looks like this:
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ853

Figure 20.19

10. Now we go to block section to program our fields.

OUTPUT

Figure 20.20
854ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Now enter any thing in Name and password field.

Figure 20.21

Now enter correct name and password which is Admin and passwd.

Figure 20.22
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ855

Tutorial 5: How to create popup window

1. First select notifier from user interface and drag it to main screen.

Figure 20.23

2. Then go to block section where you will find screen.intialize command.

Figure 20.24
OUTPUT

Figure 20.25
856ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Tutorial 6: How to open a particular url by clicking a button


WEB VIEWER:

The Web Viewer component lets you show a web page within your app. You can show
Google Maps page showing the user’s current location, a twitter page showing the most
recent trending topics related to your app, or a page from nba.com showing the statistics
for your favorite players. WebViewer is like the Canvas component in that it defines a
subpanel of the screen. But whereas Canvas is used for drawings and animations,
WebViewer shows a web page.
1. First go to designer block and drag 4 buttons from user interface to the main
screen. Name these buttons as Google, Yahoo, Thinkspeak and youtube.

Figure 20.26

2. Now select web viewer component from user interface and then drag it to the
screen. Then go to the block section to program the button.

Figure 20.27
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ857

OUTPUT

Figure 20.28

After clicking google button-

Figure 20.29
858ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

After clicking Yahoo button-

Figure 20.30

After clicking YouTube button

Figure 20.31
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ859

Tutorial 7: How to use multiple screen

1. Here we have to go to designer section and drag label and button to the main
screen.

Figure 20.32

2. Add 2nd screen by clicking the add screen button.

Figure 20.33
860ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

3. Drag label in the main screen2

Figure 20.34

4. Now go to block section to program the button and using open another screen
function.

Figure 20.35
OUTPUT

Figure 20.36
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ861

After clicking the button.

Figure 20.37

Tutorial 8: How to use if-else statement in app inventor2


Q) Display a number which is greater than zero.

1. Drag label 1, 2, textbox and button from the user interface to the main screen
and change their names by changing there properties.

Figure 20.38
862ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

2. Now go to the block section and program the button.

Figure 20.39

3. Now see the output.

OUTPUT

Figure 20.40
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ863

Figure 20.41

Figure 20.42
864ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Tutorial 9: How to add two numbers

1. Add 3 labels, 3 textbox and a button to the main screen change their properties.

Figure 20.43

2. Now go to the block section and program the button.

Figure 20.44
OUTPUT

Figure 20.45
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ865

Tutorial 10: How to add image to the main screen

1. Drag the image icon from the user interface to the main screen.

Figure 20.46

Figure 20.47
866ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 20.48

Tutorial 11: How to select a particular date.

1. First select date picker from the user interface and drag it to the main screen.

Figure 20.49
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ867

2. Go to the block section where you will select screen.initialize event .

Figure 20.50
OUTPUT

Figure 20.51
868ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Tutorial 12: How to make a list and add item to the list
Making a List

In App Inventor, lists, like numbers and text, are “hidden” variables, not seen by the
user. A list is created in the blocks editor using a variable block and a make a list block.
Suppose, for instance, that we’re writing an app to text a list of friends with one click.
We’d create the phone numbers list in the following manner:
1. From the Built-In palette, drag a “define variable” block into the program area
and change the name from “variable” to “list”.
2. From the Lists palette, drag a “make a list” block in and latch it to the variable.
This tells App Inventor that the variable will store a list of data as opposed to a
single scalar.
3. Since the elements of our list are phone numbers, drag in some text blocks, enter
the desired numbers, and connect them to the “item” slots in the make a list
block. Note that a new “item” slot open up each time you add a new element to
the list.

Figure 20.52

Figure 20.53
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ869

OUTPUT

Figure 20.54

After Clicking Listpicker

Figure 20.55
870ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Tutorial 13: How to create a led

1. First drag 2 buttons ,a canvas and a ball (to make a led).

Figure 20.56

2. Now go to block section to program the buttons.

Figure 20.57

OUTPUT

After clicking the on button


—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ871

Figure 20.58

After clicking off button

Figure 20.59
872ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Tutorial 14: How to use clock (how to print a message in every 5 sec).

1. First select timer from the sensors and drag it to the main screen.

Figure 20.60

2. Go to block section where you will program your clock.

Figure 20.61

OUTPUT
After every 5 sec you will see a message
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ873

Figure 20.62

Tutorial 15: How to retrieve contents(html) from the web by using web components
WEB Component

The Web component, a relatively new component in App Inventor, facilitates an app
communicating with a web service via the standard Hypertext Transfer Protocol (HTTP).
The information arrives as data that you can display or process as you like. The
component is fairly low level, and using it requires some programming expertise. You
typically set the Web.URL property to specify which web service you will communicate
with, and then you call one of the HTTP methods to request some action. It’s complicated
because you need to understand the API of the web service (the protocol for
communication), and you need to understand how to process the information that the
web service returns to your app. This processing is known as parsing, and it is an
advanced programming technique.
1. Drag the button and web component to the main screen.

Figure 20.63
874ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

2. Go to block section where you will program your web component.

Figure 20.64

Web1.Url is set to the URL for communicating with Google. When Web1.Get is called,
the request is made, but no data is returned immediately. Instead, when Google returns
the requested data to your app, the Web1.GotText event is triggered, and this is where
you can process the returned data. The event parameter responseContent holds the data.

OUTPUT

Figure 20.65

After clicking response button.


—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ875

Figure 20.66

Tutorial 16: How to use TinyDB.

What is TinyDB?
TinyDB is a simple “database” that stores data on your phone or tablet. Unlike program
variables that go away when your app is finished running or your phone is re-set, values
stored in TinyDB remain on your phone for use the next time your app is run.
Using TinyDB
TinyDB provides a simple way to store and retrieve data efficiently and to store the
data in long-term storage. TinyDB is based on the concept of a “tag” to identify the
stored data, and the data value. Think of a “tag” as like using your name as your
identification to look up your address:

Figure 20.67
876ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 20.68

Figure 20.69

Looking up a value is processed by the btnFind Click event handler. Again, the user
entered key (tag) value is used in a call to TinyDB1.GetValue. This call returns the stored
value, or, if not found, it substitutes the text that we provided for valueIfTagNotThere:
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ877

Figure 20.70

TinyDB stores a list of all the tags we have used in our TinyDB database. We can
fetch these values by calling TinyDB1.GetTags, which returns a list containing all of the
tags.
Our block code then scans through the list of tags. For each tag in the list, the code
callsTinyDB1.GetValue to fetch the corresponding value. Once we have both the tag and
the value, these are combined into a tag : value pair and stored in another list. Why do
we store these pairs in another list? Because to keep our code simple, we use a ListView
to display the results on screen – ListView is built to display the values in a list – so
we build a list of key:value pairs!

Figure 20.71

The erase function could not be easier – or more dangerous! One call to Tiny DB1.
ClearAll does it all!

Figure 20.72
878ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

OUTPUT

Figure 20.73

To add an item, enter a “tag” value and then enter a value that corresponds to that
tag. For this demo, I pretended this is a simple “Task list” manager and I eventually
entered 3 task items, using the task name (task1, task2, task3) as tag names, and a brief
description of each “task” as the data value.

Figure 20.74
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ879

List all Items uses a ListViewer component to display all of the values in TinyDB. Note
that for convenience, I wrote the code so that tag names are always converted to upper
case letters: “task1” becomes “TASK1”. This way, the user may use any combination of
letter cases (such as “task1”, “Task1”, “TASK1” and each of these is treated as equivalent.)

Figure 20.75

Tutorial 17: Using Accelerometer in app inventor

This tutorial introduces the accelerometer – at a high level – as a tool to detect the phone
being shaken. You can use this feature as another kind of user input to your app, for
example, make a game where shaking the phone resets the game play or starts a new
game.
An accelerometer is a hardware device that detects and measures motion, typically
in three axes: X, Y and Z. For example, if the phone is moved left or right, the acceleration
changes in the X axis and the accelerometer returns a value indicating the X axis
movement.
Smart phones – and many modern devices – have special hardware accelerometer
components built in. The orientation sensor, described previously, is actually a software
sensor that uses the hardware accelerometer but converts acceleration into orientation
values.
The purpose of this demonstration app is to show an example of using the
accelerometer.
The user interface is simple – it displays a Start button and a Stop button, and the
status of the accelerometer.
880ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 20.76

How This Works – The Blocks

The Start button activates the accelerometer by setting its Enabled property to true. The
sensitivity of the accelerometer, that is, how sensitive it is to motion – is set by adjusting
the value of the Sensitivity property. Setting the value to 3 makes the accelerometer
more sensitive, while a value of 1 makes the accelerometer less sensitive. For our
demonstration app, the Sensitivity ought to be set to 1 (less sensitive) but because the
app is intended to show some features of the accelerometer, we will detect the amount
of shaking in a different way.
At the bottom of the Designer Viewer, you can see that three non-visible components
have been added to this app. The AccelerometerSensor1 is the component that detects
phone movement. Find the Accelerometer in the Sensors section of the Palette.
The Player1 component is a media player – for our app, when the phone is shaken,
it plays an mp3 audio file that is specified as the Source in the properties for the player.
Find the Playercomponent in the Media section of the Palette.
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ881

Figure 20.77

The remaining features, while simple, are explained in sort of reverse order – meaning
we show how to stop the player before we see how to start it! We start with the Stop
button. When the Stop button is pressed on screen, we disable the accelerometer, disable
the timer, and disable the media player.
The accelerometer is disabled by setting its Enabled property to false. The Clock’s timer
is disabled be setting the TimerEnabled property to false, and the media player is stopped
by calling its Stop method.

Figure 20.78

The media player is started by calling it’s Start method, as seen below. Because this
set of blocks is very wide, the blocks are displayed very narrow – click on the image to
display in a larger size. The rest of the code blocks, here, will be explained in a moment.

Figure 20.79
882ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Tutorial 18: How to Create Text To Speech In App Inentor 2

1. First add a button and a textbox from the user interface to the main screen and
then drag Text to Speech component from the social interface and put it in the
screen

Figure 20.80

2. Now go to block section and program the button:

Figure 20.81

In this tutorial whenever you click a button app will speak a text written in the text.
—›˜’ȱ™™ȱ —ŸŽ—˜›ȱ ǭȱ —Ž›ŠŒ’—ȳ883

OUTPUT

Figure 20.82

Tutorial 19: How to create a simple timer

1. First add a start ,stop , save, load button to the main screen

Figure 20.83

2. Now go to block section where you will program your clock and buttons.
884ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

OUTPUT

Figure 20.84

REFERENCES

1. www.appinventor.org
2. https://puravidaappl.com

REVIEW QUESTIONS

1. What is the App inventor?


2. How to create a button using App inventor?
3. How to create pop-up window using App inventor?
4. How to open a particular URL by clicking a button?
5. What is TinyDB?

ANSWERS

1. App inventor let’s you develop applications for android phones using a web.
2. The button component can have methods, events, and properties. Most properties
can be changed by apps.
3. It is possible to create a popup window when user presses a button (like notifier)
with image/user inputs.
4. Set Web1URL to the desired web link. Open web browser when a button of web
viewers is clicked.
5. TinyDB is a simple database that stores data on your phones or tablets.
21 Internet of Things (IoT) & Interfacing

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ The basics of IoT and use of ARM mbed platform to develop and stream data to
IBM Bluemix.

21.1 INTERNET OF THINGS

The Internet of Things (IoT) is a system of interrelated computing devices, mechanical


and digital machines, objects, animals or people that are provided with unique
identifiers and the ability to transfer data over a network without requiring human-to-
human or human-to-computer interaction.
Internet of things is the concept of connecting any device with an on and off switch
to the Internet. This includes everything from cell phones, washing machines, headphones,
lamps, wearable devices to larger projects in industries and organizations.
On a broader scale, the IoT can be applied to things like transportation networks:
“smart cities” which can help us reduce waste and improve efficiency for things such
as energy use; this helps us understand and improve how we work and live.
With the advancement of technology, many challenges come along. Security is a big
issue in applying IoT. With billions of devices being connected together, there is a risk
of individual’s information getting vulnerable to threats of hacking. Also we have the
issues of privacy and data sharing.
IBM has come up with a series of platforms for developing applications on Internet
of things. The three platforms namely- IBM Bluemix, IBM Watson and Node RED, are
used to connect devices, collect data, publish on the cloud and create applications on
the web. IBM Bluemix is the cloud computing platform to create, run, deploy and manage
applications on the web. IBM Watson platform is the service which allows one to connect
devices and publish data from the devices on the IBM cloud. Node-RED is the online
flow editor for the application design using pre-defined nodes and JSON commands.
The sensor device streams data over Ethernet which is further published on the cloud
using programming and IBM platforms.
886ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

21.2 INTERNET OF THINGS USING ARM MBED STARTER KIT


21.2.1 ARM MBED IoT Starter Kit to Learn What is IoT.

This starter Kit for IBM IoT Foundation provides the user with a slick experience, getting
data from the on-board sensors into the IBM cloud. After the initial out of box experience,
the infinite possibilities of cloud applications can be explored through IBM’s production
grade Bluemix platform, in which deployment and device management is as simple for
one device as it is for one million. The starter kit hardware can be modified and extended
to explore the device design space.
Refer the following links for more information:
https://developer.mbed.org/platforms/IBMethernetKit/
https://developer.ibm.com/recipes/tutorials/arm-mbed-iot-starter-kit-part-1/
The ARM MBED IoT Starter Kit (Figure 1) includes the following components:
Ȋȱ FRDM K64f
» NXP K64F Kinetis K64 MCU (MK64FN1M0VLL12)
» High performance ARM® Cortex™-M4 Core with floating point unit and DSP
» 120 MHz, 256 KB RAM, 1 MB FLASH
Ȋȱ MBED Application Shield
» 128x32 Graphics LCD
» 5-way joystick
» 2 x Potentiometers
» Speaker, PWM Connected
» 3 Axis +/1 1.5g Accelerometer
» RGB LED, PWM connected
» Temperature sensor

Figure 21.1
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ887

Following settings are done to start with the kit:


Ȋȱ Connect the two boards together.
Ȋȱ Connect the computer to the boards using USB cable.
Ȋȱ Connect Internet access network using Ethernet cable.
IBM has provided platform for easier working on Internet of things. There are three
platforms on which one has to work to develop an IoT application.
Ȋȱ IBM Bluemix
Ȋȱ IBM Watson
Ȋȱ Node-RED
For simple visualization of data on the device, Quickstart on IBM Watson platform
is used. (Figs. 21.2 and 21.3)
Ȋȱ The device is power ON by connecting to the PC through USB.
Ȋȱ Now scroll down the LCD using the joystick.
Ȋȱ Device ID appears on the LCD.
Ȋȱ Enter this device ID in the Quickstart.
Ȋȱ The data from the device sensors appears in the form of graphs.

Figure 21.2
888ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.3

21.3 IBM BLUEMIX

IBM Bluemix is the cloud computing platform to create, run, deploy and manage
applications on the web.

Figure 21.4(a)
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ889

Ȋȱ To build an application on Bluemix, select the desired category from the catalog.
Ȋȱ The user interface is simple and designed aptly for beginners to expert levels.
Ȋȱ For example, select Internet of things platform starter from the boilerplates in
the catalog and create your first application by creating unique Application name
and Host name (Fig. 21.4(c)).
Ȋȱ Create a new application, then screen will take you to following Boilerplate
(window) from where you need to select Internet of things platform as shown in
Fig. 21.4(a) and (b).

Figure 21.4(b)

Figure 21.4(c)
890ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The Bluemix application dashboard will appear as shown in Fig. 21.5 below.

Figure 21.5

21.4 IBM WATSON


The next step would be that you need to first create a service.
IBM Watson platform is the service which allows one to connect devices and publish
data from the devices on the IBM cloud.
Ȋȱ To start with a sample, launch Watson dashboard from the Bluemix application
from Connections.
Ȋȱ Go to Connections and open Watson in new tab (Take IoF service standard (Fig.
21.6)

Figure 21.6
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ891

Now click on to launch dash board till you get following screen.

Figure 21.7

Ȋȱ Add Devices and Boards to configure the service.


Ȋȱ Go to Devices. (Fig. 21.7 (a))

Figure 21.7(a)
892ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.8

Click on to Add device

Ȋȱ First Create Device Type (Fig. 21.8 and 21.9).

Figure 21.9
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ893

Figure 21.10

Note: The device type name must consist only of alpha-numerical characters plus hyphen
(-), underscore (_) or period (.)
Ȋȱ Then add devices in the created device type (Fig. 21.10).

Figure 21.11
894ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Remaining following screens, Select default -Enter

Figure 21.11 (a)

Now you get following window, click Next

Figure 21.11 (b)


—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ895

Click CREATE ON next following window

Figure 21.11 (c)

Now select the created device type and click next in the following window ( Don’t
press create device again!!!)
Ȋȱ While adding devices, provide Device ID and additional details about the device.
(Fig. 21.11)

Figure 21.11 (d)


896ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Device ID, type and authentication token are important. Authentication token is created
for the connected device. This is unique to the device and is used as a password while
programming (Fig. 21.12).

Figure 21.12

Figure 21.13
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ897

SAVE THE FOLOWING INFORMATION FOR FUTURE USE BY IoT SENSOR DEVICE
FIRMWARE
Or PYTHON SENSOR-GATE-WAY SOFTWARE . IoT SENSOR DEVICE FIRMWARE
is created/coded inside the microcontroller to update/publish data at a specific interval
without having an additional PC in between sensor and IoT broker. An
Example of such a code can be seen in the following link:
https://developer.mbed.org/teams/IBM_IoT/code/IBMIoTClientEthernetExample/
PYTHON SENSOR-GATE-WAY SOFTWARE is the front-end software run on a PC
which can stream data to IoT cloud/broker when sensor is not intelligent enough to
stream data. PYTHON SENSOR-GATE-WAY SOFTWARE will have all functions to
read sensor-data and connect AND UPDATE/PUBLISH DATA to IoT clould/broker
EVERY SECOND or any pre-programmed interval from a PC running Python.
Organization ID
0xpugg
Device Type
thermostat
Device ID
room1
Authentication Method
token
Authentication Token
**********************

Another example of such information used practically


Organization ID 9fzcvf
Device Type CRYOGENICSsensors
Device ID CYOGENICS-SENSORS-ID
Authentication Method token
Authentication Token CRYOGENICS-TOKEN

In the above info, device type will be device type in python(CRYOGENICSsensors),


python organization will be the word seen on top right corner of IBM IoT Watson
screen along with login email(e.g. 9fzcvf)
Device name will be used as the macaddress in python client.
Note that Device name=Device Id= CYOGENICS-SENSORS-ID
Now at last the IBM IoT Watson IoT platform is ready to take data as shown below.
The triangular sign will be turned into a “wi-fi active ” sign as soon as data is published
from sensors elsewhere.
898ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.13 (a)


21.5 NODE RED

Node-RED is the online editor for the application. It is a flow editor. The application is
created as a flow diagram. It can be designed using predefined nodes and .json
commands.
Ȋȱ To open the Node RED editor, click on the URL of the application created in
Bluemix (Fig. 21.13).
Ȋȱ Node RED flow editor window will open (Fig. 21.14). Go to the editor to edit the
flow diagram.

Figure 21.14
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ899

Ȋȱ In the example, the following (Fig. 21.15) diagram appears.


Ȋȱ Configure the IBM IoT App In and Send to IoT Platform nodes with appropriate
entries related to the device.

Figure 21.15

Ȋȱ To configure IBM IoT App In without connected device, enter details as shown
in Fig. 21.16.
Ȋȱ Click Done and then Deploy.

Figure 21.16
900ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ȋȱ To configure IBM IoT App In with a connected device, enter details as shown in
Fig. 21.17.
Ȋȱ Click Done and then Deploy.

Figure 21.17

Ȋȱ To configure Send to IoT Platform, enter details as shown in Fig. 21.18.


Ȋȱ Click Done and then Deploy.

Figure 21.18
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ901

Ȋȱ Check devices in IBM Watson. (Fig. 21.19) It should show connected when
connection is established.

Figure 21.19

Ȋȱ Check Send Data node in the Debug pane as shown in Figs. 21.20 & 21.21.

Figure 21.20
902ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.21

21.6 MQTT PROTOCOL

MQTT is a lightweight protocol for publishing and subscribing information with more
reliability in both directions.
MQTT was invented in 1999 by Andy Stanford-Clark (IBM) and Arlen Nipper. The
original problem was to send sensor data from oil pipelines through a satellite link.
MQTT is designed to handle high volumes of data in low bandwidth networks. The
key feature of MQTT are that it has a small code footprint. It runs on the top of TCP/
IP. Both client and broker (Fig. 21.22) need a TCP/IP stack. MQTT avoids polling and
is event oriented.
MQTT has lower latency and uses less number of bytes as compared to HTTP.

Figure 21.22
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ903

Figure 21.23

The Broker works like server between the Clients with the connected devices. (Fig.
21.21) The clients publish and subscribe messages through broker. The client always
initializes the connection with the broker (Fig 21.22).
QoS (Quality of Service) is the parameter that guarantees the quality and delivery of
messages. This can be 0, 1, 2 accordingly set by the client and acknowledged by the
broker.

21.7 INTERNET OF THINGS USING PYTHON

PYTHON SENSOR-GATE-WAY SOFTWARE is the front-end software which is


developed to stream data to IBM Bluemix IoT cloud/broker when sensor or sensor-
device connected to PC . This is used when sensor is not intelligent enough to stream
data by itsef. PYTHON SENSOR-GATE-WAY SOFTWARE will have all functions to read
sensor-data and connect AND UPDATE/PUBLISH DATA to IoT cloud/broker EVERY
SECOND or any pre-programmed interval from a PC running Python

21.7.1 Getting Started with Python for IoT

Ȋȱ Download and install Python 2.7.13 or Python 3.5 module.


Ȋȱ Install the latest version of the library with pip.
Ȋȱ The included dependencies are:
» paho-mqtt
» iso8601
» pytz
» requests
To install the library:
Open command prompt and enter the following:
[root@localhost ~]# pip install ibmiotf
Thus for installing:
C:\>Python27\Scripts\pip install ibmiotf
The command prompt window will look as shown in Fig. 21.24.
904ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.24

After finalizing the python code for publishing data from the device to IoT cloud, we
have to configure the IBM Watson service platform to visualize the published data.
Refer to the following link for more details:
https://developer.ibm.com/recipes/tutorials/ibm-bluemix-with-python-and-iot-service/

21.7.2 Creating IBM Watson Service


Ȋȱ Log in to IBM Bluemix and open Catalog (Fig. 21.25).
Ȋȱ Select Internet of Things Platform from the Services. (Fig. 21.25)
Ȋȱ Provide an appropriate Service name and choose from the plans

Figure 21.25
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ905

Service will be created. Launch the dashboard. (Fig. 21.26)

Figure 21.26

Figure 21.27

Ȋȱ Now, go to Devices to add the connected device.


Ȋȱ Create a Device Type and add devices into it (Figs. 21.27 and 21.28)
Ȋȱ Following windows show the steps.
Ȋȱ Device type, Device ID and Authentication token are important. Other details like
Meta data and Additional fields are optional. (Fig. 21.29)
906ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.28

Figure 21.29

Ȋȱ Authentication token is a password which is required while programming the


device to send data on IBM cloud.
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ907

Ȋȱ It can be Auto-generated or Self-provided (Fig. 21.30)

Figure 21.30

Figure 21.31
908ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Following are the important details which need to be noted down from the summary:
Organization ID
zpjokw
Device Type
LINAC-sensors
Device ID
LINACsensor35
Authentication Method
token
Authentication Token
***************
Ȋȱ Now connect the device to the PC through Ethernet cable. (Figs. 21.34 and 21.35
show the device connected to test) Try to ping to the device to confirm that it is
connected. Else modify the IP settings of the PC.
Ȋȱ Connect the PC with Internet through WiFi or USB.
Ȋȱ Once the device is successfully connected, run the python code (after entering the
details in the code) (Fig. 21.31)
Ȋȱ Open the IBM Watson dashboard in the same or any other PC.
Ȋȱ Open Devices. The device will be shown as connected (Fig. 21.32)
Ȋȱ Click on the device to view its status and data points.

Figure 21.32
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ909

Ȋȱ Data points will be visible under Sensor information (Fig. 21.33).

Figure 21.33

Figure 21.34
910ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.34 (a) Figure 21.35

Ȋȱ There are 35 data points in the given setup created through JSON in the python
code. (Table 21.1 and Fig. 21.36)
Table 21.1 List of data points created out of the sensor
S.No. Temperature Level Pressure Vacuum
1. BUN LN2 TEM 11 BUN LN2 LVL 21 BUN LN2 PRS 31 BUN VAC
2. BUN LHe TEM 12 BUN LHe LVL 22 BUN LHe PRS 32 L1 VAC
3. L1 LN2 TEM 13 L1 LN2 LVL 23 L1 LN2 PRS 33 L2 VAC
4. L1 LHe TEM 14 L1 LHe LVL 24 L1 LHe PRS 34 L3 VAC
5. L2 LN2 TEM 15 L2 LN2 LVL 25 L2 LN2 PRS 35 REB VAC
6. L2 LHe TEM 16 L2 LHe LVL 26 L2 LHe PRS
7. L3 LN2 TEM 17 L3 LN2 LVL 27 L3 LN2 PRS
8. L3 LHe TEM 18 L3 LHe LVL 28 L3 LHe PRS
9. REB LN2 TEM 19 REB LN2 LVL 29 REB LN2 PRS
10. REB LHe TEM 20 REB LHe LVL 30 REB LHe PRS

Figure 21.36
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ911

Ȋȱ To visualize the data published, go to the Boards (Fig. 21.37)


Ȋȱ Create a new Board (say LINAC Sensors Information)
Ȋȱ Add Cards to the board: Line chart, Bar graph, Properties, etc. (Fig. 21.38)

Figure 21.37

Ȋȱ The data points are visible in the Property option while creating a new card.

Figure 21.38

Ȋȱ The card will be created and information published will appear graphically as
shown in Fig. 21.39.
912ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.39

21.7.3 Python Programming

The python code required for getting the data from the device and publishing it on the
IBM cloud requires importing libraries and few important sections.

21.7.3.1 Important parts of the python code used are as follows:

Ȋȱ The function used for collecting data from IP address using HTTP:
def myfn0():
htmlfile = urllib.urlopen(“http://192.168.1.11/rpc/LLT/read”)
htmltext = htmlfile.read()
str = htmltext
print str
return float(str)
Ȋȱ Entering the information from the IBM Watson, i.e., the device details and
authentication token:
macAddress=”LINACsensor35” #We can give the mac address as default also
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ913

#Set the variables for connecting to the IoT service


broker = “”
topic = “iot-2/evt/status/fmt/json”
username = “use-token-auth”
password = “-*LoLgx@(QVyeZRmES” #auth-token
organization = “zpjokw” #org_id
deviceType = “LINAC-sensors”
Ȋȱ Calling functions, printing & publishing variables:
BUN_LN2_TEM = myfn0()
print BUN_LN2_TEM

21.7.3.2 How to configure data points created out of sensor?

A sensor consists of different variables like temperature, pressure or vacuum. To create


and add the variables to be read on the cloud, the python code needs a JSON encoding
command. The following command is added in the python code in the end.
## JSON FORMAT FOR CREATING DATA POINTS IN IBM WATSON DEVICE
msg = json.
JSONEncoder().
encode({“d”:{“BUN_LN2_TEM”: BUN_LN2_TEM,”BUN_LHE_TEM”:BUN_LHE_
TEM})
“BUN_LN2_TEM”:BUN_LN2_TEM
This is the name of data point to be published on the IBM Watson.
“BUN_LN2_TEM”:BUN_LN2_TEM
This part is the variable from the python code to read the value and publish under
data point.

21.8 INTERNET OF THINGS USING LABVIEW

National Instruments Inc. provides an IBM IoT library (Fig. 40) for Lab VIEW. Following
is an example VI (Fig. 21.41) that publishes a randomly generated waveform to the IBM
Watson IoT platform.
Refer following links for more details and download the IoT library for LabVIEW:
https://developer.ibm.com/recipes/tutorials/
national-instruments-labview-for-the-iot-foundation/
https://github.com/Espotel/
LabVIEW-IOTFoundation?cm_mc_uid=28386409093714828159014&cm_mc_
sid_50200000=1481700101
914ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 21.40

Ȋȱ Create the IBM Watson service by following the same steps as done for Python.
Ȋȱ Enter the device details on the front panel of the VI (Fig. 21.42)
Ȋȱ Run the VI.
Ȋȱ The waveform on the front panel of the VI appears on the IBM Watson Board.
(Fig. 21.43)

Figure 21.41
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ915

Figure 21.42

Figure 21.43

21.9 RESULTS

ARM MBED IoT Starter kit is used to learn concepts of IoT and configuration of IBM
platforms. The data is read from the device using Ethernet connection and is published
on the IBM cloud using Python programming. LabVIEW programming can also be used
for IoT applications.
916ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

(a) (b)
Figure 21.44: (a) Screenshot of output of running Python code. (b) Screenshot
of IBM Watson Board with published data from the connected device.

(a) (b)

Figure 21.45: (a) Screenshot of front panel of LabVIEW program. (b) Screenshot
of IBM Watson Board displaying data from LabVIEW.

REFERENCES

1. https://en.m.wikipedia.org
2. https://www.techopedia.com
3. https://www.element14.com
4. www.ni.com

REVIEW QUESTIONS

1. What do you mean by internet of things?


2. How can you establish internet of things with python & IBM Bluemix?
3. Explain Internet of things using LabVIEW?
—Ž›—Žȱ ˜ȱ ‘’—œȱ ǻ ˜Ǽȱ ǭȱ —Ž›ŠŒ’—ȳ917

ANSWERS

1. IoT can transfer data over a network without requiring human to human or
human to computer interaction.
2. The code acts as a client to IBM Bluemix which enable applications to connect
via MQTT to publish messages.
3. IoT cloud connector uses MQTT protocol to connect any LabVIEW-enabled
equipment to IBM Watson IoT platform and further to Bluemix
Real-time DSP Filters Design Using the
22 LPC1768 ARM Cortex-M3 Microcontroller

OBJECTIVE

After going through this chapter, the students will be able to understand:
Ȋȱ Design and building of DSP filters using ARM mbed microcontrollers and
simulation using LabVIEW.

22.1 INTRODUCTION

The Arm Cortex-M3 processor is the industry-leading 32-bit processor for highly
deterministic real-time applications. It is specifically developed to enable users to develop
high-performance low-cost platforms for a broad range of devices including
microcontrollers, automotive body systems, industrial control systems and wireless
networking and sensors.
Its main features include 512 KB ash memory, 32 KB RAM, up to 100 MHz clock
speed, a 3-stage pipeline and uses the Harvard architecture with separate instruction/
data buses for high speed processing. A feature of importance is the onboard 12-bit
analog to digital converter (ADC), which allows for a theoretical maximum sampling
rate of 200 kHz; this sampling rate is excellent for fast changing signals in real time
applications.
The microcontroller is programmed using a high-level programming language,
namely, C/C++, which gives it an edge over other microcontrollers with regard to ease
of use.
In signal processing, a filter is a device or process that removes some unwanted
components or features from a signal. They also improve signal quality by removing as
much noise as possible while maintaining the signal integrity. Real-time filtering implies
that the characteristics of a filter’s output must be able to change at an instant, when
user changes the input.
There are two types of filters:
Ȋȱ Analog filter
Ȋȱ Digital filter
An analog electric filter operates on continuous variables and is said to be continuous
time. They are constructed using a combination resistor, capacitor or inductor, resistor
and capacitor in series or parallel.
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ919

However, there are many drawbacks of analog filter like:


Ȋȱ Less accuracy.
Ȋȱ Changing a single component could have an adverse effect on its output signal
characteristics.
Ȋȱ Non-linear phase.
Ȋȱ Costly
The alternative is digital filter. It has two categories:
1. Non-recursive filters consist of constant coefficients that multiply present and past
samples of a signal.
2. Recursive filter output at any instant depends on a set of values of the input as
well as a set of values of the output, i.e., it has a feedback loop that send the
output signal back into the input signal.
Digital filter has two types:
Ȋȱ Infinite impulse response (IIR)
Ȋȱ Finite impulse response (FIR)
The FIR filter is characterized by a unit-sample response that has a finite duration
and can be designed with exactly linear phase. Linear phase response is important in
applications where degradation in signal quality and integrity occurs due to a nonlinear
phase distortion.
In this age, microprocessors are used to perform better filtering using mathematical
algorithms with higher speed and accuracy.
A very common method of implementing digital filter is by using DSP chips.
They are extremely flexible.

22.1.1 Implementation

Field Programmable Gate Arrays (FPGA) have advanced to enable digital filtering
implementations at higher sampling rates compared to general purpose DSP chips, lower
costs than ASIC for moderate volume and more design flexibility; this does however
come at the cost of design complexity.
Advanced RISC Machines (ARM) processors are used in many DSP applications
including televisions, mobile phones, computers, watches, household appliances, radio
equipment, electrochemical sensors and many more. The abundant existence of ARM
processors is due to their low cost, high processing power, flexibility and ease of use.
Recently, the ARM Cortex M3 processor was combined with an mbed microcontroller
to enable applications such as DSP in real time and the implementation of complex
control systems.
The following figure shows the chip used in the project:
920ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 22.1

22.1.2 THEORY

Analog filter:
Fourier transform: used for conversion between time and frequency domain.
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ921

The time domain is a representation of how the amplitude of a signal changes over
time. Here we have 4 ways to represent a signal in time domain (continuous and discrete).
Ȋȱ ˜—’—ž˜žœȱ’–Žȱȱ ’‘ȱž—’œȱ›ŠȦœ
x(t) = Acos(Zt + ))
Ȋȱ ˜—’—ž˜žœȱ’–Žȱf with units Hz
x(t) = Acos(2Sft + ))
Ȋȱ ’œŒ›ŽŽȱ’–Žȱȱ ’‘ȱž—’œȱ›Šœ
x[n] = Acos(Zn+ ))
Ȋȱ ’œŒ›ŽŽȱ’–ŽȱŠœȱŠ—ȱ’—Ž¡ȱ
§ 2S ·
x[n] = A cos ¨ k n  ) ¸
© N ¹

Figure 22.2
Time domain represent magnitude of a signal as a function of time and the frequency
domain represents magnitude of a signal as a function of frequency.
Using Fourier transform:
f
X(:) = ³ x(t )e  j:t dt
f

e–jǍt ƽȱŒ˜œǍt Ȯȱœ’—Ǎt


and since sine is an odd function so the sine term vanishes when we integrate it
f
X(:) = ³f
x(t )cos :t dt
922ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

And inverse Fourier transform is given by:


1 f
X(:)e j:t dt
2 S ³f
x(t) =
This is the Fourier transform for continuous signal.
For discrete signals, we use DTFT(discrete time Fourier transform)
f
X(:) = ¦ f
x[n]e  j: n

1
X(:)e j:nd:
S ³ 2 S!
x[n] =

DTFT separates the time signal into its individual frequency components.

Figure 22.3
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ923

Figure 22.4

Although DTFT is reliable for conversion of signal from time to frequency domain,
the inverse DTFT is very time consuming. So an alternative to DTFT is Z-transform.
However before knowing Z-transform we must know about laplace transform: Analog
filters are described using differential equations while digital filters are described using
differential equation. A first order analog filter has one real component, i.e., Resistor
and one reactive component. In our case reactive component is capacitor.

Figure 22.5
924ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

This is a low-pass RC filter.


C
VO = Vi
RC
ic = C dV
dt
1

Vc(t) = i dt

In Laplace domain,
ic = sCVc(s)
1
Vc(s) = i ( s)
SC C
Here,
1
Xc =
SC
So the transfer function becomes,
H(s) = VO(s)/Vi(s)
1 / SC
=
R  1/SC
1
=
1  SRC
where RC is the time constant.
a = 1/W
1
= ...(1)
1  s /a
a
= ...(2)
sa
Equation 1 is the transfer function that describes first order circuit in s-plane.
1
H(s) =
1  s /a
The denominator of a transfer function represents the poles of the system, while the
numerator represents the zeros.
For a system to be stable, all the poles must be on the left half of the s-plane pole-
zero plot.
The problem remains that this function is still a representation of a continuous time
signal. This is where the Z-Transform becomes applicable. The z-plane is related to the
s-plane by z = ŽȹaT. Here T is the sampling period.
Since there is a pole at s = –a, the digital filter will have a pole at z = e–aT.
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ925

Substituting this into equation 1:


1
H(z) = A.
zr
where r = e–aT
A is a gain constant, which can be determined by finding the limit as H(ejǍ) approaches
zero.
A
lim:= 0 H(ej:) = j 0  aT
e e
A
1=
1  e  aT
A = 1 – e–aT
1  e  at
H(z) =
z  e  aT
H(z) is a representation of Y(z)/X(z), where Y(z) is the output of filter and X(z) is the
input of filter.
Y ( z)
H(z) =
X( z )
Y(z)(z – e ) = X(z) (1 – e–Šȹ)
–Šȹ

Y(z) – Y(z) e–aT = X(z) – X(z) e–aT


Y(z) = Y(z) e–aT + X(z) – X(z) e–aT ...(3)
Equation 3 can now be converted into a difference equation for use in the time domain
as follows:
Y(z) = Y (z)e–aT z–1 + X(z)z–1 – X(z)e–aT z–1
y[n] = y[n – 1]e–aT + x[n – 1] – x[n - 1]e–aT
y[n] = ry[n – 1] – rx[n – 1] + x[n – 1]
The final difference equation does not use the input x[n] , therefore adding an optional
zero at origin:
y[n] = ry[n – 1] – x[n](1 – r)
In circuit parameters,
vo[n] = rvo[n – 1] – vi[n](1 – r)
as the completed conversion of the filter from continuous-time analog domain to
discrete-time digital domain.

22.1.3 Sampling Theorem

A continuous time signal can be represented in its samples and can be recovered back
when sampling frequency fs is greater than or equal to the twice the highest frequency
component of message signal, i.e.
fsȱǃȱŘfm.
926ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

There are three types of sampling techniques:


Ȋȱ Impulse sampling.
Ȋȱ Natural sampling.
Ȋȱ Flat Top sampling.

Figure 22.6

Aliasing Effect: The overlapped region in case of under sampling represents aliasing
effect, which can be removed by
Ȋȱ onsidering fs > 2fm
Ȋȱ By using anti-aliasing filters

22.1.4 IIR Digital Filters

IIR filters have a much simpler structure to FIR filters, occupying less storage space,
employ high speed DSP with accuracy and better stability at lower orders.
An IIR digital filter takes a series of of numbers x(0); x(1); x(2); ….x(n) as inputs and
produces a second series of numbers y(0); y(1); y(2);…… y(n) as an output. This is what
is called a linear time invariant filter.
An IIR filter’s outputs depend on the inputs as well as the previous outputs, i.e., it
has feedback loop.
The output y(n) at time n does not only depend on the current input x(n) at time n
and on previous inputs x(n – 1); x(n – 2); …..x(n – N), but also on past outputs y(n – 1);
y(n – 2); …….y(n – M).
This relationship can be expressed as follows:
y(n) = c0xn + c1xn–1 + c2xn–2 + _ _ _ + cNxn–N + d1yn–1 + d2yn–2 + _ _ _ + dMyn–M;
where y(n) is the weighted sum of the current input x(n); the N previous inputs and the
M previous outputs.
ck is the weighted constant of the kth previous input x(n – k).
dk is the weighted constant of the kth previous output y(n – k).
N N
y(n) = ¦ c xn k  ¦ k 0 dk yn k
k 0 k

This is a basic form of recursive IIR function.


ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ927

22.1.5 Basic Low-Pass Filter

A low-pass filter allows frequencies below a given cut-off frequency to pass through it,
while attenuating the higher frequencies.
The focus here will be on a first order filter, which means that there is only one pole
in the real axis at z = r and one zero at z = –1.
The filter of a first order low-pass filter can be expressed as follows:
( z  1)
H(z) = A ( z  r )

(1  z 1 )
= A
(1  rz 1 )
A is the normalization factor chosen as
|H(1)| = 1
So A becomes, (1 – r)/2
r is the normalized value between 0 and 1, representing the location of pole in a unit
circle.
For any filter, the frequency response, that is how a filter responds to various
frequencies, is the magnitude of H(z) along this unit circle.
For a low-pass filter, the frequency response is at a maximum when z = 1 and a
minimum when z = –1, which corresponds to a frequency that is half of the sampling
frequency, namely, the Nyquist Frequency.

1  r (1  z 1 )
H(z) =
2 (1  rz 1 )
So it becomes relatively simple to estimate frequency response magnitude of a filter
by substitution z = ejT
1  r (1  e jT )
H(ejΌ) =
2 (1  re jT )
So,
1  r (1  cos T  j sin T)
H(ejΌ) =
2 (1  r cos T  jr sin T)

(cos T/2)
|H(ejΌ)| = (1  r )
(1  2r cos T  r 2

This is the frequency response of the given filter where T is a dimensionless frequency
representing the size of an angular step along the unit circle.
928ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 22.7

The given figure shows typical frequency response magnitude of a low-pass IIR filter.
It is clear that when r is near 1, the pole draws closer to the unit circle and so the
response’s rate of roll-off drastically increases.
Designing a filter not only requires frequency response characteristics, but also phase
and impulse response characteristics.
For phase response, an ideal filter will have linear phase in the pass band to avoid
phase distortion of the signal.
The phase response for a low-pass filter is given by equation, which is written in
polar form as:
H(ejΌ) = |H(ejΌ)| ej̘
Solving for ),
1 sin T sin T
 ) = tan  tan –1
(cos T  1) (cos T  r )
Here ) is the phase response.
Impulse response is how a filter responds to changes in the input signal that contains
all possible frequencies; its use allows for an extreme idea of how the system will cope
under various frequencies.
To obtain the impulse response of the filter:
(1  z 1 )
H(z) = A
(1  rz 1 )
with z–1 as variable.
Using Taylor series, we can expand it as:
A + Az(r + 1) + Az2(r2 + r) +…..
Substituting z = z–1
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ929

A + A(1 + r) (z–1 + rz–2 +…)


So hn = {A, n = 0
{A(1 + r) rn – 1, n > 0
hn is the impulse response.
Y ( z)
H(z) =
X( z )
(1  z 1 )
= A
(1  rz 1 )
On cross multiplying,
We get, yn – ryn–1 = Axn + Axn–1
yn = ryn–1+ Axn + Axn–1
yn = ryn–1+ A(xn + xn–1)
This is the function to be converted to C code. This completes the design of IIR low
pass filter.

22.1.6 Basic High-Pass Filter

A high-pass filter allows frequencies above a certain frequency to pass, while attenuating
lower frequencies.
Its design is similar to a low-pass filter but now the location of the zeros and poles
have changed in the unit circle.
The location of the zero is at z = 1 and the location of the pole is at z = r.
Its transfer function can be written as:
( z  1)
H(z) = A
(z  r)
(1  z 1 )
= A ...(1)
(1  rz 1 )
A is the normalization factor chosen as
|H(–1)| = 1
So A becomes, (1 + r)/2
r is the normalized value between 0 and 1, representing the location of pole in a unit
circle.
1
H(z) = 1  r (1  z )
2 (1  rz 1 )
So it becomes relatively simple to estimate frequency response magnitude of a filter
by substituting z = ejΌ
(sin T/2)
|H(ejΌ)| = (1  r ) ...(2)
1  2r cos T  r 2 )
930ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

This is the frequency response of the given filter.

Figure 22.8

The phase response for a low-pass filter is given by equation, which is written in
polar form as:
H(ejΌ) = |H(ejΌ)| ej)
˜•Ÿ’—ȱ˜›ȱ̘ǰ
1 sin T sin T
̘ȱƽȱ tan  tan –1
(cos T  1) (cos T  r )
Here ) is the phase response.
Impulse response is how a filter responds to changes in the input signal that contains
all possible frequencies; it use allows for an extreme idea of how the system will cope
under various frequencies.
To obtain the impulse response of the filter:
Using Taylor series, we can expand as:
A + Az(r – 1) – Az2(r2 – r) -…..
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ931

Substituting z = z–1
A + A(1 – r) (z–1 + rz–2 +…)
So hn = {A, n = 0
{A(1 – r) rn–1, n>0
hn is the impulse response.
Y ( z)
H(z) =
X( z )
(1  z 1 )
= A
(1  rz 1 )
On cross multiplying,
We get, yn – ryn–1 = Axn – Axn–1
yn = ryn–1+ Axn – Axn–1
yn = ryn–1+ A(xn – xn–1)
This is the function to be converted to C code. This completes the design of IIR high-
pass filter.

22.1.7 The Bilinear Transform

The bilinear transform is a method of transforming an analog filter into a digital filter
by providing 1-1 mapping from the analog s-plane to the digital z-plane.
The definition of the bilinear transform is given as :
z-1
S= k
z+1
where k = 2/T, T is the sampling period.
Frequencies in the analog domain are represented by s = j:, while frequencies in the
digital domain are represented by z = ejΌ.
In order to convert from analog to digital and vice versa, s and z are substituted into
above equation to produce:
e jT  1
j: = k
e jT  2
j: = jkȱŠ—ǻΌȦŘǼ
: = kȱŠ—ǻΌȦŘǼ
The mapping becomes non-linear as frequency approaches the Nyquist frequency.
To compensate for this, a procedure known as pre-warping is performed,
—ȱ’’Š•ȱ˜–Š’—ǰȱΌȱƽȱZT
where Z is the digital frequency,
: = k tan(ZT/2)
Hence, ΝȱƽȱŘȱŠ—–1ǻǍT/2)
932ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

The mapping between analog frequencies and digital frequencies can be done without
worrying about frequency warping. It is now possible to convert analog frequencies into
digital frequencies and vice versa without any frequency distortion.

22.1.8 FIR Digital Filters

The use of FIR filters in Digital Signal Processing (DSP) applications is more common
due to its excellent stability, ease of design and linear phase properties.
There are however a few drawbacks with the main being the extensive computation
needed to process a signal, thus a large number of multipliers are needed to process
these signals in parallel.
Large number of multipliers occupy much more space and leads to delays in processing
as well as excessive power consumption.
FIR filters, in general, are simpler in design as compared to IIR filters.
Unlike IIR filters, which are obtained by converting continuous time analog filters,
FIR filters are implemented in the discrete time domain.
FIR filters come in various form including: Least Mean Square; Equiripple and
Windowed.

22.1.9 Difference Between FIR and IIR Filters

Ȋȱ FIR filter consumes less power and IIR filter need more power due to more
coefficients in the design.
Ȋȱ IIR filters have analog equivalent and FIR filters have no analog equivalent.
Ȋȱ FIR filters are less efficient while IIR filters are more efficient.
Ȋȱ FIR filters are used as anti-aliasing, low-pass and baseband filters. IIR filters are
used as notch (band stop), band pass functions.
Ȋȱ FIR filter need higher order than IIR filter to achieve same performance. Delay is
more than IIR filter. It has lower sensitivity than IIR filter.

22.2 METHODOLOGY

You must have digital filter design toolkit installed in your labVIEW software in order
to calculate the filter coefficients.
To calculate the coefficient of an butterworth filter:
Step1:
Open the labVIEW software and create a new VI.
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ933

Figure 22.9

Step 2:
Type butterworth coefficients in the search pallete.

Figure 22.10
934ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step 3:
Now place the butterworth coefficients in your VI.
Step 4:
The following icon will appear.

Figure 22.11

Step 5:
Double click on the butterworth icon.

Figure 22.12
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ935

The following window appears.


Step 6:
Enter the sampling frequency and the type of filter

For the lowpass and highpass filter enter only the low cut-off frequency. and for
bandpass and band stop, enter both, i.e., low and high cut-off freqency.
Also enter the filter order and then click the run button. And hence you will get
desired filter coefficients.
Sample coefficients:
Suppose we assume :
Ȋȱ ŠȱœŠ–™•’—ȱ›ŠŽȱ˜ȱŘŖȱ” £ȱ
Ȋȱ ˜ Ȭ™Šœœȱ’•Ž›ȱ’—ȱ’•Ž›ȱ¢™Ž
Ȋȱ ˜ ȱŒžȬ˜ȱ›ŽšžŽ—Œ¢ȱŠœȱŜŖŖȱ £
Ȋȱ ›Ž›ȱř

Figure 22.13
936ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Now we click the run button and output is shown below.

Figure 22.14

The reverse coefficient means that they are the coefficient of output with reverse sign.
And forward coefficient means that they are the coefficient of input.
Hence in this way we get the coefficient of filter.
IIR filter equation

Figure 22.15
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ937

22.3 GETTING STARTED WITH MBED

Mbed is a platform and operating system for internet-connected devices based on 32-bit
ARM Cortex-M microcontrollers. Such devices are also known as Internet of Things
devices. The project is collaboratively developed by Arm and its technology partners.
To get started you need to follow the following steps:
Step 1:
Type mbed on google and go to compiler

Figure 22.16

Step 2:
Create an account and add the chip LPC1768

Figure 22.17
938ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step 3:
Create a new program and give it a suitable NAME

Figure 22.18

Step 4:
Then type the required program in main.cpp.

Figure 22.19

Here as a sample we have created a sine wave using discrete points.


ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ939

Step 5:
Click on the compile button and check whether there are errors or not.

Figure 22.20

Step 6:

Figure 22.21
940ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Step 7:
If you get success then click on show in folder.

Figure 22.22

Step 8:
Copy the given program.
Then attach the chip with your laptop using USB cable and paste the given program.

Figure 22.23
Step 9:
Disconnect the microcontroller chip from USB and see the output in CRO.
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ941

22.4 INPUT AND OUTPUT OF DIGITAL DATA

We can develop an mbed program which reads signal data in via the analog-to-digital
converter (ADC), processes the data digitally and then outputs the signal via the digital-
to-analog converter (DAC). Since DSP algorithms need to sample and process data at
regular fixed intervals, we will use the mbed Timer interrupts to enable a scheduled
program.
Program:
/‫כ‬DSP input and Output
‫כ‬/
#include “mbed.h” //PROGRAM NAME IN MBED adc_to_dac
//mbed objects
AnalogIn Ain(p15);
AnalogOut Aout(p18);
Ticker s20khz_tick;
//function prototypes
void s20khz_task(void);
//variables and data
float data_in, data_out;
//main program start here
int main() {
s20khz_tick.attach_us(&s20khz_task,50); //attach task to 50us tick
}
// function 20khz_task
void s20khz_task(void){
data_in=Ain;
data_out=data_in;
Aout=data_out;
}

Output
First define analog input and output objects (data_in and data_out) and a single Ticker
objects 20khz_tick. There is also function called s20khz_task( ). The main( ) function
simply assigns the 20 kHz Ticker to the 20 kHz task, with a Ticker interval of 50 μs
(which sets up the 20 kHz rate). The input is now sampled and processed at this regular
rate,within s20khz_task( ).
As we program the microcontroller with this program we get the following waveform.
942ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Figure 22.24

Figure 22.25
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ943

Figure 22.26

22.4.1 To Design IIR Low-Pass Filter

Figure 22.27
944ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Here we design a butterworth low-pass filter with the following specifications:


Ȋȱ ŘŖȱ” £ȱœŠ–™•’—ȱ›ŽšžŽ—Œ¢
Ȋȱ ŗŘşȱ £ȱ’—™žȱœ’—Žȱ ŠŸŽ
Ȋȱ ˜ Ȭ™Šœœȱ’•Ž›
Ȋȱ ŗŖȱ £ȱŒžȱ˜ȱ
Ȋȱ ›Ž›ȱř
We will get the filter coefficients generator in labVIEW.

Figure 22.28
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ945

Program for Low-Pass Filter


#include “mbed.h”
AnalogIn Ain(p15);
AnalogOut Aout(p18);
Ticker s20khz_tick;
//function prototypes
void s20khz_task(void);
//variables and data
float data_in, data_out;
//main program start here
int main() {
s20khz_tick.attach_us(&s20khz_task,50); // attach task to 50us tick
}
float LPF(float LPF_in){
float a[4]={1, 2.9937168173,- 2.9874533582, 0.9937365101};
float b[4]={0.00000000386,0.00000001159,0.00000001159,0.00000000386};
static float LPF_out;
static float x[4], y[4];
x[3] = x[2]; x[2] = x[1]; x[1] = x[0]; // move x values by one sample
y[3] = y[2]; y[2] = y[1]; y[1] = y[0]; // move y values by one sample
x[0] = LPF_in; // new value for x[0]
y[0] = (b[0]*x[0]) + (b[1]*x[1]) + (b[2]*x[2]) + (b[3]*x[3])+ (a[1]*y[1])+
(a[2]*y[2]) + (a[3]*y[3]);
LPF_out = y[0];
return LPF_out; // output filtered value
}
//function 20khz_task
void s20khz_task(void)
{
data_in=Ain;
data_out= LPF(data_in);
Aout=data_out;
}
946ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Output

Figure 22.29
Multiplied Output:
Program:
#include “mbed.h”//PROGRAM NAME IN MBED “multiplied”
AnalogIn Ain1(p15);
AnalogIn Ain2(p16);
AnalogOut Aout(p18);
Ticker s20khz_tick;
//function prototypes
void s20khz_task(void);
//variables and data
float data_in1,data_in2,data_out;
//main program start here
int main() {
s20khz_tick.attach_us(&s20khz_task,50); //attach task to 50us tick
}
float multiplic(float LPF_in1, float LPF_in2){
float LPF_out;
LPF_out=LPF_in1*LPF_in2;
return LPF_out;
}
// function 20khz_task
void s20khz_task(void){
float a;
float b;
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ947

data_in1=Ain1;
data_in1=data_in1-0.5f;
data_in2=Ain2;
data_in2=data_in2-0.5f;
data_out= multiplic(data_in1,data_in2);
Aout=data_out+0.5;
}
Output

Figure 22.30

Figure 22.31
948ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

When two signals are multiplied and then passed through a low-pass filter
Here we design a butterworth low-pass filter with the following specifications:
Ȋȱ ŘŖȱ” £ȱœŠ–™•’—ȱ›ŽšžŽ—Œ¢
Ȋȱ ŗŘşȱ £ȱ’—™žȱœ’—Žȱ ŠŸŽȱǻ ˜Ǽ
Ȋȱ ˜ Ȭ™Šœœȱ’•Ž›
Ȋȱ ŗŖȱ £ȱŒžȱ˜ȱ
Ȋȱ ›Ž›ȱř
We will get the filter coefficients generator in labVIEW.

Figure 22.32
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ949

Program:
#include “mbed.h”//PROGRAM NAME IN MBED 10Hz-LPFmultiplied
AnalogIn Ain1(p15);
AnalogIn Ain2(p16);
AnalogOut Aout(p18);
Ticker s20khz_tick;
//function prototypes
void s20khz_task(void);
//variables and data
float data_in, data_out, data_in1, data_in2;
//main program start here
int main() {
s20khz_tick.attach_us(&s20khz_task,50); // attach task to 50us tick
}
float LPF(float LPF_in){
float a[4]={1, 2.9937168173,- 2.9874533582, 0.9937365101};
float b[4]={0.00000000386,0.00000001159,0.00000001159,0.00000000386};
static float LPF_out;
static float x[4], y[4];
x[3] = x[2]; x[2] = x[1]; x[1] = x[0]; // move x values by one sample
y[3] = y[2]; y[2] = y[1]; y[1] = y[0]; // move y values by one sample
x[0] = LPF_in; // new value for x[0]
y[0] = (b[0]*x[0]) + (b[1]*x[1]) + (b[2]*x[2]) + (b[3]*x[3])+ (a[1]*y[1])+
(a[2]*y[2]) + (a[3]*y[3]);
LPF_out = y[0];
return LPF_out; // output filtered value
}
// function 20khz_task
void s20khz_task(void){
data_in1=Ain1;
data_in2=Ain2;
data_in1=data_in1-0.500f;
data_in2=data_in2-0.500f;
data_in= data_in1* data_in2;
data_out= LPF(data_in);
Aout=data_out;
}
950ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Output:

Figure 22.33

Figure 22.34
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ951

22.4.2 High-Pass Filter

When two signals are multiplied and then passed through a high-pass filter
Here we design a butterworth low-pass filter with the following specifications:
Ȋȱ ŘŖȱ” £ȱœŠ–™•’—ȱ›ŽšžŽ—Œ¢
Ȋȱ ŗŘşȱ £ȱ’—™žȱœ’—Žȱ ŠŸŽȱǻ ˜Ǽ
Ȋȱ ‘’‘Ȭ™Šœœȱ’•Ž›
Ȋȱ ŗŖȱ £ȱŒžȱ˜ȱ
Ȋȱ ›Ž›ȱř
We will get the filter coefficients generator in labVIEW.

Figure 22.35
952ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Program:
#include “mbed.h”//HPF-10Hzmultiplied
AnalogIn Ain1(p15);
AnalogIn Ain2(p16);
AnalogOut Aout(p18);
Ticker s20khz_tick;
//function prototypes
void s20khz_task(void);
//variables and data
double data_in, data_out, data_in1, data_in2;
//main program start here
int main() {
s20khz_tick.attach_us(&s20khz_task,50); // attach task to 50us tick
}
float multiplic(float LPF_in1, float LPF_in2){
float LPF_out;
LPF_out=LPF_in1*LPF_in2;
return LPF_out;
}
double LPF(double LPF_in){
float a[4]={1,2.9937168173,-2.9874533582,0.9937365101 };
float b[4]={0.99686333570,-2.99059000709,2.99059000709,-0.99686333570};
static double LPF_out;
static double x[4], y[4];
x[3] = x[2]; x[2] = x[1]; x[1] = x[0]; // move x values by one sample
y[3] = y[2]; y[2] = y[1]; y[1] = y[0]; // move y values by one sample
x[0] = LPF_in; // new value for x[0]
y[0] = (b[0]*x[0]) + (b[1]*x[1]) + (b[2]*x[2]) + (b[3]*x[3])+ (a[1]*y[1])+
(a[2]*y[2]) + (a[3]*y[3]);
LPF_out = y[0];
return LPF_out; // output filtered value
}
// function 20khz_task
void s20khz_task(void){

data_in1=Ain1;
data_in2=Ain2;
data_in1=data_in1-0.500f;
ŽŠ•Ȭ’–Žȱ ȱ ’•Ž›œȱ Žœ’—ȱ œ’—ȱ ‘Žȱ ŗŝŜŞȱȱ ˜›Ž¡Ȭřȱ ’Œ›˜Œ˜—›˜••Ž›ȳ953

data_in2=data_in2-0.500f;
data_in= multiplic(data_in1,data_in2);
data_out= LPF(data_in);
Aout=data_out;
}
Output

Figure 22.36

REFERENCE

1. A Shaikh, Osama (2016). Real time digital filtering using the LPC1768 ARM
Cortex-M3 Microcontroller. 10.13140/RG.2.2-31673.16487.

REVIEW QUESTIONS

1. What difference between FIR & IIR?


2. What are the advantages of digital filters over analog filters?

ANSWERS

1. IIR filters are difficult to control and have no particular phase, whereas FIR filters
make a linear phase. IIR can be unstable whereas FIR is always stable. IIR is
derived from analog whereas FIR has no analog history.
2. A digital filter is programmable. Analog filters can only be changed by redesigning
the circuit.
APPENDIX : LEARN PYTHON SCRIPT
FOR INTERFACING

There are many applications where you want to interface python with a computer.
Python is one language which you may wish to use. This page provides a series of
tutorials( Python class-1 to 21) of code that can be tried out one by one and then use
it to communicate with RS232 and Ethernet devices using RPC and a guide to set up
Python.

PYTHON CLASS – 1

Installation of Python on Wondows Operating System

Steps

1. go to internet browser and type


http//www.python.org/ftp/python/2.6.1/python-2.6.1.msi
2. Now download this installation setup file
3. double click on the file downloaded
4. It will take a few minutes to install… continue till you get finish
5. Now you will see python in start menu as shown below

6. Now open python IDLE (Python GUI)


7. You will see a screen as below
956ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

PYTHON CLASS – 2

Basic Python programming:


Python code can be launched in two basic ways.
1. As a script or
2. inside an interactive interpreter

Use of interactive interpreter

When you open python in IDLE ( python GUI mode) , it enters in to the interactive
mode as shown below
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ957

Now you may type help()


Then the prompt becomes help>
Now type in keywords to know all keywords of python
Further one can type q , if you want to quit or else type the command like “and” or
“or” to get details.
Example 1
Type
Print “ Hello”
>>> print (“Hello”)
Hello
>>>

Example 2

To create a script file , from the python interactive window


Do File -> New Window
Then type in the text of program
Then save as try.py or whatever file name you want to give…
958ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

then click on run -> run module to get the above output on left window

Example 3

Try the following


>>> A=3
>>> B=4
>>> A**B
81
>>> A*B
12
>>> A<B
True
>>> A>B
False
>>>

Example 4

Learn pass
>>> class car:
pass
>>> def function():
pass
>>>
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ959

Example 5

>>> for k in range(5)


print k
0
1
2
3
4
>>>

Example 6

>>> for k in range(5)


print (5-k)
5
4
3
2
1
>>>

PYTHON CLASS – 3

Import modules
import the os module and interact with the operating system

Example 1

>>> import os
>>> os.getcwd()
‘C\\Python26’
>>>
The above example returns current working directory
PL. note that when you type os. ( then hold for a sec) then all the available options
will be displayed as shown below
960ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

example2 comments and function main

# commemts.py
# author jan bodnar
# ZetCode 2008
>>> def main()
print (“comments”)
>>> main()
comments
>>>

what is a variable?
A variable is an identifier, which holds a value. In programming, we say that we assign
a value to a variable. Technically speaking, a variable is a reference to a computer
memory, where the value is stored. In Python language, a variable can hold a string, a
number or various objects like a function or a class. Variables can be assigned different
values over time.
Variables in Python can be created from alphanumeric characters and
underscore _ character. A variable cannot begin with a number. The Python interpreter
can easier distinguish between a number and a variable.
Value
value2
company_name
These were valid identifiers.
12Val
exx$
first-name
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ961

These were examples of invalid identifiers.

Operators

An operator is a symbol used to perform an action on some value.


+ - ~ * ** / %
<< >> & | ^
and or not in not in
is is not < > != <>
== <= >=

Delimiters

A delimiter is a sequence of one or more characters used to specify the boundary between
separate, independent regions in plain text or other data stream.
( ) [ ] { }
, . ` = ;
+= -= *= /= //= %=
<= |= ^= >>= <<= **=
‘ “ \ @
Delimiters are used in various area of the Python language. They are used to build
expressions, string literals, tuples, dictionaries, or lists.

PYTHON CLASS -4

Learn about random randint first!

Example 1

Run the following program


>>> import random
>>> random.randint(0,1)
0
>>> random.randint(0,1)
0
>>> random.randint(0,1)
1
>>> random.randint(0,1)
1
>>> random.randint(0,1)
0
962ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

This means this function some time returns 1 else 0

Example 2

Run the following program


#!/usr/bin/python
# kid.py
import random
male = False
male = bool(random.randint(0, 1))
if (male)
print “We will use name John”
else
print “We will use name Victoria”
RUN MULTIPLE TIMES, THE RESULT WILL LOOK AS FOLLOWS
>>>
We will use name Victoria
>>> ========================== RESTART ===========================
>>>
We will use name Victoria
>>> ========================== RESTART ============================
>>>
We will use name John
>>>

Example 3

Try the following example


#!/usr/bin/python
# boolean.py
print bool(True)
print bool(False)
print bool(“text”)
print bool(“”)
print bool(‘ ‘)
print bool(0)
print bool()
print bool(3)
print bool(None)
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ963

result
True
False
True
False
True
False
False
True
False
>>>
Match the results
special data type – None

Example 4

#!/usr/bin/python
# None.py
def function():
pass
print function()
Result
None
>>>

PYTHON CLASS – 5

Numbers
In Python programming language, we have integer numbers, floating point numbers,
and complex numbers.
If we work with integers, we deal with discrete entities. We would use integers to
count apples.

Example 1

#!/usr/bin/python
# apples.py
# number of baskets
baskets = 16
# number of apples in a basket
apples_in_basket = 24
# we get the total number of apples
total = baskets * apples_in_basket
964ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

print “There are total of”, total, “apples”


Result
>>>
There are total of 384 apples
>>>

Example 2

Floating point numbers represent real numbers in computing. Real numbers measure
continuous quantities. Let’s say a sprinter for 100m ran 9.87s. What is his speed in km/h?
#!/usr/bin/python
# sprinter.py
# 100m is 0.1 km
distance = 0.1
# 9.87s is 9.87/60*60 h
time = 9.87 / 3600
speed = distance / time
print “The average speed of” \
“ a sprinter is “ , speed, “km/h”
Result
>>>
The average speed of a sprinter is 36.4741641337 km/h
>>>

PYTHON CLASS – 6

Strings
String is a data type representing textual data in computer programs. Probable the single
most important data type in programming.
Strings in Python can be created using single quotes, double quotes, and triple quotes.
When we use triple quotes, strings can span several lines without using the escape
character.

Example 1

Try this
>>> a = “proximity alert”
>>> print a
proximity alert
>>> b = ‘evacuation’
>>> print b
evacuation
>>> c = “””
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ965

requiem
for
a
tower
“””
>>> print c
requiem
for
a
tower
>>> d=”””A”””
>>> print d
A
>>>

Example 2
Try \n the ENTER escape character
>>> print “Incompatible, it don’t matter though\n’cos someone’s bound
to hear my cry”
Incompatible, it don’t matter though
‘cos someone’s bound to hear my cry
>>>

Example 3
Try back space escape character
>>>print “Python\b\b\booo”
Pythonooo
>>>
It is supposed to print Pytooo

Example 4
Try this
>>>print “Johnie’s dog”
SyntaxError invalid syntax
>>>

Example 5

How to correct above issue


>>> print ‘Johnie\’s dog’
Johnie’s dog
>>>
966ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Example 6

>> print “eagle has”, len(“eagle”), “characters”


eagle has 5 characters
>>>

Example 7

If we append an r to the string, we get a raw string. The escape


sequences are not interpreted.
>>> print r”Another world\n”
Another world\n
>>>

Example 8

>>> print “eagle “ * 5


eagle eagle eagle eagle eagle

Example 9

Try the following


>>> print “eagle “ “falcon”
eagle falcon
>>>
>>> print “eagle “ + “and “ + “falcon”
eagle and falcon
>>>

PYTHON CLASS – 7

Tuples
A tuple is an immutable sequence data type. The tuple can contain mixed data types.
fruits = (“oranges”, “apples”, “bananas”)

Example 1

>>> fruits = (“oranges”, “apples”, “bananas”)


>>> print fruits
(‘oranges’, ‘apples’, ‘bananas’)
>>> fruits = “oranges”, “apples”, “bananas”
>>> print fruits
(‘oranges’, ‘apples’, ‘bananas’)
>>>
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ967

Example 2

#!/usr/bin/python
# tuples.py
first = (1, 2, 3)
second = (4, 5, 6)
print “len(first) “, len(first)
print “max(first) “, max(first)
print “min(first) “, min(first)
print “first + second “, first + second
print “first * 3 “, first * 3
print “1 in first “, 1 in first
print “5 not in second “, 5 not in second
Result
len(first) 3
max(first) 3
min(first) 1
first + second (1, 2, 3, 4, 5, 6)
first * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3)
1 in first True
5 not in second False

Example 3

Indexing
#!/usr/bin/python
# tuples2.py
five = (1, 2, 3, 4, 5)
print “five[0] “, five[0]
print “five[-1] “, five[-1]
print “five[-2] “, five[-2]
print “five[] “, five[]
print “five[04] “, five[04]
print “five[12] “, five[12]
print “five[2] “, five[2]
print “five[-1] “, five[-1]
print “five[9] “, five[9]
Result
five[0] 1
five[-1] 5
five[-2] 4
five[] (1, 2, 3, 4, 5)
968ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

five[04] (1, 2, 3, 4)
five[12] (2,)
five[2] (1, 2)
five[-1] (1, 2, 3, 4)
five[9] (1, 2, 3, 4, 5)
>>>

Example 4

Mix data types

#!/usr/bin/python
# mix.py
mix = (1, 2, “solaris”, (1, 2, 3))
print “mix[1] “, mix[1]
print “mix[2] “, mix[2]
print “mix[3] “, mix[3]
print “mix[3][0] “, mix[3][0]
print “mix[3][1] “, mix[3][1]
print “mix[3][2] “, mix[3][2]

Result
mix[1] 2
mix[2] solaris
mix[3] (1, 2, 3)
mix[3][0] 1
mix[3][1] 2
mix[3][2] 3
>>>

PYTHON CLASS – 8

Replacing strings

The replace() method replaces substrings in a string with other substrings.

Example 1

>>> a = “I saw a wolf in the forest. A lonely wolf.”


>>> b = a.replace(“wolf”, “fox”)
Result
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ969

>>> print b
I saw a fox in the forest. A lonely fox.
>>>

Example 2

replace(old, new [, max])


By default, it replaces all occurrences of a substring. The
method takes a third argument which limits the replacements to
a certain number.
>>> a = “I saw a wolf in the forest. A lonely wolf.”
>>> c = a.replace(“wolf”, “fox”, 1)
>>> print c
I saw a fox in the forest. A lonely wolf.
>>>

Example 3

>>> a = “I saw a wolf in the forest. A lonely wolf.”


>>> c = a.replace(“wolf”, “fox”, 2)
>>> print c
I saw a fox in the forest. A lonely fox.
>>>
Splitting strings
A string can be split with the split() or the rsplit() method. They return a list of
strings which were cut from the string using a separator. The optional second parameter
is the maximum splits allowed.

Example 4

>>> nums = “1,5,6,8,2,3,1,9”


>>> k = nums.split(“,”)
>>> print k
[‘1’, ‘5’, ‘6’, ‘8’, ‘2’, ‘3’, ‘1’, ‘9’]
>>>

Example 5

>>> l = nums.split(“,”, 5)
>>> print I

[‘1’, ‘5’, ‘6’, ‘8’, ‘2’, ‘3,1,9’]


>>>
970ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Example 6

>>> m = nums.rsplit(“,”, 3)
>>> print m
[‘1,5,6,8,2’, ‘3’, ‘1’, ‘9’]
>>>
JOIN method

Example 7

nums = “1,5,6,8,2,3,1,9”
>>> n = nums.split(“,”)
>>> print n
[‘1’, ‘5’, ‘6’, ‘8’, ‘2’, ‘3’, ‘1’, ‘9’]
>>> m = ‘’.join(n)
>>> print m
15682319
>>>

Partition

Another method which can be used for splitting strings is partition(). It will split
the string at the first occurrence of the separator and return a 3-tuple containing the
part before the separator, the separator itself, and the part after the separator.

Example 8

>>> s = “1 + 2 + 3 = 6”
>>> a = s.partition(“=”)
>>> print a
(‘1 + 2 + 3 ‘, ‘=’, ‘ 6’)
>>>

PYTHON CLASS – 9

Working with case

Example 1

Try this
>>> a = “ZetCode”
>>> print a.upper()
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ971

ZETCODE
>>> print a.lower()
zetcode
>>> print a.swapcase()
zETcODE
>>> print a.title()
Zetcode
>>>
The title() method returns a copy of the string, where the first character is in uppercase
and the remaining characters are in lower case.

Example 2

Try this
sentence = “There are 22 apples”
alphas = 0
digits = 0
spaces = 0
for i in sentence
if i.isalpha()
alphas += 1
if i.isdigit()
digits += 1
if i.isspace()
spaces += 1
print “There are”, len(sentence), “characters”
print “There are”, alphas, “alphabetic characters”
print “There are”, digits, “digits”
print “There are”, spaces, “spaces”

Result
>>>
There are 19 characters
There are 14 alphabetic characters
There are 2 digits
There are 3 spaces
>>>
972ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

PYTHON CLASS – 10

Example 1

Try this
print “Ajax Amsterdam” “ - “ + “Inter Milano “ “23”
print “Real Madridi” “ - “ “AC Milano “ “33”
print “Dortmund” “ - “ “Sparta Praha “ “21”
result
Ajax Amsterdam - Inter Milano 23
Real Madridi - AC Milano 33
Dortmund - Sparta Praha 21

Example 2

Suppose we want output look like this better


>>>
Ajax Amsterdam - Inter Milano 23
Real Madrid - AC Milano 33
Dortmund - Sparta Praha 21
>>>
program would be
teams = {
0 (“Ajax Amsterdam”, “Inter Milano”),
1 (“Real Madrid”, “AC Milano”),
2 (“Dortmund”, “Sparta Praha”)
}
results = (“23”, “33”, “21”)
for i in teams
print teams[i][0].ljust(16) + “-”.ljust(5) + \
teams[i][1].ljust(16) + results[i].ljust(3)
String formatting

Example 3

To do string interpolation, we use the %operator.


>>> print ‘There are %d oranges in the basket’ % 32
There are 32 oranges in the basket
>>>
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ973

Example 4

If we interpolate more values, we put the arguments into a tuple.


>>> print ‘There are %d oranges and %d apples in the basket’ % (12,
23)
There are 12 oranges and 23 apples in the basket
>>>

Example 5

>>> print ‘Height %f %s’ % (172.3, ‘cm’)


Height 172.300000 cm
>>>

Example 6

>>> print ‘Height %.1f %s’ % (172.3, ‘cm’)


Height 172.3 cm
>>>

Example 7

Try this
# hexadecimal
print “%x” % 300
print “%#x” % 300
# octal
print “%o” % 300
# scientific
print “%e” % 300000
Result
>>>
12c
0x12c
454
3.000000e+05
>>>

Example 8

>>> for x in range(1,11)


print ‘%d %d %d’ % (x, x*x, x*x*x)
1 1 1
2 4 8
974ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

Example 9

To look it better
>>> for x in range(1,11):
print ‘%2d %3d %4d’ % (x, x*x, x*x*x)
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>>

PYTHON CLASS – 11

Python lists
Python list is a mutable container. It can contain mixed types. A list is an ordered collection
of values. It represents a mathematical concept of a finite sequence. Values of a list are
called items or elements of the list. A list can contain the same value multiple times.
Each occurrence is considered a distinct item.
List elements can be accessed by their index. The first element has index 0, the last
one has index -1.

Example 1

>>> nums = [1, 2, 3, 4, 5]


>>> print nums
[1, 2, 3, 4, 5]
>>>
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ975

Example 2

Try the following


>>> class Being:
pass
>>> objects = [1, -2, 3.4, None, False, [1, 2], “Python”, (2,
3), Being(), {}]
>>> print objects
[1, -2, 3.3999999999999999, None, False, [1, 2], ‘Python’, (2,
3), <__main__.Being instance at 0x011A8F58>, {}]
>>>
Pl. note that <__main__.Being instance at 0x011A8F58> came when we called the class
Being by Being()
This concept can be more clear when you try the following small example
>>> class first:
pass
>>> object = [first()]
>>> print object
[<__main__.first instance at 0x011A8D28>]
>>>

List initialization

Example 3

>>> n1 = [0 for i in range(15)]


>>> print n1
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>>

Example 4

>>> n1 = [5 for i in range(15)]


>>> print n1
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>>

Example 5

Try following example to initialize with 5 then 10 and 7


>>> n1 = [5 for i in range(15)]
>>> print n1
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
976ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

>>> n1[011] = [10] * 10


>>> print n1
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 5, 5, 5, 5]
>>>
>>> n1[011] =[7] *10
>>> print n1
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 5, 5, 5]
>>>
The list() function
The list() function creates a list from an iterable object. An iterable may be either a
sequence, a container that supports iteration, or an iterator object.

Example 6
>>> a = []
>>> b = list()
see If no parameter is specified, a new empty list is created.
>>> print a == b
True
>>> print list((1,2,3))
[1, 2, 3]
>>> print list(“zetcode”)
[‘z’, ‘e’, ‘t’, ‘c’, ‘o’, ‘d’, ‘e’]
>>> print list([‘Ruby’, ‘Python’, ‘Perl’])
[‘Ruby’, ‘Python’, ‘Perl’]
>>>

Example 7

#!/usr/bin/python
n1 = [1, 2, 3, 4, 5]
n2 = [3, 4, 5, 6, 7]
print n1 == n2
print n1 + n2
print n1 * 3
print 2 in n1
print 2 in n2
result
>>>
False
[1, 2, 3, 4, 5, 3, 4, 5, 6, 7] # This is the result of n1
+ n2
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ977

[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] # This is
the result of n1 * 3
True
False
>>>

PYTHON CLASS – 12

Sequence functions

Example 1
n = [1, 2, 3, 4, 5, 6, 7, 8]
print “There are %d items” % len(n)
print “Maximum is %d” % max(n)
print “Minimum is %d” % min(n)
print “The sum of values is %d” % sum(n)
--------results-----
There are 8 items
Maximum is 8
Minimum is 1
The sum of values is 36
>>>

Example 2
Adding list elements
langs = list() #!An empty list is created using the built-in list() method.
langs.append(“Python”)
langs.append(“Perl”)
print langs
langs.insert(0, “PHP”)
langs.insert(2, “Lua”)
print langs
langs.extend((“JavaScript”, “ActionScript”))
print langs

---results-----------
[‘Python’, ‘Perl’]
[‘PHP’, ‘Python’, ‘Lua’, ‘Perl’]
[‘PHP’, ‘Python’, ‘Lua’, ‘Perl’, ‘JavaScript’, ‘ActionScript’]
>>>
978ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Example 3

IndexError, TypeError
n = [1, 2, 3, 4, 5]
try
n[0] = 10
n[6] = 60

except IndexError, e

print e

results
list assignment index out of range
>>>
index 6 is out of range for our list. An IndexError is thrown.

Removing elements

langs = [“Python”, “Ruby”, “Perl”, “Lua”, “JavaScript”]


print langs

langs.pop(3)
langs.pop()
print langs

langs.remove(“Ruby”)
print langs

Exaplanation

langs.pop(3)
langs.pop()

We take away the element which has index 3. The second line removes and returns the
last element from the list, namely “JavaScript” string.
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ979

Results
>>>
[‘Python’, ‘Ruby’, ‘Perl’, ‘Lua’, ‘JavaScript’]
[‘Python’, ‘Ruby’, ‘Perl’]
[‘Python’, ‘Perl’]
>>>

PYTHON CLASS – 13

Modifying elements
Try following
#!/usr/bin/python
langs = [“Python”, “Ruby”, “Perl”]
langs.pop(2)
langs.insert(2, “PHP”)
print langs
langs[2] = “Perl”
print langs
>>>
[‘Python’, ‘Ruby’, ‘PHP’]
[‘Python’, ‘Ruby’, ‘Perl’]
>>>

Copying lists

Practice the following in command prompt


>>> w = [“python” , “ruby” , “perl”]
>>> c1=w[]
>>> print c1
[‘python’, ‘ruby’, ‘perl’]
>>> c2 = list(w)
>>> print c2
[‘python’, ‘ruby’, ‘perl’]
>>> c3 = copy.copy(w)
>>> print c3
[‘python’, ‘ruby’, ‘perl’]
>>> c4 = copy.deepcopy(w)
>>> print c4
[‘python’, ‘ruby’, ‘perl’]
980ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

>>> c5 = [e for e in w]
>>> print c5
[‘python’, ‘ruby’, ‘perl’]
>>> c6 = []
>>> for e in w
c6.append(e)
>>> print c6
[‘python’, ‘ruby’, ‘perl’]
>>> c7 = []
>>> c7.extend(w)
>>> print c7
[‘python’, ‘ruby’, ‘perl’]
>>>

PYTHON CLASS – 14

Indexing list elements

Elements in a Python list can be accessed by their index. Index numbers are integers;
they start from zero. Indexes can be negative; they refer to elements from the end of
the list. The first item in a list has index 0, the last item has -1.

Example 1

n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[0]
print n[-1]
print n[-2]
print n[3]
print n[5]

>>>
1
8
7
4
6
>>>
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ981

Example 2

The index(e, start, end) method looks for a particular element and returns its
lowest index. The start and end are optional parameters that limit the search to given
boundaries.

n = [1, 2, 3, 4, 1, 2, 3, 1, 2]
print n.index(1)
print n.index(2)
print n.index(1, 1)
print n.index(2, 2)
print n.index(1, 2, 5)
print n.index(3, 4, 8)

>>>
0
1
4
5
4
6
>>>
A code example with the index() method.
print n.index(1)
print n.index(2)
These two lines print the indexes of the leftmost 1, 2 values of the n list.
print n.index(1, 1)
print n.index(2, 2)
Here we search for values 1 and 2 after specified indexes.
print n.index(1, 2, 5)
Finally, we search for value 1 between values with indexes 2-5.
$ ./indexing2.py
0
1
4
5
4
6
Example output.
982ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Slicing

List slicing is an operation that extracts certain elements from a list and forms them into
another list. Possibly with different number of indices and different index ranges.
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[15]
print n[5]
print n[1]
print n[]
>>>
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
We create four slices from a list of 8 integers.
print n[15]
The first slice has values with indexes 1, 2, 3, and 4. The newly formed list is [2, 3, 4,
5].
print n[5]
If the start index is omitted then a default value is assumed, which is 0. The slice is [1,
2, 3, 4, 5].
print n[1]
If the end index is omitted, the -1 default value is taken. In such a case a slice takes all
values to the end of the list.
print n[]

PYTHON CLASS – 15

Traversing lists

This section will point out three basic ways to traverse a list in Python.

Example 1

n = [1, 2, 3, 4, 5]
for e in n
print e,
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ983

print
Result
>>>
1 2 3 4 5
>>>

Example 2

n = [1, 2, 3, 4, 5]
i = 0
s = len(n)
while i < s
print n[i],
i = i + 1
print
Answer
>>>
1 2 3 4 5
>>>

Example 3

n = [1, 2, 3, 4, 5]
for e, i in enumerate(n)
print “n[%d] = %d” % (e, i)
>>>
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5
>>>

The enumerate() built-in function gives us both the index and the value of a list in a
loop.

PYTHON CLASS – 16

Counting list elements


Counting how many times it exits
984ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Example 1

#!/usr/bin/python
n = [1, 1, 2, 3, 4, 4, 4, 5]
print n.count(4)
print n.count(1)
print n.count(2)
print n.count(6)

Result
>>> print n.count(4)
3
>>> print n.count(1)
2
>>> print n.count(2)
1
>>> print n.count(6)
0
>>>

Example 2

Nested lists

This is like a two-dimensional array

Example 3

nums = [[1, 2], [3, 4], [5, 6]]


print nums[0]
print nums[1]
print nums[2]

print nums[0][0]
print nums[0][1]

print nums[1][0]
print nums[2][1]

print len(nums)
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ985

Result
>>>
[1, 2]
[3, 4]
[5, 6]
1
2
3
6
3
>>>

Example 4

nums = [[1, 2, [3, 4, [5, 6]]]]

print nums[0]
print nums[0][2]
print nums[0][2][2]

print nums[0][0]
print nums[0][2][1]
print nums[0][2][2][0]

----------------------------
Result
>>>
[1, 2, [3, 4, [5, 6]]]
[3, 4, [5, 6]]
[5, 6]
1
4
5
>>>

PYTHON CLASS – 17

Sorting lists
986ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Example 1

n = [3, 4, 7, 1, 2, 8, 9, 5, 6]
print n
n.sort()
print n
n.sort(reverse=True)
print n
Answer
>>>
[3, 4, 7, 1, 2, 8, 9, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>

Example 2

n = [3, 4, 1, 7, 2, 5, 8, 6]
>>> print sorted(n)
[1, 2, 3, 4, 5, 6, 7, 8]
>>>

Example 3

Reversing elements
Question
a1 = [“bear”, “lion”, “tiger”, “eagle”]
a2 = [“bear”, “lion”, “tiger”, “eagle”]
a3 = [“bear”, “lion”, “tiger”, “eagle”]
a1.reverse()
print a1
it = reversed(a2)
r = list()
for e in it
r.append(e)
print r
print a3[-1]
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ987

Answer
>>>
[‘eagle’, ‘tiger’, ‘lion’, ‘bear’]
[‘eagle’, ‘tiger’, ‘lion’, ‘bear’]
[‘eagle’, ‘tiger’, ‘lion’, ‘bear’]
>>>
Explanation
n the example, we have three identical string lists. We reverse the elements in three
ways.
a1.reverse()

The first way is to use the reverse() method.


it = reversed(a2)
r = list()
for e in it
r.append(e)
print r

The reversed() function returns a reverse iterator. We use the iterator in a for loop
and create a new reversed list.
print a3[-1]

The third way is to reverse the list using the slice syntax, where the step parameter is
set to -1.
$ ./reverse.py
[‘eagle’, ‘tiger’, ‘lion’, ‘bear’]
[‘eagle’, ‘tiger’, ‘lion’, ‘bear’]
[‘eagle’, ‘tiger’, ‘lion’, ‘bear’]

PYTHON CLASS – 18

The map() and filter() functions

Example 1

def to_upper(s):
return s.upper()
words = [“stone”, “cloud”, “dream”, “sky”]
words2 = map(to_upper, words)
print words2
988ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Ans
>>>
[‘STONE’, ‘CLOUD’, ‘DREAM’, ‘SKY’]
>>>
Explain
The map() function applies a particular function to every element of a list.
def to_upper(s):
return s.upper()
This is the definition of the function that will be applied to every list element. It calls
the upper()string method on a given string.
words = [“stone”, “cloud”, “dream”, “sky”]
This is the list of strings.
words2 = map(to_upper, words)
print words2

The map() function applies the to_upper() function to every string element of the
words list. A new list is formed and returned back. We print it to the console.

Example 2

def positive(x):
return x > 0
n = [-2, 0, 1, 2, -3, 4, 4, -1]
print filter(positive, n)
An example demonstrating the filter() function. It will create a new list having only
positive values. It will filter out all negative values and 0.
def positive(x):
return x > 0
This is the definition of the function used by the filter() function. It returns True or
False. Functions that return a boolean value are called predicates.
Result
>>>
[1, 2, 4, 4]
>>>

PYTHON CLASS – 19

Operators
In Python programming language, we have several types of operators
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ989

Ȋȱ Arithmetic operators
Ȋȱ Boolean operators
Ȋȱ Relational operators
Ȋȱ Bitwise operators
An operator may have one or two operands. An operand is one of the inputs (arguments)
of an operator. Those operators that work with only one operand are called unary operators.
Those who work with two operands are called binary operators.
Example 1
Try the following
>>> 2
2
>>> +2
2
>>> a=1
>>> -a
-1
>>> 3*3
9
>>> 3+3
6
>>> a=b=c=4
>>> print a b c
Syntax Error invalid syntax
>>> print a,b,c
4 4 4
>>>
Arithmetic operators

Example 2

a = 10
b = 11
c = 12
add = a + b + c
sub = c - a
mult = a * b
div = c / 3

pow = a ** 2
print add, sub, mult, div
print pow
990ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

result
>>>
33 2 110 4
100
>>>

Example 3

# division.py
print 9 / 3
print 9 / 4
print 9 / 4.0
print 9 // 4.0
print 9 % 4
Ans
>>>
3
2
2.25
2.0
1
>>>
The example demonstrates division operators.
print 9 / 4
This results in 2. The division operator works differently for integers and for floating
point numbers. Integer division gives an integer result. The fraction part is truncated.
Hence we get 9 / 4 = 2
print 9 / 4.0
Here we get the expected value 2.25. One of the operands is a floating point number,
so the result is a floating point too.
print 9 // 4.0
Python has also a special floor division operator. The result is the floor of the value
returned by true division.
print 9 % 4
The % operator is called the modulo operator. It finds the remainder of division of one
number by another. 9 % 4, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder
of 1.
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ991

PYTHON CLASS – 20

Creating dictionaries

Python dictionary is a container of key-value pairs. It is mutable and can contain mixed
types. A dictionary is an unordered collection. Python dictionaries are called associative
arrays or hash tables in other languages. The keys in a dictionary must be immutable
objects like strings or numbers. They must also be unique within a dictionary.
Example 1
Try following
>>> things = [‘a’, ‘b’, ‘c’, ‘d’]
>>> print things[1]
b
>>> things[1] = ‘z’
>>> print things[1]
z
>>> things
[‘a’, ‘z’, ‘c’, ‘d’]
Example 2
Try following
>>> stuff = {‘name’ ‘Zed’, ‘age’ 39, ‘height’ 6 * 12 + 2}
>>> print stuff[‘name’]
Zed
>>> print stuff[‘age’]
39
>>> print stuff[‘height’]
74
>>> stuff[‘city’] = “San Francisco”
>>> print stuff[‘city’]
San Francisco

Example 3
Try following
>>> stuff[1] = “Wow”
>>> stuff[2] = “Neato”
>>> print stuff[1]
Wow
>>> print stuff[2]
Neato
>>> stuff
{‘city’ ‘San Francisco’, 2 ‘Neato’, ‘name’ ‘Zed’, 1 ‘Wow’,
‘age’ 39, ‘height’ 74}
992ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

Example 4

Try following
>>> del stuff[‘city’]
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{‘name’ ‘Zed’, ‘age’ 39, ‘height’ 74}

Example 5

Try following
# create a mapping of state to abbreviation
states = {
‘Oregon’ ‘OR’,
‘Florida’ ‘FL’,
‘California’ ‘CA’,
‘New York’ ‘NY’,
‘Michigan’ ‘MI’
}
# create a basic set of states and some cities in them
cities = {
‘CA’ ‘San Francisco’,
‘MI’ ‘Detroit’,
‘FL’ ‘Jacksonville’
}
# add some more cities
cities[‘NY’] = ‘New York’
cities[‘OR’] = ‘Portland’
# print out some cities
print ‘-’ * 10
print “NY State has “, cities[‘NY’]
print “OR State has “, cities[‘OR’]
# print some states
print ‘-’ * 10
print “Michigan’s abbreviation is “, states[‘Michigan’]
print “Florida’s abbreviation is “, states[‘Florida’]
# do it by using the state then cities dict
print ‘-’ * 10
print “Michigan has “, cities[states[‘Michigan’]]
print “Florida has “, cities[states[‘Florida’]]
# print every state abbreviation
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ993

print ‘-’ * 10
for state, abbrev in states.items()
print “%s is abbreviated %s” % (state, abbrev)
# print every city in state
print ‘-’ * 10
for abbrev, city in cities.items()
print “%s has the city %s” % (abbrev, city)
# now do both at the same time
print ‘-’ * 10
for state, abbrev in states.items()
print “%s state is abbreviated %s and has city %s” % (
state, abbrev, cities[abbrev])
print ‘-’ * 10
# safely get a abbreviation by state that might not be there
state = states.get(‘Texas’)
if not state
print “Sorry, no Texas.”
# get a city with a default value
city = cities.get(‘TX’, ‘Does Not Exist’)
print “The city for the state ‘TX’ is %s” % city

Answer
----------
NY State has New York
OR State has Portland
----------
Michigan’s abbreviation is MI
Florida’s abbreviation is FL
----------
Michigan has Detroit
Florida has Jacksonville
----------
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
----------
FL has the city Jacksonville
CA has the city San Francisco
MI has the city Detroit
994ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

OR has the city Portland


NY has the city New York
----------
California state is abbreviated CA and has city San Francisco
Michigan state is abbreviated MI and has city Detroit
New York state is abbreviated NY and has city New York
Florida state is abbreviated FL and has city Jacksonville
Oregon state is abbreviated OR and has city Portland
----------
Sorry, no Texas.
The city for the state ‘TX’ is Does Not Exist
>>>

PYTHON CLASS – 21

Operators contd…

Example 1

Try following

>>> ‘return’ + ‘of’ + ‘the’ + ‘king’


‘returnoftheking’
>>> str(3) + ‘ apples’
‘3 apples’
>>> ‘dollar ‘ * 5
‘dollar dollar dollar dollar dollar ‘

Example 2

print True and True


print True and False
print False and True
print False and False
>>>
True
False
False
False
>>>
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ995

Example 3

print not False


print not True
print not ( 4 < 3 )
>>>
True
False
True
>>>

Example 4

Analyse the following example


x = 10
y = 0

if (y != 0 and x/y < 100)


print “a small value”
and compare the answer of above program with following program
x = 10
y=1
if (y != 0 and x/y < 100)
print “a small value”
Ans in this case
>>>
a small value
>>>
Note: Short circuit evaluation means that the second argument is only evaluated if the
first argument does not suffice to determine the value of the expression when the first
argument of and evaluates to false, the overall value must be false; and when the first
argument of or evaluates to true, the overall value must be true.

PYTHON CLASS – 22

Plotting data, Try following

Example 1

import matplotlib.pyplot as plt


plt.plot([1,2,3,4])
plt.ylabel(‘some numbers’)
plt.show()
996ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you
provide a single list or array to the plot() command, matplotlib assumes it is a sequence
of y values, and automatically generates the x values for you. Since python ranges start
with 0, the default x vector has the same length as y but starts with 0. Hence the x data
are [0,1,2,3].

Example 2

import matplotlib.pyplot as plt


plt.plot([1,2,3,4], [1,4,9,16], ‘ro’)
plt.axis([0, 6, 0, 20])
plt.show()
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ997

PROJECTS ON INTERFACING

Example 1
PYTHON AND RS232 INTERFACING

Code to read data from a serial device which is continuously transmitting data
import serial
import time
ser = serial.Serial(
port = ‘COM18’,
baudrate = 2400,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE
#serial.LF
)
while ser.isOpen()
datastring = ser.readline(20)
print float((datastring))
time.sleep(1)
ser.close()

Example 2

PYTHON AND ETHERNET HTTP CLIENT INTERFACING

Interfacing a device server running an http server using Python


AIM To read the data coming out from a device through Ethernet using Python language.
998ȳ˜–™žŽ›ȱ —Ž›ŠŒ’—ȱ Š—ȱž˜–Š’˜—

PROGRAM
import httplib as ht //defines classes which implement the client side of the HTTP and HTTPS
protocols
import urllib2 //defines functions and classes which help in opening URLs (mostly HTTP)
import time //provides various time-related functions
while True
try
req= urllib2.Request(“http//192.168.1.11/rpc/vdata/read”)
resp= urllib2.urlopen(req)
data=resp.read()
datastr=str(data)
print int(datastr,10)*10 //converting the string into integer with base 10
print float(datastr)*10 //converting the string into float
time.sleep(2) //Suspend execution for the given number of seconds
print time.ctime()
except ht.BadStatusLine
pass
print”ERROR”
The try statement works as follows.
Ȋȱ First, the try clause (the statements between the try and except keywords) is
executed.
Ȋȱ If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
Ȋȱ If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then if its type matches the exception named after the except keyword,
the except clause is executed, and then execution continues after the try statement.
Ȋȱ If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer try statements.
™™Ž—’¡ȱ DZȱ ŽŠ›—ȱ ¢‘˜—ȱ Œ›’™ȱ ˜›ȱ —Ž›ŠŒ’—ȳ999

OUTPUT
INDEX

488.2 standard 641 ATMEGA168, ENCJ60 RJ45 hardware


8-bit ATMEL based embedded servers 693 interface 688
8-BIT ethernet interfaces 760 Automatic CAM 143
9600,N,8,1 in, meaning of 99 Automatic device-health checker 705
Auto-switching link 225
A ȱꛖ Š›Žȱ‹˜˜ȱ•˜ŠŽ›œȱŗśŘ
Accurate water heater system design 195
AVR in-system programming 150
ADAM-4024 273
ADAM-4117 273 B
ADAM-4520 274 Basic high-pass filter 929
ADC interface signals 616 Basic ladder programming 323
Address resolution protocol 750 Basic low-pass filter 927
Advanced embedded systems using 32-bit Basic semaphore 125
ARM mbed 446
Baud rate 31
Advanced HTTP server library 126
Bilinear transform method 931
Advanced robust GPIB communication 664
Advanced, robust RS232/ISOBUS Binary to hex generation 153
communication 665 Boot loading firmware 152
Agilent 34420A nanovoltmeter 68, basic Browsers, working of 749
framework of 667
Analog capture circuit 614
C
C++ 488
Analog PID 190
C++ environment setup 371
Analog to digital converter (ADC) 615
Analog vs digital PID 193 CAMAC 448
advantages 193 CAMAC crate 561
Analog vs digital PID controller 193 CAMAC modules, use of 572
App inventor 843-883 Channel test signals 28
installing of 843 CISCO 300-28 725
tutorials on 743-882 CISCO network switches 725
Arm Cortex-M3 processor 918 Command message 577
ȱꛖ Š›Žȱ‹˜˜ȱ•˜ŠŽ›œȱŗśř Command/reply message sequences 580
ARM in-system programming 150 Compact RIO architecture 792
ARP (address resolution protocol) analysis 719 Compact RIO scan mode 801
ASCII commands 40 Complex programming instruction set
Asynchronous transmission 34 computer 132
1002ȳ —Ž¡

Computer automated measurement and control DTE (data terminal equipment) 225
(CAMAC) 548 DTE to DCE communication 19
advantages of 551
basic features of 550 E
number of lines in 550 EKI-1524 239
use 550 EKI-152X series serial device servers 265
Controller-area network (CAN) 769 Electrical interface 635
advantages and disadvantages of 782 Electrical standards 36
applications 780 Electromechanical relays 528
benefits 779 Electronic memory 139
bus arbitration 773 Embedded web server 744
bus cabling 775 Error detection 32
Ethernet challenge 782
bus description 774
External memory, in-system programming
bus node 771
of 151
future of 783
history 770 F
operation of 772 Feedback test 786
with ethernet backbone 776 Field-programmable gate arrays (FPGAs) 589
working of 770 architecture 591
Controllers, types of 203 components and features 599
Crate 561 configuration options 605
serial connection of 574 design and programming 594
merits and demerits of 598
D Filters 747
DAC interface signals 611 FIR digital filters 932
Data acquisition module 242 Firmware
Data bit 31 for digital PID control 194
Data circuit-terminating equipment (DCE) 16, 96 Flash magic 154
Data terminal equipment (DTE) 16, 96 Formatting bytes 579
Dataway 554 Free online development tools 411
Dataway lines 556 FT232R USB UART IC 138
DCE (data communications equipment) 225 Full-duplex devices 219
Demand message 578 Full-duplex operation 33
DHCP server 450
G
Digital data, input and output of 941
GPIB bus controllers 644
Digital I/O FPGA 804 GPIB cables 645
Digital outputs from analog inputs 615 GPIB command concept 647
Digital PID control code 205 GPIB
Digital PID controller 192 connecting instruments 666
Digital to analog converter 610 error processing 648
Digital transmission, RC pulse distortion 5 hardware and software options 653
Domain name 509 history and concept 638
Driver circuits 517 origin of 653
Driver ICs 519 overview of 652
DSC module 251 writing programs 647
—Ž¡ȳ1003

GPIB controller card 648 I


GPIB controller initialization 648 I/O modules 793
GPIB data bus, description of 637 IBM Bluemix 888
GPIB devices 645 IBM Watson platform 890
GPIB instrument control 652 IC, types and components 35
GPIB instrument control system 652 IEEE-488 interface bus (HP-IB/GP-IB) 634
GPIB interface messages 639 interface messages and addresses 640
GPIB interface, functions of 636 physical bus structure 640
Gratuitous ARP 752 IGBTs 523
GUI 488 IGOR signal lines 569
GUI programs 487 IIR digital filters 926
IIR Filters 932
H
Industrial automation systems 537
Half-duplex devices 219
IN-system programming 146
Half-duplex operation 33
Intel hex file 159
Handshaking (flow control) 23
Interactive keyboard control programs 646
Hard drivers 517
—Ž›—Š•ȱ̊œ‘ȱ–Ž–˜›¢ȱȱŗŚŜ
Hardware and HTML coding 736
Internet networking 507
Hardware cots design (component level) 135
Internet of things (IoT) 885
Hardware development kit (HDK) 411
using LabVIEW 913
Hardware flow control 23
using Python 903
Hardware handshaking 23
IO graph analysis 722
H-bridge driver ICs 524
IP address 510, 511
Higher power SSRs 537
parts of 511
Highway 554
IP forwarding 512
Highway D ports 583
Isolated link 225
HMI-PLC based automation system 365
Home automation systems 539 K
Honeywell PID controller 277 Keithley 2612A Source Meter 684
HP-IL variation 638 basic framework of 685
HTTP analysis 717 interfacing commands of 685
HTTP client in Python 735 KEPserver 363
HTTP data drop checker 705
L
HTTP protocol 713, 744
LabVIEW 105, 107, 792, 795
HTTP server 762
HTTP success codes 719 basic example of 110
HTTP benefits of 248
analyzing errors in 718 Ctl ꕎ in 125
design of an embedded automation network for modbus communication 246
of 703 in FPGA 796
HUBS 747 interfacing devices using 663
Hyper terminal 157 LabVIEW FPGA Interface mode 801
1004ȳ —Ž¡

LAKE SHORE 335 temperature controller 686 N


LED driver ICs 527 NI 9381 794
Level shifter 40 Null modem cable 20, 98
Limitations of 12 Null modem cable 98
Low-power link 223
O
LPC1768 ARM chip
Optical isolation 533
applications of 168
features of 167 P
LPC1768 mbed ARM board 163, features & PACs 537
terminologies 412 Pages 745
Ludlum model 375 area monitor 51 Parallel transmission 3
Parity bit 32
M Parity system, disadvantages of 33
MATLAB and embedded systems 169 PCB Design 141
MATLAB code 170 PID control scheme 191
MATLAB RPC library 170 Ping 507
Mbed and programming interrupts 416 PLL synthesizers 137
Mbed web server 766 Plug-in units (CAMAC modules) 565
Media access control 746 Power switches 541
Memory function, types of 443 Pressure server 755
Message fields 578 Programmable logic controller (PLC) 321
Message structure 575 Proportional control theory 195
Micro memory 144 Proportional integral control 196
Microcontroller 133 Proportional integral derivative (PID) 190
advantages of 135 Protocols (RS232/485/422) 220
MicroLogix 1000 programmable logic controller Proxy ARP 752
systems 352 PWM control 518
PWM, advantage of 208
MicroLogix 1400 programmable logic controller
Python and ethernet HTTP client
systems 353
interfacing 997
Microprocessor 131, 443 Python script 955
Modbus message format 228
Modbus messages 228 Q
Modbus serial device server 235 Qt 487, 690, 728
basic concepts 728
features 237
source code in 698
specifications 237
Qt creator 488
Modbus TCP/IP, advantages of 234
Qt designer 489
Modbus transmission modes 230
Mode jumpers 607 R
MOSFETs 521 Random access memory (RAM) 140
MSComm control 42 Read only memory (ROM) 140
MSComm properties 43 types of 141
Multiple CAN 788 Real-time controller 793
—Ž¡ȳ1005

Receiver timing signals 28 Serial transmission 3


Reconfigurable I/O FPGA 793 versus parallel data transmission 4
Reduced instruction set computer (RISC) 133 SH (serial highway) 574
Reed relays 531 Short-circuit protection 224
Reflow soldering process 143 Signal characteristics 37
Signal state voltage assignments 39
Relays 527
Simple GPIB communication 664
Remote procedure call (RPC) server 765
Simple RS232 communication 665
Reply message 577
Simplex device 219
RFID (radio frequency identification) 56
SMD BGAs 136
RFID reader 57 SMD resistors 135
Router 514 Software 690
RS-232, 254 Software development kit (SDK) 411
bit format 22 Software handshaking 29
cable length 11 Solid state relays 532
functional characteristics 10 Spartan-3e FPGA family 595
interfacing of instruments 51 Spartan-3E kit 598
length & speed of 101 Special purpose driver ICs 524
mechanical interface characteristics 10 SPI programming with 32-bit microcontroller
protocol 31-32 ARM mbed 473
serial communication 1 SSR modules 535
Start bit 31
serial ports 609
Stepper motor driver ICs 526
shortcomings of 95
Step-voltage input 5
standard 8
Stop bit 32
serial port /com port 665 Straight cable 97
RS-422 14 Switches 747
RS-485 14 Synchronous transmission 34
RS-485 basics 221 advantages and disadvantages of 35
RS-485 standard 219
T
S TCP analysis 714
Sawtooth wave 210 TCP connection 767
SCADA (supervisory control and data TCP protocol 743
acquisition)286 TCP state machine 743
TCP/HTTP webserver 713
SCPI
TCP/IP implementation in microprocessors/
bus controllers 644 microcontrollers 739
command structure 643 TCP/IP stack 738
commands 642 TCP/IP stack, microprocessor 740
error reporting 644 TeamViewer 515
variables and channel lists 643 Tera term 157
Secondary/non-volatile memory 140 Three-phase induction motor 340
Serial communication 1 Timers and 32-bit ARM mbed
Serial data, transmitting and receiving 7 programming 480
Serial standards 13 Transmission control protocol 740
specifications of 15 Transmitter 28
1006ȳ —Ž¡

U Web server 508


UART, features 8 WEB-DAC 753
UDP 742 Wi-fi network 512
UDP header 743 Wi-fi routers 747
Universal asynchronous receiver/transmitter 6 Wireshar 702
URL 745 Wonderware intouch SCADA 287, 361
USART (Universal Synchronous/ properties of 287
Asynchronous Receiver Transmitter) 101
trends in 309
User data gram protocol 740
Worldwide developer community 411
V
X
VFD, working of 341
XC3S500E FPGA chip 596
VME bus 584
XILINX ISE webpack 11.1 617
advantages of 585
configuration 618
Volatile memory 140
implementation 619
W steps for simulation 619
Wave form reference library 835 support 618
WEB client 748 XON/XOFF protocol 29
Computer Interfacing and Automation
TM

Computer Interfacing

Computer Interfacing and Automation


and Automation

978-81-947787-8-3

Distributed by:

9 788194 778783 TM

You might also like