Skip to main content

Full text of "Embedded Programming"

See other formats


Jivan S. Parab 
Vinod G. Shelake 
RajanishK.Kamat 
Gourish M. Naik 



A Hands on Approach 



EXPLORING C FOR MICROCONTROLLERS 



Exploring C for Microcontrollers 

A Hands on Approach 



JIVAN S. PARAB 

Goa University 
India 



VINOD G. SHELAKE 

Shivaji University 
Kolhapur, India 

RAJANISH K. KAMAT 

Shivaji University 
Kolhapur, India 

and 

GOURISH M. NAIK 

Goa University 
India 



4y Springer 



A C.I. P. Catalogue record for this book is available from the Library of Congress. 



ISBN 978-1-4020-6066-3 (HB) 
ISBN 978-1-4020-6067-0 (e-book) 



Published by Springer, 

P.O. Box 17, 3300 AA Dordrecht, The Netherlands. 

www. springer, com 



Printed on acid-free paper 



All Rights Reserved 

© 2007 Springer 

No part of this work may be reproduced, stored in a retrieval system, or transmitted 

in any form or by any means, electronic, mechanical, photocopying, microfilming, recording 

or otherwise, without written permission from the Publisher, with the exception 

of any material supplied specifically for the purpose of being entered 

and executed on a computer system, for exclusive use by the purchaser of the work. 



Contents 



Foreword ix 

Preface xiii 

Acknowledgments xvii 

1 

Microcontrollers: Yesterday, Today, and Tomorrow 1 

1.1 Denning Microcontrollers 1 

1.2 Eagle's View: Microcontrollers and Other Competing Devices 2 

1.3 Vignettes: Microcontrollers 3 

1.4 Microcontroller Applications 5 

1.5 Growth Economics 7 

1.6 The Major Players in the Microcontroller Chip Market 8 

1.7 Architectural Trends 10 

1.8 Jump Starting Your First Embedded System Project 14 

1.9 Execution of Embedded System Project: Is it a 

Gordian's Knot? 16 

2 

Integrated Development Environment 19 

2.1 Getting Familiar with the IDE 19 

2.2 Working with Keil IDE 20 

2.3 Development Flow for the Keil IDE 21 

3 

Art of C Programming for Microcontrollers 29 

3.1 Familiarizing with Your Compiler Capabilities 29 

3.2 Whether to Use Headers or Not? 30 

3.3 Basic C Program Structure 34 

3.4 Differences from ANSI C 34 



vi Contents 



Exploring the Capabilities of On-Chip Resources Programming 37 
for I/O Ports, Interrupts and Timer/Counter 

4.1 Importance of Ports 37 

4.2 Simple Ideas for Port Expansion 46 

4.3 LED Interfacing 46 

4.4 Relevance of LEDs in Today's Lightening Industry 48 

4.5 Different Programs for LED Interfacing 48 

4.6 More Projects on LED Interfacing to Microcontrollers 51 

4.6.1 Running LEDs 51 

4.6.2 Running Bicolor LED 51 

4.6.3 Interfacing 6 LEDs 

Using 3 Microcontroller Pins by 51 

4.6.4 The LED Dimmer Demoboard 51 

4.6.5 Fading RGB LED 52 

4.6.6 LED Moving Font 52 

4.7 DIP Switch Interfacing: Getting Input to Your 

Embedded System 52 

4.8 LCD Interfacing 54 

4.9 Interrupts in Microcontrollers 57 

4.9.1 Writing ISRs in C 58 

4.9.2 A Word about Interrupt Latency 63 

5 

Hyperterminal-Based Control 69 

5.1 Hyperterminal 69 

5.2 Packet-based Control Scheme 69 

5.3 Mechanism and Lots of Possibilities 70 

5.4 Application 1: Packet-based Interface for LEDs 71 

5.5 Application 2: Packet-based Interface for Stepper 

Motor Control 74 

5.6 Application 3: Home Automation from PC HyperTerminal 78 

6 

Embedding Microcontroller in Routine Applications 85 

6.1 Application 1: Podium Timer 85 

6.2 Application 2: Front Desk Notifier 90 

6.3 Application 3: Cafeteria Food Alert/Microcontroller-based 
Menu Card 94 

6.4 Application 4: Chimney Sentinel 100 

6.5 Application 5: Who's First Timer 104 



Contents vii 

6.6 Application 6: Counting Cars 110 

6.7 Application 7: Anonymous Voting 114 

6.8 Energy Efficient Lighting Using Microcontroller 119 

7 

Microcontroller-based Measurement and Control Applications 123 

7.1 Application 1: Reading a PWM Waveform Using 
Microcontroller 123 

7.2 Single Set-point On/Off Controller 127 

7.3 Application 3: I 2 C Interface with Serial EPROM 133 

8 

Securing Your Embedded System Application 139 

8.1 Security Challenges in Embedded Systems 139 

8.2 Application 1: Authentication for Your Embedded 

System Application 140 

8.3 Application 2: Timeout Waiting for Input Data 144 

References 151 

Index 155 



Foreword 



If we accept the premise that an embedded engineer is made rather 
than born, then how does one go about making a good one? The authors 
of this book Exploring C for Microcontrollers: A Hands-on Approach are 
certainly "good ones" . Not only do they explore some of the influences 
that shaped themselves but they also try to shape "would-be" embedded 
engineers. Research and developmental activities in embedded systems 
has grown in a significant proportion in the recent past. Embedded soft- 
ware design is not new to the world, but with the changing time, it 
has gained considerable momentum in the recent past, and many young 
engineers are strongly inclined to pursue their future in this field. The 
book is mainly targeted to these engineers who would like to understand 
in great depth the synergetic combination of hardware and software. 

The book is divided into eight chapters. Chapter 1 introduces a brief 
background about micro-controllers and explains how they are embed- 
ded into products commercially available in the market to emphasize the 
importance of these in the daily life of mankind. It also gives an insight 
into the architectural details and embedded system concepts for stu- 
dents' projects to motivate them into this exciting field. The rest of the 
book concentrates on software development. The integrated development 
environment (IDE) is introduced in Chapter 2. Again the screen shots 
and step-by-step procedure will certainly make the students and engi- 
neers fully understand the development process. Chapter 3 differenti- 
ates the embedded C paradigm from the conventional ANSI C. Again 
the authors explain how to successfully overcome the memory and time 
constraints while developing an embedded C program. Chapter 4 gives 
an overview of program development for on-chip resources for MCS51 
family of microcontrollers. Chapters 5-8 are devoted to live case studies. 

The book has come out with an elegant presentation to aspiring 
students and engineers from the teaching experience and technical 
knowledge the authors have put over a long time in this field. I strongly 
recommend this book for intermediate programmers, electronics, electri- 
cal, instrumentation engineers or any individual who is strongly inclined 



IX 



x Foreword 

to take up his or her career in embedded C programming. I am sure the 
reader will experience learning embedded programming by example and 
learning by doing. Last but not the least, this book will certainly be a 
value addition to the world of embedded programming. 

Dr. A. Senthil Kumar 

Head 

Data Quality Evaluation 

National Remote Sensing Agency 

Department of Space 

Government of India 

Dr. Senthil Kumar is Head of DQE and PQCD sections of National 
Remote Sensing Agency (NRSA) an autonomous operational center 
under Department of Space (DOS), Government of India. This is the 
nodal agency in the country for receiving, processing, and distributing 
the satellite and aerial remote sensing data and products. NRSA is also 
responsible for providing end-to-end solutions for utilization of data 
for geospatial applications and information services. NRSA has a huge 
archive of remote sensing data acquired through Indian and foreign 
satellites and also has the capability to acquire data pertaining to any 
part of the globe on demand. It is one of the important centers for 
promotion of remote sensing and geographic information system tech- 
nologies in India. NRSA has set up satellite data processing facilities 
starting from data reception to utilization at various centers within 
India and across the globe. 



Preface 



The past few decades have witnessed evolution of microcontrollers. 
They have revitalized a number of products or equipment in almost all 
fields including telecommunications, medical, industrial, and consumer 
products. These embedded microcontroller systems now resides at the 
heart of modern life with a variety of applications in fields like con- 
sumer electronics, automotive systems, domestic, and even in aerospace 
products. Embedding a microcontroller in an electronics instrument or 
product requires a specialized design skill which requires a synergy of 
hardware and software skills. 

In our day-to-day life we come across a number of embedded products. 
When we switch on the washing machine or send an SMS on a cell phone 
one cannot prevent without thinking the mechanism and the co-working 
of hardware and software in the background. The market for such smart 
embedded products is occupying newer and newer applications seem- 
ingly impossible few years back. Last year the IDC, a premier global 
market intelligence firm, revealed that the embedded industry product 
development was expected to be as high as $75 billion. This entails the 
industry requirement of trained human resource with mixed skill set 
both in hardware and software. Unfortunately the synergetic demand 
of hardware and software or sometimes even referred to as firmware 
competency has led to a supply-demand gap of HR in this field. This 
gap expressed in numerical figures led to requirement of around 150,000 
embedded engineers to serve the global embedded industry. This book 
is ideal for all those who would like to pursue their career in the exciting 
world of microcontroller-based embedded systems. The approach is ped- 
agogical; first the hardware module is presented and then the associated 
software code in Keil C. 

The hardware designed is useful for engineering graduates and prac- 
ticing professionals with the required knowledge and practical hands on 
skills to design with embedded systems. However, the prerequisite for 
the book is background of theoretical aspects of architecture of micro- 
controllers especially the MCS-51 family. The book starts with initial 



XI 



xii Preface 

experiments, which provide familiarization with the capabilities and the 
limitations of the basic 8051 microcontroller using a simulator. Once the 
reader is comfortable with these primitive programs which covers almost 
all the on-chip resources, he or she can switch to more advanced ones. 

The Scope of the Book 

We now review the topics covered in sequence, chapter by chapter. 

Chapter 1 provides an overview of microcontrollers and their appli- 
cations in different domains. The architectural trends and the growth 
economics emphasizes the importance of the subject. The photograph of 
the setup and the hints toward project execution will definitely boost the 
confidence of the novice to kick-start the project with minimal resources. 

Chapter 2 is devoted to the IDE for the MCS-51 family. The simulation 
and single stepping as described in this chapter will solve all the project 
intricacies of the readers. Chapter 3 illustrates the basic difference in 
traditional C programming and embedded C. Chapter 4 deals with the 
programming of on-chip resources of MCS-51 family microcontrollers 
in C. The theoretical details of these on-chip resources such as ports, 
timers, etc., are completely eliminated. As the book aims at hands-on 
approach, the programs for the on-chip resources have been developed 
and their execution is illustrated in the Keil simulation environment. 

The last four chapters, i.e., 5-8 deal with various project case stud- 
ies. Several case studies in various application domains such as lighting, 
measurement and control, security, and domestic applications are devel- 
oped from scratch. The hardware and software developed in the form of 
case studies also caters to a set of mini projects, which are discussed in 
detail from the design phase to the actual implementation on a target 
system. There are 17 case studies given in this book on various systems 
that you may encounter in day-to-day life. Overall the hardware and 
software developed in this book can be reused for any embedded sys- 
tem project and is expected to act as a rapid prototyping unit for the 
embedded systems industry. 

Reasons for Proposing this Book 

The market is flooded with a number of good books on embedded sys- 
tems designed especially with the most popular MCS-51 family. These 
books are traditional in nature, i.e., they start with the routine archi- 
tectural features of 8051, description of registers, ports, interrupts, etc. 
Most of these are already covered in the device data sheet and appli- 
cation notes. In the present book all such routine features are skipped. 
The focus is on programming microcontrollers to be specific MCS-51 



Preface xiii 

family in 'C using Keil IDE. The book presents 20 live case studies 
apart from the many basic programs organized around every on-chip 
resource like port, time/counter, interrupt, serial I/O, etc. Rather than 
introducing the underpinning theory or reproducing lengthy data sheets, 
our approach is "learning-through-doing" and one that appeals to busy 
electronics designers. The 'C codes given are well supported by easy-to- 
understand comments wherever required. Mastering the basic modules 
and hands-on working with the projects will enable the reader to grasp 
the basic building blocks for most 8051 programs. Whether you are a 
student using the MCS-51 family of microcontrollers for your project 
work or an embedded systems programmer, this book will give you a 
kick start in using and understanding the most popular microcontroller. 
Authors through their interaction with the undergraduate and post- 
graduate students as well as industry professionals have found that such 
a book is the need of the microcontroller community interested in C 
programming. The book will bridge the gap between the microcontroller 
hardware experts and the C programmers. 

Major Features 

The objective of this book is to introduce the readers to the design 
and implementation of an embedded system. It covers the unique require- 
ments and limitations of operating in an embedded environment. It also 
covers microcontrollers as the most widespread example of embedded 
systems. In particular, it focuses on the MCS-51 family of microcon- 
trollers, their programming in C language, and interfacing techniques. 

Special emphasis is to provide hands-on experience for the readers 
using a hardware and interfacing modules described in this book. The 
aim is to empower the reader to actually solve his or her problem with 
a practical hands-on pedagogy through the hardware and software pre- 
sented in this book. The principle of "Design Reuse" is explained effec- 
tively. 

Further, the readers will also learn how to follow the sequence of data 
flow through the microcontroller when a program is executed. Addi- 
tionally, the readers will learn the operation of the microcontroller's 
I/O functions and the external devices driven by the microcontroller. 
Hardware and software design issues are discussed for specific systems 
implemented using MCS-51 as the embedded microcontroller. 



Acknowledgments 



We would like to take the opportunity to thank all those who have 
contributed or helped in some way in the preparation of this text. 
Particular thanks must go to our heads of the institutions - - Professor 
M.M. Salunkhe, Vice Chancellor, Shivaji University, Kolhapur, India, 
and Professor P.S. Zacharias, Vice Chancellor, Goa University, Goa, 
India for the encouragement and support. We would also like to 
thank Mr. P. Venugopal, Director, Software Technology Parks of India, 
Maharashtra Region, for his support. Dr. Kamat and Dr. Naik would 
like to thank their respective wives for their understanding and patience 
shown when the preparation of the book took time which could have 
been spent with the family. Our thanks then to Kamat's wife Rucha 
and Naik's wife Deepa. 

Additionally, Mr. Shelake and Mr. Parab would like to express grati- 
tude to their parents for their encouragement and support over the years. 
Kamat would like to dedicate his contribution to this book to the mem- 
ory of the late Professor G.G. Tengshe and the late Dr. V. Rao Indolkar, 
ACD Machine Control Tools Ltd., Mumbai. 

Dr. Kamat would also like to thank to his teacher in this field 
Mr. S. Ramgopal, Indian Institute of Science, Bangalore, and Dr. Senthil 
Kumar, Dr. Raghurama, Deputy Director (Academic) of BITS Pilani 
as well as Mr. K.S. Deorukhkar for help in reviewing and critical sug- 
gestions. The past batches of M.Sc. Electronics students of both Shivaji 
University and Goa University especially Mr. Roy, Mr. Rupesh from 
Satyam Computers must be thanked for generation of problems for 
programs developed in this book. 

■ Jivan S. Parab 

■ Vinod G. Shelake 

■ Dr. Rajanish K. Kamat 

■ Dr. Gourish M. Naik 



xv 



Chapter 1 

Microcontrollers: Yesterday, Today, 
and Tomorrow 



1.1 Defining Microcontrollers 

It is said that from the definition everything true about the con- 
cept follows. Therefore, at the outset let us take a brief review of how 
the all-pervasive microcontroller has been defined by various technical 
sources. 

A microcontroller (or MCU) is a computer-on-a-chip used to con- 
trol electronic devices. It is a type of microprocessor emphasizing 
self-sufficiency and cost-effectiveness, in contrast to a general-purpose 
microprocessor (the kind used in a PC). A typical microcontroller con- 
tains all the memory and interfaces needed for a simple application, 
whereas a general purpose microprocessor requires additional chips to 
provide these functions (Wikipedia [1]) 

A highly integrated chip that contains all the components compris- 
ing a controller. Typically this includes a CPU, RAM, some form of 
ROM, I/O ports, and timers. Unlike a general-purpose computer, which 
also includes all of these components, a microcontroller is designed for 
a very specific task to control a particular system. As a result, the 
parts can be simplified and reduced, which cuts down on production 
costs. . . . (Webopedia [2]) 

A {microprocessor} on a single {integrated circuit} intended to ope- 
rate as an {embedded} system. As well as a {CPU}, a microcontroller 
typically includes small amounts of {RAM} and {PROM} and timers 
and I/O ports. . . .(Define That [3]) 

A single chip that contains the processor (the CPU), non- volatile 
memory for the program (ROM or flash), volatile memory for input and 
output (RAM), a clock and an I/O control unit. . . . (PC Magazine [4]) 

A microprocessor on a single integrated circuit intended to operate 
as an embedded system. As well as a CPU, a microcontroller typically 
includes small amounts of RAM and PROM and timers and I/O ports. 
...(FOLDOC [5]) 

1 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 1-18. 
© 2007 Springer. 



2 Eagle's View: Microcontrollers and Other Competing Devices 

The definitions given by various sources describe microcontroller as 
an integrated circuit (IC) with processor as well as peripherals on chip. 
But the crux of the matter is the widespread uses of microcontrollers 
in electronic systems. They are hidden inside a surprising number of 
products such as microwave oven, TV, VCR, digital camera, cell phone, 
Camcorders, cars, printers, keyboards, to name a few. 

The last three decades and especially the past few years have wit- 
nessed the tremendous growth in the top-of-the-line processors used 
for personal computing and digital signal processor (DSP) applications. 
Today, the use of microcontrollers in embedded systems outnumbers 
the use of processors in both the PC and the workstation market. It is 
estimated that over 50% of the vast majority of the computer chips sold 
are microcontrollers. The main reasons behind their huge success are 
powerful yet cleverly chosen customizable electronics, ease in program- 
ming, and low cost. These days microcontrollers find increasing appli- 
cation even in areas where they could not be used previously. With the 
decreasing costs and footprints, it is now possible to have small-sized 
and cost-effective microcontroller units (MCUs) for new applications. 
The microcontrollers today are small enough to penetrate into the tra- 
ditional market for 4-bit applications like TV remote controls, toys, and 
games. For the simplest of all control applications they can offer high 
value smart switch functionality for applications that previously used 
electromechanical devices. Also the customers now can add intelligence 
to their end products for low cost as per the microcontroller market 
report by Frost & Sullivan research service [6]. 

1.2 Eagle's View: Microcontrollers 

and Other Competing Devices 

Generally the technical fraternity try to compare the various devices 
like microprocessors, PCs, microcontrollers, DSPs, and reconfigurable 
devices like FPGAs and CPLDs. An interesting point to note is that 
embedded systems are made using all the above-mentioned devices 
except PC owing to its general purpose architecture. As programma- 
bility is the common feature of all these devices, they have their firm 
footing in different application domains. On one side of the spectrum, 
microcontroller-based embedded system design emphasizes on task- 
specific dedicated applications at low power, low cost, high through- 
put, and highest reliability. On the other extreme of the spectrum, 
FPGA-based embedded systems dominate their custom computing 
architectures. Unlike microcontrollers, these systems can be reconfigured 
on the fly to suit the application with higher computational density and 



Microcontrollers: Yesterday, Today, and Tomorrow 3 

throughput. With the proliferation of density, FPGA-based embedded 
systems offer higher performance with the only challenging issue of 
memory required to store their configurations. 

The technical community also tends to associate various character- 
istics of embedded systems with microprocessors and microcontrollers. 
The microprocessors are typically found to dominate the desktop arena 
focusing on more and more bit processing capability, with other fea- 
tures such as fairly good amount of cache with memory management 
and protection schemes supported by the operating system. Although 
microcontrollers share flexibility aspect of microprocessors through pro- 
gramming, 8-bit versions are more in use (although 16- and 32-bit exist) 
with RAM and ROM (instead of cache) added with many on chip 
peripherals like timer/counter, decoder, communication interface, etc. 
In the literature many embedded systems products have been reported as 
microprocessors. On the other side of the processor spectrum, a DSP pos- 
sesses special architecture that provides ultra- fast instruction sequences, 
such as shift and add, multiply and add, which are commonly used in 
math-intensive signal processing applications. The common attributes 
associated with the DSPs are multiply-accumulate (MAC) operations, 
deep pipelining, DMA processing, saturation arithmetic, separate pro- 
gram and data memories, and floating point capabilities required most 
of the time. However, the line of differentiation between all these devices 
is getting blurred at a rapid pace. With the introduction of fuzzy logic, 
artificial intelligence and networked communication capabilities in the 
consumer products like refrigerators, mobile phones, and cars, conver- 
gence of the architectures of most of the above-mentioned programmable 
devices is witnessed by the industry. Today's ideal microcontroller is 
expected to offer plenty of MIPS, run the DSP programs with the same 
speed of the DSP processor, integrate all its peripherals and support 
flash, communicate with the world with 12 C or CAN protocols, with- 
stand extremes of environment in a car engine, and cost but a few 
cents. 

1.3 Vignettes: Microcontrollers 

It is interesting to note that the development of microprocessors seems 
to be an accident out of the microcontroller synthesis. In 1969, Busicom, 
a Japanese company, approached Intel to convert their special pur- 
pose ROM and shift register-based calculator cores into a specialized 
application specific processor. The objective was the development of 
microcontrollers rather than a general purpose of CPU chips for key- 
board scanning, display control, printer control, and other functions for 



4 Vignettes: Microcontrollers 

a Busicom-manufactured calculator. However, the Intel engineers opted 
for a more flexible programmable microcomputer approach rather than 
the random logic chip-set originally envisioned by Busicom. The four 
designs [7] proposed by Federico Faggin, Ted Hoff, and Stan Mazor from 
Intel were a 2048-bit ROM with a 4-bit programmable input /output 
port (4001); a 4-registers x 20-locations x 4-bit RAM data memory 
with a 4-bit output port (4002); an input/output (I/O) expansion chip, 
consisting of a static shift register with serial input and serial/parallel 
output (4003); and the 4-bit CPU chip (4004). The 4001, 4002, and 
4003 are very close to microcontroller kind of architecture rather than 
microprocessor. However, the Intel 4004, which was supposed to be the 
brains of a calculator, turned out to be a general-purpose microproces- 
sor as powerful as ENIAC. The scientific papers and literature published 
around 1971 reveal that the MP944 digital processor used for the F-14 
Tomcat aircraft of the US Navy qualifies as the "first microprocessor" . 
Although interesting, it was not a single-chip processor, and was not 
general purpose -- it was more like a set of parallel building blocks you 
could use to make a special purpose DSP form [8]. It indicates that 
today's industry theme of converging DSP- microcontroller architectures 
was started in 1971. 

The other companies were also catching up at the same time. The 
first official claim of filing the patent goes to Texas Instruments under 
the trade name TMS1000 way back in 1974. This was the first micro- 
controller which included a 4-bit accumulator, 4-bit Y register and 2- or 
3-bit X register, which combined to create a 6- or 7-bit index register 
for the 64 or 128 nibbles of on-chip RAM. A 1-bit status register was used 
for various purposes in different contexts. This microcontroller served as 
the brain of the Texas Instrument's educational toy named "Spark and 
Spell" shown in the movie ET: The Extraterrestrial. In 1976, Intel intro- 
duced the first 8-bit microcontroller family MCS-48 which was so pop- 
ular that they could ship 251,000 units in that year. After four years of 
continuous research, the MCS-48 family was upgraded to 8051, an 8-bit 
microcontroller with on-board EPROM memory. Intel shipped 22 million 
pieces in 1980. The market requirement was so much that the total units 
sold in three years later were 91 million. The year 2005 is a special one 
for the microcontroller 8051. It has celebrated its 25th anniversary. But, 
also in 2005, Intel notified they would discontinue all automotive versions 
of their microcontrollers, including 8051. Car engine control units were 
once perhaps the most prominent application for 8051s. This means only 
one thing, Intel gives up the microcontrollers for good. This is confirmed 
by product change notification published in early 2006, announcing that 
Intel drops its whole microcontroller business [9]. 



Microcontrollers: Yesterday, Today, and Tomorrow 5 

1.4 Microcontroller Applications 

The microcontroller applications are mainly categorized into the 
following types (see Figure 1.1): 

Audio 

Automotive 

Communication/wired 

Computers and peripherals 

Consumer 

Industrial 

Imaging and video 

Medical 

Military/ aerospace 

Mobile/wireless 

Motor control 

Security 

General Purpose 

Miscellaneous 

Automobile industry is the main driving force in propelling the growth 
of microcontrollers. It is estimated that the microcontrollers constitute 
33% of the semiconductors used in a vehicle [10]. Requirements of the 
automobile sector has forced the microcontroller manufacturers to come 
out with the new bus protocols such as control area network (CAN) 
and local interconnect network (LIN). Microcontrollers of all bit cores 
are used in vehicles according to the Frost & Sullivan Industry report. 
The 8- and 16-bit microcontrollers are used for low-end applications 
and lower-cost vehicles while the 32-bit microcontrollers are used for 
high-end application and high-end vehicles. It is estimated that cur- 
rently 30-40 microcontrollers are used in low-end vehicles and about 
70 microcontrollers are used in high-end vehicles. These requirements 
are continuously increasing and it is highly likely that the count of micro- 
controllers in vehicles will further increase in the future, quotes World 
Microcontrollers Market Report by Frost & Sullivan [10]. 



6 



Microcontroller Applications 




Figure 1.1 Microcontroller application tree 



Microcontrollers: Yesterday, Today, and Tomorrow 7 

Embedding microcontrollers in the product offers some unique 
advantages. For an example, in the latest technology washing machines, 
a transmission is no longer required because a lower-cost AC induction 
or reluctance motor controlled by sophisticated microcontroller-based 
electronics can provide all the normal machine cycles [11]. Additionally, 
the electronically controlled induction or reluctance motor provides a 
more effective and gentler agitation (wash) cycle that allows the drum 
containing the clothes to be rotated first in one direction, then stopped, 
and rotated in the opposite direction without requiring any additional 
mechanical device. This forward/reverse agitation cycle provides a more 
effective means of cleaning your clothes without damaging the fibers 
used to make them. 

It is also observed that the induction of microcontrollers in a product 
has increased the market demand of the product itself. One such exam- 
ple is NEC Electronics' 8-bit microcontroller [12], which is employed in 
over half of the digital cameras produced throughout the world, thus 
making it a hit product - albeit one that plays its role behind the scenes. 
In 2003, the shipment volume of 8-bit microcontrollers for digital cam- 
era use achieved monthly shipments of two million. Currently, the most 
commonly used microcontroller for digital cameras is the |lPD78003x. 
The industry's top-level, low-voltage (1.8 V) A/D converter is built 
into this compact 64-pin QFP package with an edge measuring a mere 
10 x 10 mm. 

1.5 Growth Economics 

Many industry analysts have reported a bright growth economics 
for microcontroller in the near future. Bourne Research reports that 
MEMS-based motion, pressure, and acoustic sensors (as well as other 
next-generation sensing technologies) are not only finding their way into 
classic consumer products like toys, housewares, sporting goods, and 
clothing, but applications as far-reaching as flooring materials, medical 
diagnostics, retail fixtures, and vending machines. System complexity is 
just as varied, but Bourne Research notes that, more often than not, 
these products will utilize multiple sensors and microcontrollers [13]. 
Another interesting report by the Semiconductor Industry Association 
(SI A) reveals that the microcontroller sales are projected to grow by 
1.9% to $12.3 billion in 2006 and to $15.4 billion in 2009, a compound an- 
nual growth rate (CAGR) of 6.3% [14]. The positive growth economics of 
microcontroller chips also ushers the associated growth of software such 
as simulators, cross compilers, and assemblers. The market is witnessing 
many novel supporting software packages with simple user interface with 
convenient compiling and debugging tools. 



8 



Microcontroller Applications 



1.6 



The Major Players in the Microcontroller 
Chip Market 



Table 1.1 Major players in the microcontroller market. (From 2006 EDN Directory 
of Microprocessors and Microcontrollers) 



Name 
of the 
company 



Product range 



Application domain 



Actel 



Altera 



Altium 



Analog 
devices 



Applied 
Micro 
Circuits 
Corp 

ARC Inter- 
national 



ARM 



Atmel 



Core8051 
8-bit-microcontroller IP 

Nios Il/f (fast), Nios Il/e 
(economy), Nios II/s 
(standard), Soft IP cores 
Royalty- free, 8- and 32-bit, 
FPGA-based soft processors, 
and FPGA-independent 
TSK3000RISC core 
ADuC7128 family of precision 
analog microcontrollers; 
ADSP-BF561 Blackfin 
ADSP-BF534 Blackfin, BF539 
with CAN 

Embedded PowerPC proces- 
sors PPC405CR PPC405EP, 
PPC405EZ, PPC405GP, 
PPC405GPr, nP405H, etc. 

Two configurable, 32-bit 
processor-core families 
ARC600 and ARC700 

Range of processor cores, 
including the ARM7, ARM9, 
ARM10, and ARM11 families 
and the new Cortex family 
featuring Thumb- 2 technology 
AVR, AVR32, ARM7, ARM9, 
8051, Teak, and Diopsis DSP 
cores 



Consumer, communications, auto- 
motive, industrial, and military/ 
aerospace applications 
Automotive, consumer, industrial, 
medical 

Automotive, industrial, 
communications, and 
computer-peripheral 

Audio, automotive, 
communication/wired, consumer, 
industrial, imaging and video, 
medical, motor control, security 

Communication/wired, computers 
and peripherals, consumer, 
industrial, imaging and video, 
medical, mobile/wireless, motor 
control, security 
Sound advanced subsystems 
targeting portable media devices 
and advanced-definition audio 
applications 
Audio, automotive, 
communication/wired, computers 
and peripherals, consumer, 
industrial, imaging and video, 
medical mobile/ wireless, security 
Consumer, computer/networking, 
communications, security/smart 
cards, automotive, industrial, 
medical, military, and aerospace 
applications 



Microcontrollers: Yesterday, Today, and Tomorrow 



9 



Cast 



Cirrus Logic 



Dallas Semi- 
conductor 



Freescale 
Semicon- 
ductor 



Lattice 
Semicon- 
ductor 



Luminary 

Micro 

Microchip 

Technology 



8-, 16-, and 32-bit IP cores 
including 8051 cores with 
instruction execution one clock 
per cycle; configurable 8051, 
8-bit Z80 and 16-bit 68000 
compatible devices 
ARM9- and ARM7-based 
embedded processors 
EP9301, EP9302, EP9307, etc. 
Four microcontroller families 
targeting networked, secure, 
mixed-signal, and 8051 drop-in 
designs 



Ultralow-end, RS08-based, 
8-bit microcontrollers to an 
advanced 32-bit ColdFire core 



Fujitsu 


32, 16, and 8-bit 


Micro- 


microcontrollers with 


electronics 


onboard-flash, ROM, ADC, 


America 


DAC, CAN (controller area 




network), USB, and LCD 




controllers 


Infineon 


8-, 16-, and 32-bit bit 


Technolo- 


XC886/888, XC164CM 


gies 


TC116x 



8-bit microcontrollers, 
including the 8051 and PIC, 
through its partners, Cast and 
Digital Core Design, 
LatticeMico8 an 8-bit soft 
microcontroller core 
ARM Cortex-M3-based 
microcontrollers 
8- and 16-bit PIC 
microcontrollers, as well as 
16-bit dsPIC DSCs (digital 
signal controllers) 



Automotive, communication/ 
wired, computers and 
peripherals, consumer 
industrial, imaging and video, 
medical military/aerospace, 
mobile/wireless motor control 
Audio and industrial markets 



Networking applications as 
they have an optional TCP/IP 
stack in ROM, a built-in 
Ethernet MAC (media access 
controller), CAN (controller 
area network), and parallel 
and serial ports 
Mobile and videoconferencing 
phones, portable media 
players, PDAs, and portable 
GPS applications, networking, 
home and SOHO 
(small-office/home-office) 
networking, automobile 
Automotive, communications, 
computer peripheral, 
industrial, and consumer 
applications 



Industrial and automotive, 
industrial motor control, 
building control for lifts and 
escalators, intelligent sensors, 
distributed I/O modules, and 
industrial automation 
Automotive, 
communication/wired, 
computers and peripherals, 
consumer industrial, medical 



Industrial and motor control 

Motor control and general 
purpose 



10 



Architectural Trends 



Table 1.1 Continued. 



Name 
of the 
company 



Product range 



Application domain 



National 
Semicon- 
ductor 



NEC 

Electronics 

America 



COP8 flash microcontrollers 
featuring an 8-bit core with 32 
kbytes of onboard flash 



8-bit uPD78F0711 and 
uPD78F0712 flash-based 
microcontrollers, 32-bit 
flash-based V850ES/IE2 series 



Hardware communications 
peripherals, and an 
expandable external bus to 
target embedded system 
communications applications, 
such as automotive telematics, 
vehicle-network gateways, 
hands- free car kits, and 
industrial and medical 
instrumentation and control 
Consumer appliances, home 
health care, building 
management systems and 
industrial controlled 
applications 



1.7 



Architectural Trends 



The emerging trends in microcontroller architecture are dictated by 
the technological needs of the embedded system applications. In gen- 
eral the common road map is characterized by the features like single 
functional, tightly constrained in terms of cost, power, speed, and foot- 
print as well as continuously reactive in a real-time manner. The micro- 
controller world is divided over the architecture used. Controllers like 
8051, 68HC11 join their microprocessor counterparts (80 x 86 family) in 
using Von-Neumann architecture by sharing RAM and program mem- 
ory with the same bus. This imposes the same bit width for the buses 
irrespective of their requirement, which is not the case with the PIC 
processors which uses Harvard architecture. 

8-bit Treads on MCU Turf 

It is really interesting to note that in this era of 32-bit processors, 
the 8-bit microcontrollers are flourishing and enjoying a stable future. 
The reasons behind this are low cost and inexpensive development soft- 
ware. An 8-bit microcontroller like 8051 today enjoys 40% of the market 
share [15]. It has become so popular that about 40 manufacturers now 
make it with 800 derivatives used for diverse applications right from 



Microcontrollers: Yesterday, Today, and Tomorrow 11 

simple process control to high-tech telecom. The original MCS-51 family 
developed by Intel consists of CHMOS processors with features such 
as 8-bit CPU optimized for event control, Boolean processing, on-chip 
memory (up to 32 K) and on-chip peripherals (timer/counters, serial 
ports, PC A, etc.). The other manufacturers like Atmel, Dallas, Philips, 
Analog Devices, etc., have extensively worked for strengthening the basic 
core by introducing additional features such as Additional Data Pointers 
(DPTR), Extended Stack Space, Fast Math Operations and Extended 
or Reduced Instruction Sets to name a few. Table 1.1 summarizes the 
features of the popular 8051 derivatives manufactured by various compa- 
nies. Although industry analysts predicted the saturation of 8051 family 
and also its death, it turned out to be a rumor. In 2003, Cygnal released 
world's highest performance 8051 microcontroller [16]. The C8051F120 
family devices include 128 Kbyte Flash memory, 8448 byte RAM, and 
are packaged in either a 100-pin or 64-pin TQFP. On-chip peripherals 
include a 12-bit lOOksps ADC, two 12-bit DACs, a 2% internal oscillator, 
temperature sensor, voltage reference, two UARTs, and many features 
of a DSP processor. 

Low Power Design 

The latest 8-bit devices continue to drive up the performance bar 
with simplicity for usage and ease of programming. Most of these de- 
vices are aimed at low power consumption achieved by using sleep modes 
and the ability to turn certain peripherals on and off. The best example 
for this is XE88LC02 from XEMICS [17], a recently launched microcon- 
troller, which features programmable gain/offset amplifier followed by 
high resolution ADC with four differential or seven pseudo differential 
inputs, with current consumption as low as 2 |iA in real-time clock mode 
and a typical 300|iA/MIPS in sustained computing mode. Recently, 
Atmel has also strategically evolved their microcontroller architecture by 
implementing novel power saving techniques. Atmel' s picoPower tech- 
nology uses a variety of techniques that eliminate unnecessary power 
consumption in power-down modes. These include an ultra- low-power 
32 kHz crystal oscillator, automatic disabling and re-enabling of brown- 
out detection (BOD) circuitry during sleep modes, a power reduction 
register that completely powers down individual peripherals, and dig- 
ital input disable registers that reduces the leakage current on digi- 
tal inputs [18]. PicoPower microcontrollers consume down to 340 Jl A in 
active mode, 150 |iA in idle mode at 1 MHz, 650 nA in power-save mode 
and 100 nA in power-down mode. 



12 Architectural Trends 

Convergence of DSP with Micro 

The trend of convergence of functionality in microcontroller was 
started in the 1970s with MP944, which had more of DSP orienta- 
tion. For a microcontroller engineer to consider a DSP or for a DSP 
engineer to use a microcontroller, three strict criteria must be met: 
price/performance, peripheral set, and development tool quality [19]. 
This trend is now more pronounced as seen in the newly launched 
microcontroller cores by Motorola. For instance, in its 56F83xx family 
of microcontrollers, Motorola has introduced a series of devices that it 
intends to meet uprated processing needs in today's systems - partic- 
ularly in automotive systems while keeping 8/16-bit economics and 
avoiding the shift to 32-bit controllers. The defining features of the 
device series are the inclusion of some DSP attributes and the use of 
on-chip flash memory instead of EEPROM. The term "hybrid" describes 
the devices' combination of microcontroller and DSP functions. These 
devices are not hybrid in the sense that they combine twin processing 
cores; rather, they add the facility to efficiently execute certain DSP- 
like arithmetic functions such as multiply-accumulate operations [20]. 
These kinds of architectures are in heavy demand owing to such hybrid 
signal processing requirements in application domains such as speech 
processing in consumer applications. The key challenges in converging 
these two diversified architectures are combining the pipelining, register 
oriented, complex conditional resolving architecture of microcontrollers 
with the multiply-accumulate, data massive, and deterministic software 
typically with zero overhead loops of the DSPs. With the inclusion of 
DSP functionality in microcontrollers many things such as modem sup- 
port, compression of data voice, and image as well as filtering and speech 
synthesis/recognition are possible. This has been successfully done in 
some of the recently launched microcontrollers like Goal Semiconduc- 
tor's VMX1016. This microcontroller possesses a powerful hardware 
arithmetic unit with 32-bit barrel shifter that can perform simultaneous 
16-bit signed multiplication and 32-bit addition. Another example of 
this convergence is Hitachi's SH3-DSP based on a single instruction 
stream approach combining general purpose CPU and dedicated DSP 
functionality in a single architecture [21]. These types of microcon- 
trollers facilitate upgradation of the embedded systems merely with the 
addition of software utilities. 

Hidden Debugger 

With the increasing design complexity debugging or verification has 
become the major bottleneck to meet the tight time to market schedule. 



Microcontrollers: Yesterday, Today, and Tomorrow 13 

It is estimated that debugging time is almost 30-50% of the total deve- 
lopment time. The conventional techniques such as extra design for 
testability by embedding test points or scan chains as well as exter- 
nal debugger are on the way of extinction. The new microcontrollers 
are struggling to sort out the resource requirement vs computational 
complexity dilemma. The use of logic analyzer for monitoring the clock 
quality as well as the bus activity has become very expensive and many 
times physically impossible with the shrinking footprint of microcon- 
trollers operating at the clock speed as high as 100 Mhz. The IEEE-ISTO 
Nexus 5001 Forum which comprises around 25 major microcontroller 
manufacturers defines a common set of on-chip debug features, proto- 
cols, pins, and interfaces to external tools which may be used by real-time 
embedded application developers. As a result, more than 70% of leading 
embedded microcontroller vendors now have dedicated circuits and pins, 
whichassist in new product development based on the IEEE 1149.1 Joint 
Test Action Group (JTAG) 4- wire serial interface [22]. Apart from the 
JTAG interface, today's microcontrollers are enriched with the back- 
ground debug mode (BDM) and on-chip emulation being achieved at 
higher abstraction level for reducing size and searching space in the 
debugging. Although the microcontroller community is still far from 
implementing the debugging solution for pointer problems, accessing 
unintialized memory, and interprocess interaction, the chips are domi- 
nated with single stepping and breakpoint utilities, e.g., the recently 
launched C8051F120 [23] has on-chip debug circuitry facilitating full- 
speed in-system debug features such as single-stepping, breakpoints, and 
modifying registers and memory. 

Web-Enabled Microcontrollers 

Embedded internetworking allows anytime, anywhere, control of the 
product with a regular self-maintenance and pervasive, wearable com- 
puting. The tangible benefits of Internet connectivity in products like 
air conditioner or washing machine are self-upgradation by downloading 
the software updates, lowering cost by fine-tuning energy consumption 
in peak hours, generating auto maintenance alarms, etc. Microcontroller 
manufacturers have come out with new processors having a built-in 
capability to cope with the challenges of web processing. Dallas Semi- 
conductor has come out with the microcontrollers that can directly serve 
up web pages. TINI (Tiny InterNet Interface) [24] is a microcontroller- 
based development platform that executes code for embedded web 
servers. Remote devices can have preferences and settings adjusted from 
afar, just by having their administrator browse a web page hosted by 



14 Jump Starting Your First Embedded System Project 

the microcontroller no other computers required. The TINI development 
platform combines a powerful chipset and a Java runtime environment 
that exposes the extensive I/O capability of the Dallas microcontrollers. 
A Java programmer accesses the I/O from robust APIs (Application 
Program Interfaces) that include Ethernet, RS-232 serial, I2C, 1-Wire 
net, CAN, and memory-mapped parallel bus. By using these APIs, 
programmers code functions without worrying about the underlying 
interface to hardware peripherals. The runtime environment is tightly 
coded for optimized network communications and efficient device I/O 
throughput. 

Dominance of Soft IP cores/Free Microcontroller? 

The new VLSI devices such as FPGAs offer several advantages 
over microcontrollers. FPGA-based platform enables the developer to 
test (thanks to the JTAG philosophy) and add features in parallel 
without the need for repeating the complete testing of the platform 
once again. Increasing number of manufacturers are now offering the 
FPGA-based microcontroller core. The list of FPGA-based soft IP cores 
for 8051-based microcontrollers is available at the web page of Keil 
(http://www.keil.com/dd/ipcores.asp). For example, the C-8051 core is 
the HDL model of the Intel 8-bit 8051 microcontroller by Aldec Inc. [25]. 
The model is fully compatible with the Intel 8051 standard and is avail- 
able in both EDIF and VHDL netlists formats. The EDIF netlist is used 
for the place and route process and VHDL is the post-synthesis netlist 
used for the simulation only. Both netlists are technology-dependent 
because they are created after the synthesis where the customer needs 
to specify a vendor, target family, etc. Even the source code of a set of 
HDL testbenches for the cores is also available. 

1.8 Jump Starting Your First Embedded 

System Project 

Figure 1.2 shows a minimum setup required to build microcontroller- 
based embedded system project. The foremost requirement is a low- 
end PC pre-loaded with the IDE to facilitate the code development, 
simulation and testing before actual dumping the code in the flash of the 
microcontroller. The Keil IDE is covered in depth in Chapter 2. Most of 
the projects developed in this book have been tested on AT89S52 which 
has the following features: 

■ 8K Bytes of In-System Reprogrammable Flash Memory 

■ Fully Static Operation: Hz to 33 MHz 



Microcontrollers: Yesterday, Today, and Tomorrow 



15 




Figure 1.2 Minimum setup recommended for your Embedded System Laboratory 



Three-level Program Memory Lock 



256 x 8-bit Internal RAM 



32 Programmable I/O Lines 
Three 16-bit Timer/Counters 
Eight Interrupt Sources 
Programmable Serial Channel 
Low-power Idle and Power-down Modes 
4.0V to 5.5V Operating Range 
Full Duplex UART Serial Channel 
Interrupt Recovery from Power-down Mode 
Watchdog Timer 



16 Execution of Embedded System Project: Is it a Gordian's Knot? 

■ Dual Data Pointer 

■ Power-off Flag 

■ Fast Programming Time 

■ Flexible ISP Programming (Byte and Page Mode) 



1.9 Execution of Embedded System Project: 

Is it a Gordian's Knot? 

Here is a piece of thought for the student community as well as 
entrepreneurs looking for a successful embedded system project. 

Project Idea to Execution 

For successful project development, first you must develop an idea. 
There are lots of sources for idea generation. Ideally your ideas should 
move from research laboratories towards the marketplace. Many devices 
and processes around can be improved by the inculcation of microcon- 
trollers. The automation of the nylon rubber stamp making machine 
described in the case studies is the best example. The thinking should 
ideally go on the following lines: How can the process be controlled 
using a microcontroller, ultimate efficiency, or throughput improvement 
with embedding of microcontrollers? Are there any simulation tools to 
model and estimate before the actual experimentation? In what way 
can the process be made more intelligent (or thinking) by using the mi- 
crocontrollers? For answering the automation of a process plant using 
microcontroller, one must think about the on-chip resources and their 
effective usage (e.g., interrupt level/edge, usage of ports, timer/counter, 
and so on). The answer to the second question should throw light on 
the benefits of using the microcontroller in your project. (Can you think 
of green house controller without microcontroller? Or the amount of 
energy saved with the microcontroller-based corridor lighting which is 
implemented in the case studies.) According to the US Department of 
Energy [26], the electricity used to light businesses represents 25% of the 
energy they spend; so it is important to develop energy-saving devices. 
Even a simple switch equipped with photosensor and microcontroller can 
help to reduce lighting energy consumption by 30%. 

Simulation is the best methodology to avoid project failure as well 
as to work in a time-efficient manner. It is always a good idea to simu- 
late the things using the microcontroller IDE instead of rushing to the 
project board and actually dumping the code in the on-chip memory. 



Microcontrollers: Yesterday, Today, and Tomorrow 17 

Moreover, there are simulation tools even to model physical systems 
(such as Proteus) which can be used together with the IDE to work out 
your project. The last question is little challenging. In order to make 
the microcontroller think or make it intelligent you have to resort to 
some novel items such as neural net implementation, extrapolation, and 
statistical techniques. 

As the sole success of the embedded system project is on firmware, the 
software and the underlying hardware should not be treated as separate 
entities. Therefore, the term "Hardware-Software Co Design" has gained 
lots of significance in the field of embedded systems. Following issues 
pertaining to hardware and software are of utmost importance while 
executing any embedded system project. 

Hardware and Software Issues 

Even the simplest things dictate the final specifications of the final 
product. There is often a major gap between the theory of design and 
what "plays" in the real world. The most casual thing for a designer in 
any microcontroller-based product is the value of the crystal frequency 
which is 11.0592 MHz. The rationale behind this value is the ease of 
frequency division to yield exact clock rates for standard baud rate gen- 
eration for the UART. However, in the applications where the serial 
communication is not at all in picture, the designer has lot of flexibil- 
ity in choosing the crystal value. The crystal value decides the execution 
speed, e.g., Intel 8051 microcontrollers require a minimum of 12 oscillator 
cycles. This means if the crystal is of 12 MHz, then 8051 microcontroller 
works at performance of 1 MIPS. If a thorough analysis of the occurrence 
of real-time events reveals that this speed is not required, then a designer 
may go for a lower value of the crystal. The ultimate advantage is a 
significant reduction in power consumption. In CMOS-based versions of 
8051, a linear relation between oscillator frequency and power consump- 
tion exists. Another lower range crystal value is 7.3728 MHz which can 
be used even for standard baud rate generation. The notable thing is: 
using counter 1 of 8051; this gives an even 38.4 Kbps rate exactly, which 
is not possible even with 11.0952 MHz Xtal. The lower crystal value also 
enables to access low-speed peripherals and frees the system from elec- 
tromagnetic interference (EMI) evident in high clock speed MCUs. 

Problems such as reset, latch-up, memory corruption, and code run- 
away are found to fail the embedded system application due to ESD 
and EMI. Areas of MCUs typically vulnerable to ESD and EFT stresses 
include: power and ground pins, edge sensitive digital inputs, high fre- 
quency digital inputs, analog inputs, clock (oscillator) pins, substrate 



18 Execution of Embedded System Project: Is it a Gordian's Knot? 

injection, general purpose I/O (GPIO) with multiplexed pin functions, 
etc. These kind of problems can be solved by using the microcontroller 
having proper package style, footprint, and maximum number of supply 
and ground pins [27]. 

While developing the software it is important to have a modular app- 
roach. The interrupt service routines should be as short as possible to 
reduce the interrupt latency. Readability and debugging specifications 
not only enhances the value of the software but also frees the novice 
to minimize the learning curve. Choice of the language plays an impor- 
tant role to decide the lead time, life and processor migration of your 
microcontroller-based product. Using the higher level languages like 'C 
for writing programs offers some unique advantages such as faster devel- 
opment, improved portability, reusability, platform independence all 
at reduced cost. Complex algorithms can be very easily implemented in 
'C rather than assembly. As the design evolves in due course, the req- 
uired restructuring of the program without breaking the existing design 
can be easily done in 'C. Although assembly language is the best choice 
for time critical programs, the user face lot of difficulties in managing 
large programs especially in memory allocation. "Porting" the assembly 
language code to another processor family is almost impossible or very 
difficult. 



Chapter 2 

Integrated Development Environment 



Integrated development environment popularly known as IDE is a 
suite of software tools that facilitates microcontroller programming. The 
Keil IDE enables the embedded professional to develop the program in 
C and assembly as well. The IDE passes through the source code to 
check the syntax. The compilation leads to a hex file to be dumped in 
the microcontroller on-chip ROM. A quick session of simulation and 
debugging using the IDE ensures the working of the program before- 
hand. The user can verify the results as the package presents screenshots 
of on-chip resources. This chapter presents in-depth discussion on using 
the \x Vision 2 package of Keil IDE on MS Windows platform. It is 
recommended that while going through the discussion the user should 
access the (iVision 2 package of the Keil. A step-by-step working as 
discussed in this chapter will empower the user to get familiar with 
the Keil IDE. 

2.1 Getting Familiar with the IDE 

The microcontroller product development cycle consists of several 
steps such as 

■ Development of code either in assembly or C 

■ Simulation of the code 

■ Dumping the code in microcontroller 

■ Prototyping or debugging if required by using in-circuit testing 

■ Emulation of the code in case of big project 

■ Refining the code, reprogramming and final testing 

A microcontroller-based project generally makes several iterations 
through the above-mentioned steps before it sees the light of the day. 



19 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 19-28. 
© 2007 Springer. 



20 Working with Keil IDE 

Almost all the microcontroller manufacturers have come out with 
the development tools for their products. A suite of such software 
tools for microcontroller application development is refereed to as IDE. 
Some examples of the popular IDEs apart from Keil are MPLAB from 
Microchip, PE micro from Motorola, and AVR studio from Atmel. 

Any typical IDE comprises many subcomponents such as a text editor 
for entering the code, building tools for converting the code into machine 
level, compiler to convert 'C code to assembly or hex format, and linker 
to provide absolute addresses to the relocatable object code. The IDE is 
generally equipped with powerful code simulator that models operation 
of the target microcontroller as code execution is in process. IDEs are 
available as a software suite which runs on a stand-alone PC and displays 
and allows to modify the contents of virtual I/O and on-chip resources 
such as registers. Single-stepping and breakpoint facilities are provided 
to systematically execute and watch the cause/effect relationship of the 
code. A provision of instruction cycle calculation/display is also provided 
so as to see the time/memory efficiency of the code. 

2.2 Working with Keil IDE 

As the entire software development described in this book is based 
on the Keil 8051 Development Tools, it is worthwhile to study the tool 
in depth. The Keil IDE is a user-friendly software suite to develop your 
'C code and test the same in a virtual 8051 environment. The main 
feature of the Keil is that it allows C programmers to adapt to the 8051 
environment quickly with little learning curve. 

It offers the designer a device database of MCS-51 family from which 
the target device of interest can be chosen. The (iVision IDE sets the 
compiler, assembler, linker, and memory options for the designer. The 
suite comes with numerous example programs to assist the designer to 
start his project. With the virtual environment, the available on-chip 
resources of the microcontroller chosen can be seen working on the PC 
screen. The simulation window facilitates very realistic simulation of 
both CPU and embedded peripherals. The graphical window shows the 
state and configuration of the embedded peripherals and displays the 
interaction of the microcontrollers with external peripherals. Although 
the simulation exercise consumes time, it helps to save the bugs and 
project failure in the long run. 

A natural question that occurs to designer is in what way the 
conventional C programming for PC is different from the C programming 
with Keil or C51 programming. The basic objective of the conventional 



Integrated Development Environment 21 

C programming language was to make it work on the PC architecture 
with a high level interface. Therefore, it does not support direct 
access to registers. However, unlike the conventional C program- 
ming on PC, most of the microcontroller-based embedded systems 
applications demand reading and setting or resetting of single bits, 
or Boolean processing. The second main difference is the program- 
ming environment. Conventional C operated under the umbrella of an 
operating system may be Linux or Windows, wherein there is a pro- 
vision of system calls the program may use to access the hardware. 
Almost all the programs written with microcontroller are for direct 
use where the while(l) loop is common. The above-mentioned differ- 
ences are bridged in Keil compiler by adding several extensions to 
the C language, e.g., connecting of interrupt handlers. A good web- 
resources are available on this topic at www.massey.ac.nz/~chmessom/ 
Chapter%206%20C%20Progr ammingFinal.pdf 

2.3 Development Flow for the Keil IDE 

The evaluation version of the Keil IDE for MCS-51 family (also 
known as C51 evaluation software) can be downloaded from the website 
www.keil.com. One can go up to a limit of 2 Kbytes of object code 
with the evaluation version. Once the Keil IDE is installed, a short cut 
appears on the desktop. 

Step 1: Interfaces Offered by Keil IDE 

After clicking on the above shown shortcut the following steps 
should be carried out. The first blank window will appear as shown 
in Figure 2.1. 

You will be working with three windows presented by the Keil IDE. 
The first is target toward the extreme left of the screen which is blank 
at the moment, but will be updated as you go on working with the 
project. The source file, register header file, and the target microcon- 
troller chosen is displayed here. The bookmarks for the user such as 
data sheet, user guides, library functions, etc., forms a ready reckoner 
for the developer. The program window which occupies most of the size 
of your screen displays the source code in C. At the lowermost end of the 
screen, an output window is presented which gives information regarding 
the errors and other output messages during the program compilation. 

Open a new text file for writing your source code. This file has to be 
saved with .c extension. This source code file will be ultimately added 



22 



Development Flow for the Keil IDE 



9 1 ' trial MViBion2 


B®(S 


git E<fc g«w wojttt B*lx»g Fljsh Ptrtpht. *te Took £MC5 windo* Hrip 


^G»B0 /4 '. *r 


dM 




|'J ,£,$ |[iQ|S|- *> & 


k£|T«d*1 






-^-l,d ^^^^^^^^^^^^^^^ 








. stert 



(£' tna - |,Viqo-li 



Figure 2. 1 The starting interface of Keil IDE 

into your project to be opened as per step 2. The addition should be 
done as per the instructions given in step 5. 

Step 2: Opening a New Project 

Here you can give a meaningful name for your project. After saving it 
will create a folder which will store your device information and source 
code, register contents, etc. Figure 2.2 shows a project opened with a 
name trial. 



Step 3: Selecting a Device for the Target 

After completing step 2, Keil will give an alert to select the device. 
The (iVision 2 supports 45 manufacturers and their derivatives. In the 
exercise given in this book we have selected Atmel's 89S52 microcon- 
troller as a target. 

Step 4: Copying Startup Code to Your Project 

The "startup. a51" will be added automatically to your project from 
the Keil library "c:\keil\c51\lib" to [c:\keil\c51\EXAMPLES\HELLO\ 
ctrial\STARTUP.A51]. 



Integrated Development Environment 



23 



i'T' trial uYision? 



d BS H & A '* 

£ ■© |[rE[jS| e fer 



_ - x 



n Xs|T«grt1 



•J* 



1j Source Group 1 



rS 1 -. (jJb... 




Ftename [ftaTf 



5«v* «tKP*: |PtaiedFi»i:r'*-2| 



~ NBJiACwrr»lAFindnBw f 



f 



m 



, Stan ■*> ^ * GMd D'h-e 



■IcrrvJ^i "lucsoUWo... ^nrt uvu:ww> ^1 T fc36PH 



Figure 2.2 Opening a new project 



R' tria.11 (jV is ion 2 



Fie £d(t Vtew Eroject Qebug Pfeh Peripherals Took JVCS fijndw tjelp 






Select Device for Target 'Target 1" 






I* £j Target 



[=1 Files 




CPU 

Vendot: Almel 
Device: ATSB52 
Far*: MCS-51 

Database 



r U» Extended Linker (1X51 ) instead ol BL51 
r * Extended/ lofA51 



Description: 





□ AT89C55V/D 




- 




£}AT89F51 








DAT83F52 








CJ AT89LS51 




- 




□ AT89LS52 








Q AT89LV51 








CJ AT83LV52 








■ AT83LV55 








D AT89LV55WD 








DAT89S4D12 








Cj AT89S51 






_jQ 






DAT89S53 




- 


i 


> 





8051 bawd RJ State CMOS control* with 32 WQ itm, 3 Timer ttourfe 
8 K ROM Memory, 25E Bytes On-chip RAM 




Cancel 



~\ \R>Mfi Conwand A Find * Fles / 



: 



„ start 



w 



GMei Drive J My Computer IV MicrosottWo... pT>" trial 1 -uvbi... ^j>?* 2:39 PM 



Figure 2.3 Selecting a device for the target 



24 



Development Flow for the Keil IDE 



0. Irial1 |jVi*ion2 [C:\Docunients and Se1ting3\OWNERV)esklc>p\kei!\STARTUP.A51] 



|)Fte £dt View Project Qabug Rash Perphwak lads £/CS Wndow Help 



_ 6> X 



n* 



<£ m m * | » jfcpF^n 



^J 



- H3 Source&oupl 

if 



FiM |^ u3e~ 



(■0HQD51 



Ibis file is pact of che C51 Cokpilec package 

Cepyci.ght (c) 1988-2005 Kail Elakttoniis GafcH and Kail Software, Inc. 

Vacsion 9.01 

*** <« Use Configuration Uisaid in Context Menu >» TT ' 

STARTUP »A51: This code is executed after processor ceset. 

To translate this file use A51 vich che following invocation: 

AS I STARTUP. AS 1 

To link the Modified STARTUP. OBJ die to youx application use the following 
L:<51 Invocation; 



S 



1 




For Help, press Ft 



■*" 'ZFal Drive 



J MyuJTOuler Mc-csoft Ao... f!i* tnall -||WI9. 



R/W 



Figure 2.4 Copying startup code to your project 



Step 5: Adding Your Program Source Code 

To accomplish this, follow the steps: 

■ Right click "source group 1" followed by 

■ Choose "Add Files to Group 'Source Group 1"' 

■ Set "Files of type" to "All files (*.*)" 

■ Select "Startup. a51" 

Observe the files getting updated in the target window. You will have 
to double-click on the C source file name displayed in the target window 
to view it. 

Step 6: Configuring and Building the Target 

Right click on target 1 in the target window, select the option for 
target 1, a window to choose the options for the target will be displayed. 
Here you can choose the microcontroller frequency, listing of files, output 
in hex, debug information, etc. 

The important point here is choosing the appropriate memory model. 



Integrated Development Environment 



25 



triall vVteionl [C:\Documents and Settings\OWNER\Desktop\keil\STARTUP.A51] 



[^Fie e* y&n Project Debug flash Peripherals loot gvcs window Help 

to s a cp «6 fe 



- h" 1 x 



-|j|x| 



^M 






- ?J Target 1 

- ta_ 
1 



ikhddsi 



; TMs tile is east o£ th 
ce for Target Target 1' 
Options Fcr Group 'Source Group 1' 



C5l Compiler package 
Kei.1 Elekcconik GabH and Keil Software, Inc. 



Oper Tile 
fgjgebuH target 
^BuH target 

£ :tco byild 



FT 



Add Fibs to Grotp "Souic? G'cuo I" 



IergetSj Groups,, Ffas... 
Fit* Id? RejTMveGroLp 'Source Group i' and t'sFfej 



n «i sard in Context Henw >» *** 
is executed after processor reset. 
st A51 with Che following invocation: 

IP.OEJ flit to yrjr ami LCftdOD USE the fcllcwiri] 




^ Include Dependencies 



^ 



~| \ B«iM fcCanwmi /, Fid .■■ R« / 



^ 



Add Fits to current Project Group 



R/W 



" . ' :l I ' ■■ 



J My Compute W Microsoft Wo... H»' trial! - .. 



Figure 2.5 Adding your program source code 



As per the on-line Keil IDE manual [28] C51 currently supports the 
following memory configurations: 

■ ROM: currently the largest single object file that can be produced 
is 64 K, although up to 1 MB can be supported with the BANKED 
model described below. 

■ All compiler output to be directed to EPROM/ROM, constants, 
look-up tables, etc., should be declared as "code". 

■ RAM: There are three memory models, SMALL, COMPACT, and 
LARGE 

■ SMALL: all variables and parameter-passing segments will be 
placed in the 805 l's internal memory. 

■ COMPACT: variables are stored in paged memory addressed by 
ports and 2. Indirect addressing opcodes are used. On-chip 
registers are still used for locals and parameters. 

■ LARGE: variables etc. are placed in external memory addressed by 
@DPTR. On-chip registers are still used for locals and parameters. 



26 



Development Flow for the Keil IDE 



;■■•' 1 1-.. i i 1B *\owNra\fic-.M 1 .| 



Qm* {« v*m from Djibug Pi** P***** Took SvCS window Htto 



Options for large! ' larsel 1' 



c 



IB iiu 




B««_(d 



Device Target | Qjipul Lelng C51 | A51 | BL51 Locale | BL51 Mac | Debug | UUtes | 
AbnelATB9E51 

Xl«l(MHz|: [SB U» OrvcNp flOM (ftiO-OtfFF) 



Memory Modot Smai variable* r> DATA 
Code Rom Sue: I Largs 84K progiarn 



Opmting syttan Norte 



"3 

3] 



OK 



Coned Default* 



~I \i»HA ComnwdA RrcuRkt / 



- * X 



_ a x 



Ulf-chio Co* nenoty 


Eprom | 
Epnm 


Start 


See: 


OH-chip xdoto irnomoij' 


Start . :* 




1 


Ram T 




L 


R«r,r 
Ran,p 


r Cede Banking 


BonkAiM | 


Start 


End; 


V 
V 




B«**r 







^ 



3 



d 




Figure 2.6 Configuring and building the target 



Table 2.1 Choosing the best memory model for your C51 program 



Model 



RAM supported 



Best for 



Worst for 



Small 
Compact 



Large 



Total RAM 128 bytes 

(8051/31) 

256 bytes off-chip, 128 

or 256 bytes on-chip 



64KB, 128, or 256 
bytes on-chip 



Code size up to 4 K 

High stack usage, pro- 
grams with large num- 
ber of medium speed 
8-bit variables 



Easiest model to use 



Global variable (be 
kept minimum) 
Rarely used in 
isolation, usually 
combined with the 
SMALL switch 
reserved for 
interrupt routines. 
Never used in 
isolation, combined 
with small and 
compact 



BANKED: Code can occupy up to 1 MB by using either CPU port 
pins or memory-mapped latches to page memory above x FFFF. 
Within each 64 KB memory block a COMMON area must be set 
aside for C library code. Inter-bank function calls are possible. 



Integrated Development Environment 



27 



? T ' Trail |jVis1on2 [C:\DocumenU and S«tting$lOWNER\DeskT©p\kellto.c] 



£\m E* Sw» Prow* Qebua Rs* Perjpbsrab loots SVCS Wndw Hob 



* £fe 



£J /4 9fc| 



^* 



• «l CIS 6fe ft 



, ; t \ Tanatl 



' 



:_i 



-^ Sourcs Group 1 
£] STMTUP.A51 

- j£|M 

Q resh.h 



Br*. Iff UiTT JjL J 



// Sinpie ptogcaa explain the Pott ConCiguracilon of the 
// TC3-51 Faaily. Which outs the data. 
*!inrluJ»<neg52.h> 
void main(void) 

{ 

P1-0K22; 

P2-5X33J 

} 



Oil* 



_|gJ jC| 



1 



^ 



3 



Build target 'Target 1' 

compiling a.c. . . 

linking. . . 

Program Size: data-9.0 xdata-0 code-22 

"trail" - Q Error (a). Warning (a). 



~| VIMWA ConffWHlA FWinFlM / 



L:B C:5 




u 



R/W 



- GMeriDl 



i |f» trail - t*VWon 



Figure 2.7 Compiling your program by pressing F7 



Step 7: Compile Your Program by Pressing F7 

Either press F7 or click on build target in the target window to compile 
your program. The output window will show the errors or warnings if 
any. You can also see the size of data, code, and external data, which is 
of immense importance since your on-chip memory is limited. 

Step 8: Working in Simulated Mode 

Once the program is successfully compiled, you can verify its func- 
tionality in the simulated mode by activating the debug window. For 
this press CTRL + F5 or go to the menu option "Debug" and select 
"Start and Stop Debug Section". Press Fll for single stepping or F5 
for execution in one go. Go to the menu item "Peripheral" and select 
the appropriate peripherals to view the changes as the program starts 
executing. 

Terminating the debug session is equally important. Click on "stop 
running" or ESC key to halt the program execution. You can make 
the changes to the program after coming out from the debug session 



28 



Development Flow for the Keil IDE 



Iruil ■ fjVnion? [C \Documenls and Settings \OWNER\Desklop\keil\d.cl 



Q* tdlt JTIew Protect Qebug Flash Peripherals look JVC5 W«oW tNo 



'_ rT X 



-1*1 x 



^1 



Interrupt Sytlom 




^ t V n fc p 



// Staple pcag cut explain the Poet. Configur >CLian aC 
ft HC3-51 Family. Hblca outs zht data. 
J include<r egS2 . h> 



11^ ff... [IJJB I j« 



Running in Eval Mode (2 
Load "C:SSReilNNtraal" 



Vccta Mode j Reg 1 Ena | Pri [ 



0003H 

OOOGH 
JUIJH 
001 BH 
QD23H 
QQ23H 



r ea 



Satoc tad Intern^* 

r ito r ieo 



r EXD Ph:[ft 



3 



Parallel Port v 1 



Pet 2 



P£|Qx33 

Pew 0*33 



7 BUt 

rrwwrrw 



s.^ ^- 



P.ii.illelPuri 1 



Pat" 



PI- 0x22 



7 Bite 

I I kll I M 



Ptor|OC2 | | kl I I kl 



1 




ASM ASSIGN BreakDisable BreakEnable BreatKill BreekList BreakSet BreakAccess 
I -H^IH^I V lMMAriiiiiiiA Rn.it He«~7 ~ ~~ Hi 




L:7C!l 



IVW 



, start ■-' 



- ..'■IjlL-i 



pi- -I-V ■ :. • ■ 



- j n 



Figure 2.8 Simulation mode of Keil 



by pressing start /stop debug session. Few iterations through the 
above-mentioned process will make your program completely bug- free 
and save your time and other resources on the actual hardware. 

Step 9: Actual Dumping of the Code 
in Microcontroller's On-chip Memory 

There are different mechanisms for this. Some programmers use ready- 
made programmers to program the microcontroller. If you are interested 
in purchasing one for your project, the list is enclosed. Design of vari- 
ous programmers has also been given at Wichit Sirichote's webpage at 
http://www.kmitl.ac.th/~kswichit%20/. 



Chapter 3 

Art of C Programming for Microcontrollers 



There are large number of textbooks and data sheets which give 
an overview of 8051 architecture, pinout, and other peripheral details. 
However, with the Keil IDE, you can take the benefit of the header 
files and need not remember the details like the port address, timer 
counter addresses, etc. The CA51 Compiler Kit for the 8051 microcon- 
troller family supports all 8051 derivatives including classic devices and 
IP cores from companies like Analog Devices, Atmel, Cypress Semicon- 
ductor, Dallas Semiconductor, Goal, Hynix, Infineon, Intel, OKI, Philips, 
Ailicon Labs, SMSC, STMicroelectronics, Synopsis, TDK, Temic, Texas 
Instruments, and Winbond. 

3.1 Familiarizing with Your Compiler 

Capabilities 

The C for microcontrollers and the standard C syntax and seman- 
tics are slightly different. The former is aimed at the general purpose 
programming paradigm whereas the latter is for a specific target micro- 
controller such as 8051. The underlying fact is that everything will be 
ultimately mapped into the microcontroller machine code. If a certain 
feature such as indirect access to I/O registers is inhibited in the target 
microcontroller, the compiler will also restrict the same at higher level. 
Similarly some C operators which are meant for general purpose com- 
puting are also not available with the C for microcontrollers. Even the 
operators and constructs which may lead to memory inefficiency are not 
available in C programming meant for microcontrollers. Be aware that 
the target code should fit in the limited on-chip memory of the proces- 
sor. Even the I/O functions available in standard C such as printf() or 
scanf() are either not made available in C compilers for microcontrollers 
or advised not to use them. These functions eat up lot of memory space 
and are not time-efficient owing to the dragging of supporting func- 
tions like floating point routines and lot of delimiters. Another striking 
difference in case of embedded systems programs is that they do not 

29 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 29-36. 
© 2007 Springer. 



30 Whether to Use Headers or Not? 

have the umbrella or support of the operating system. The programmer 
has to be accustomed with the absence of system calls which makes life 
easy in traditional C. 

The C for microcontrollers is more closer to the assembly language 
than the conventional or traditional C. Few examples to support the 
above statement are presence of arithmetic/logic/bitwise operations to 
resemble machine operations, Use of pointers which corresponds to mem- 
ory access at machine level etc. The detailed information regarding the 
features of 'C supported may be found in the document C x 51 Compiler 
User's Guide for Keil Software [28]. 

3.2 Whether to Use Headers or Not? 

As a professionally embedded systems developer one can write a stand- 
alone 'C code, requiring no header files, and it will compile correctly with 
the Keil C51 compiler. However, this requires a through study of the tar- 
get microcontroller architecture. With the large number of derivatives 
of the 8051, it is difficult to remember the on-chip resources, e.g., the 
MCS-51 versions from Atmel such as AT89C2051 or AT89C51 have two 
timers while the other members such as At89C52 or AT89S53 have three 
timers. Therefore, although there is little memory space overhead, it is 
advisable to use the header files which defines all the on-chip resources 
for the target microcontroller, e.g., whenever you choose the target de- 
vice such as AT89C52, Keil IDE gives the information regarding all its 
on-chip resources in the window at the right side as shown in Figure 3.1. 

You can observe another advantage of working with the header file. 
Define the header file <REG51.h> or <REG52.h> in the program win- 
dow and select the target device as 80C51. Now open the header file, 
which will reflect all the on-chip resources of 80C51 as shown below: 

/• 

REG51.H 

Header file for generic 80C51 and 80C3f microcontroller. 

Copyright © 1988-2002 Keil Elektronik GmbH and Keil Software, Inc. 

All rights reserved. 



#ifndef __REG51_H„ sbit EX1 = OxAA; 

#define __REG51_H__ sbit ETO = 0xA9; 

/* BIT Register */ sbit EXO = 0xA8; 
/* BYTE Register */ /* PSW */ 

sfr P0 = 0x80; sbit CY = 0xD7; /* IP */ 

sfr PI = 0x90; sbit AC = 0xD6; sbit PS = OxBC; 



Art of C Programming for Microcontrollers 



31 



sfr P2 = OxAO; 
sfr P3 = OxBO; 
sfr PSW = OxDO; 
sfr ACC = OxEO; 
sfr B = OxFO; 
sfr SP = 0x81; 
sfr DPL = 0x82; 
sfr DPH = 0x83; 
sfr PCON = 0x87; 
sfr TCON = 0x88; 
sfr TMOD = 0x89; 
sfr TLO = 0x8A; 
sfr TL1 = 0x8B; 
sfr THO = 0x8C; 
sfr TH1 = 0x8D; 
sfr IE = 0xA8; 
sfr IP = 0xB8; 
sfr SCON = 0x98; 
sfr SBUF = 0x99; 

sbit TB8 = 0x9B; 
sbit RB8 = 0x9A; 



sbit FO = 0xD5; 
sbit RSI = 0xD4; 
sbit RSO = 0xD3; 
sbit OV = 0xD2; 
sbit P = OxDO; 



/* TCON 
sbit TF1 
sbit TR1 
sbit TFO 
sbit TRO 
sbit IE1 = 
sbit IT1 = 
sbit IEO = 
sbit ITO = 



= 0x8F 
= 0x8E 
= 0x8D 
= 0x8C 
= 0x8B; 
= 0x8 A; 
= 0x89; 
= 0x88; 



/* IE * 
sbit EA = OxAF; 
sbit ES = OxAC; 
sbit ET1 = OxAB; 
sbit TI = 0x99; 
sbit RI = 0x98; 



sbit PT1 
sbit PX1 
sbit PTO 
sbit PXO 



OxBB; 
OxBA; 
0xB9; 
0xB8; 



/* P3 V 

sbit RD = 0xB7; 
sbit WR = 0xB6; 
sbit Tl = 0xB5; 
sbit TO = 0xB4; 
sbit INT1 = 0xB3; 
sbit INTO = 0xB2; 
sbit TXD = OxBl; 
sbit RXD = OxBO; 



/* SCON V 
sbit SMO = 0x9F 
sbit SMI = 0x9E 
sbit SM2 = 0x9D 
sbit REN = 0x9C 



#endif 



triad uVision? [Texl2] 



[Uete E* S*w Eroject G*ufl >%** Perjpherab look £VC5 HJndow tMp 

Sg£H 



Options for Target 'Target 1' 



c 



- :-J Target 



Files 



- J X 



- \& x 



Device | T*flftt | Output | Ltstng | CS1 A51 

Database: |~~ 

Vendor Atroel 
Device: AT89C52 
Famly; MCS-51 



BL51 Locate BL51 Msc | Debug | UtiWe« | 

r U*e Extended Linker ILX51) instead of BLS1 



_| AT83C51R C 

l iaiaaaaJ 
_J AT89C55 
_]AT89C55v/D 
_JATB9F51 
QAT89F52 
_J AT89LS51 
CJ AT89LS52 
DAT89LV51 
_|AT89LV52 
LJAT89LV55 
LJAT89LV55WD 
[J AT89S4D12 
~1 ATfWRI 



v 



6051 beted Ful S lafc CM OS controter with T hree-Levd Program Memory Loci 
32 I/O lines, 3 Timers/Counters, B Interrupts souces 
8 K Flesh Memory, 256 Bytes Orvchp RAM 



OK 



Cancel 



Defaults 



H i MM A Command A Find h Bet T 



GMail r ■ f My Computer U" Microsoft Wo,,. fl'tn-jl] -|jVisi, 



1 



R/W 



Figure 3.1 On-chip resources in the window 



32 



Whether to Use Headers or Not? 



Now select another target device 80C52. This device has three timers. 
Now the header file will automatically update the database of on-chip 
resources pertaining to this device as shown below. 



REG52.H 

Header file for generic 80C52 and 80C32 microcontroller. 

Copyright © 1988-2002 Keil Elektronik GmbH and Keil Software, Inc. 

All rights reserved. 



#ifndef __REG52 _H__ 
#define __REG52 _H_. 

/* BYTE Registers * 
sfr P0 = 0x80; 
sfr PI = 0x90; 
sfr P2 = OxAO; 
sfr P3 = OxBO; 
sfr PSW = OxDO; 
sfr ACC = OxEO; 
sfr B = OxFO; 
sfr SP = 0x81; 
sfr DPL = 0x82; 
sfr DPH = 0x83; 
sfr PCON = 0x87; 
sfr TCON = 0x88; 
sfr TMOD = 0x89; 
sfr TLO = 0x8 A; 
sfr TL1 = 0x8B; 
sfr THO = 0x8C; 
sfr TH1 = 0x8D; 
sfr IE = 0xA8; 
sbit EXO = IE A 0; 



IP 



A 



sbit PT2 = IP A 5; 



sfr IP = 0xB8; 
sfr SCON = 0x98; 
sfr SBUF = 0x99; 

/* 8052 Extensions */ 
sfr T2CON = 0xC8; 
sfr RCAP2L = OxCA; 
sfr RCAP2H = OxCB; 
sfr TL2 = OxCC; 
sfr TH2 = OxCD: 



/* BIT Registers */ 
/* PSW */ 
sbit CY = PSW A 7; 
sbit AC = PSW A 6; 
sbit FO = PSW A 5; 
sbit RSI = PSW A 4; 
sbit RSO = PSW A 3; 
sbit OV = PSW A 2; 
sbit P = PSW A 0; 
//8052 only 
sbit RCLK = 
T2CON A 5; 
sbit TCLK = 
T2CON A 4; 



/* TCON 
sbit TF1 
sbit TR1 
sbit TFO 
sbit TRO 
sbit IE1 = 
sbit IT1 = 
sbit IEO = 
sbit ITO = 



= TCON A 7 
= TCON A 6 
= TCON A 5 
= TCON A 4 
= TCON A 3; 
= TCON A 2; 
= TCON A l; 
= TCON A 0; 



/* IE */ 

sbit EA = IE A 7; 
sbit ET2 = IE A 5; 
//8052 only 
sbit ES = IE A 4; 
sbit ET1 = IE A 3 
sbit EX1 = IE A 2 
sbit ETO = IE A 1 



Art of C Programming for Microcontrollers 



33 



sbit PS = IP A 4; 
sbit PT1 = IP A 3; 
sbit PX1 = IP A 2; 
sbit PTO = IP A 1; 
sbit PXO = IP A 0; 

I* p3 *i 

sbit RD = P3 A 7; 
sbit WR = P3 A 6; 
sbit Tl = P3 A 5; 
sbit TO = P3 A 4; 
sbit INT1 = P3 A 3; 
sbit INTO = P3 A 2; 
sbit TXD = P3 A 1; 
sbit RXD = P3 A 0; 



sbit EXEN2 
T2CON A 3; 
sbit TR2 = 
T2CON A 2; 
sbit C.T2 = 
T2CON A l; 
sbit CP _RL2 
T2CON A 0; 

#endif 



/* SCON 
sbit SMO 
sbit SMI 
sbit SM2 
sbit REN 
sbit TB8 
sbit RB8 
sbit TI = 
sbit RI = 



= SCON A 7 
= SCON A 6 
= SCON A 5 
= SCON A 4; 
= SCON A 3; 
= SCON A 2; 
SCON A l; 
SCON A 0; 



/* pi 7 

sbit T2EX = P1 A 
//8052 only 
sbit T2 = P1 A 0; 
//8052 only 



i; 



/* T2CON 7 

sbit TF2 = T2CON A 7; 

sbit EXF2 = 

T2CON A 6; 



Note the bold letters which are exclusively added for the 80C52 only. 



34 Differences from ANSI C 

In nutshell the first program sentence will be always a statement 
^include <reg51.h> for MCS-51 family. The standard initialization 
and startup procedures for the 8051 are contained in startup. a51. This 
file is included in your project and will be assembled together with 
the compiled output of your C program. For custom applications, this 
startup file might need modification, because the stack or stack space, 
etc., are predefined as per the memory model. 

3.3 Basic C Program Structure 

Listing below shows a basic structure for a C program. 



//Basic blank C program that does nothing 
// Includes 



^include <reg51.h> // SFR declarations 
void main (void) 

{ 

while(l); 

{ 

body of the loop // Infinite loop 

} 

} // match the braces 



Note: Similar to conventional C, all the variables must be declared at 
the start of a code block, you cannot declare variables in the midst of 
the program statements. 

3.4 Differences from ANSI C 

There are marginal differences of Cx51 compiler from the ANSI 
C compiler. These differences are twofold, viz. compiler related and 
library related. The details are given in the help menu of the Keil 
IDE. Frequently used things are given below for ready reference of the 
programmers. 

Variable Types 

The Keil C compiler supports most ANSI C variable types and in 
addition has several of its own. 



Art of C Programming for Microcontrollers 

Standard Types 



35 



Only floating point variable types of ANSI C are not supported by 
Keil C compiler as the basic 8051 core is not efficient for the same. The 
types supported are as follows: 



Type 


Bits 


Bytes 


Range 


Char 


8 


1 


-128 to +127 


Unsigned char 


8 


1 


to 255 


Enum 


16 


2 


-32,768 to +32,767 


Short 


16 


2 


-32,768 to +32,767 


Unsigned short 


16 


2 


to 65, 535 


Int 


16 


2 


-32,768 to +32,767 


Unsigned int 


16 


2 


to 65, 535 


Long 


32 


4 


-2, 147, 483, 648 to 2, 147, 483, 647 


Unsigned long 


32 


4 


to 4, 294, 697, 295 



Keil Types 

The bit and Boolean capabilities of MCS-51 family are well explored 
by the Keil C Compiler by adding several new types. Some of them are 
as follows: 



Type 


Bits 


Bytes 


Range 


Bit 


1 





to 1 


Sbit 


1 





to 1 


Sfr 


8 


1 


to 255 


Sfl6 


16 


2 


to 65, 535 



Of these, only the bit type works as a standard variable. The other 
three have special behavior that a programmer must be aware of. The 
bit type gets allocated to the 805 l's bit-addressable on-chip RAM. Note 
that you cannot declare a bit pointer or an array of bits. The special 
function registers are declared as a sfr data type in Keil C. If you give 
the address of the SFR as 0x80h then it gets allocated to port of 
8051. Extensions of the 8051 often have the low byte of a 16 bit register 
preceding the high byte. Therefore the timer for instance should be 
declared as a 16-bit special function register, sfr 16, giving the address of 
the low byte: 



sfrl6 TMRORL = 0x8A; 
sfrl6 TMRO = 0x8B; 



// Timer reload value 
// TimerO lower 



36 



Differences from ANSI C 



Keil Variable Extensions 

In consistent with the 8051 architecture Keil offers various types of 
variable extensions. Following table summarizes the same. Assembly 
language mnemonics are used to indicate the subsequent meaning of 
the variable extension used. 



Extension 


Memory Type 


Related ASM 


Data 


Directly-addressable data mem- 
ory (data memory addresses 
0x00-0x7F) 


MOV A, 056h 


Idata 


Indirectly-addressable data 
memory 


MOV R0, #09Ah 




(data memory addresses 


MOV A, R0 




OxOO-OxFF) 




xdata 


External data memory 


MOVX @DPTR 


Code 


Program memory 


MOVC ©A+DPTR 



In case the memory type extension is not specified, the compiler will 
decide which memory type to use automatically, based on the memory 
model (SMALL, COMPACT, or LARGE, as specified in the project 
properties in Keil). 



Chapter 4 

Exploring the Capabilities of On-Chip 
Resources Programming for I/O Ports, 
Interrupts and Timer/Counter 

4.1 Importance of Ports 

Ports are the means through which the microcontroller communi- 
cates with the outside world. They are the most common I/O devices. 
An interesting point to note is that the number of I/O pins or ports 
are decided by the packaging style of the microcontroller. A compari- 
son of various packages is given below: A new trend in 8-bit controller 
design is to place the chip inside a 20-, 16-, or even 8-pin PDIP or SOP 
package, allowing for very small and cheap embedded systems to be 
constructed [29]. 

Fortunately most of the derivatives of the 8051 are generally offered 
in 40-pin DIP or 52-pin PLCC packages and there is not much varia- 
tion in terms of package pinouts. The obvious advantage of the upward 
compatibility maintained into the different versions of the 8051, is 
the direct replacement of the latest advanced 8051 from Intel to its 
cheap predecessor without even changing the printed circuit board. 
This "drop-in" replaceability is rarely true of other microcontroller 
architectures [30]. 

Playing with the Ports 

Program 4.1: Simulated Port Testing Using Keil 

The program illustrates simple port programming in a simulated mode 
using the Keil compiler. A sample data is sent to the port and the output 
is observed in the simulator window. You may as well connect LEDs to 
observe the output. 



37 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 37-67. 
© 2007 Springer. 



38 



Importance of Ports 



Table J^.l Comparison of the packages 



Package 


Number of 
pins 


Features 


Applications 


PDIP (plastic 


8-64 


Through hole type 


Prototype or 


dual in-line 




devices, dense style 


hobbyist type 


package) 




package, pins/area 


applications, 






ratio of PDIP not very 


smaller 8-bit 






efficient 


microcontrollers 


PLCC (plastic 


20 up to 


Through hole type 


Small, 


leaded 


80+ 


devices 


low-pincount 


chip-carrier) 






microcontrollers 


SOIC (small 


8-64 pins 


Pins are spaced much 




outline 




closer together, 




integrated 




package designed to be 




circuit) or 




soldered directly to the 




"SOP" (small 




top of a board 




outline 








package) 








QFP (quad flat 


8-220+ 


Sophisticated soldering 


16- to 32-bit 


package) 


pins 


workstation required to 


microcontrollers 






deal with the pins 


to 64-bit 






closely spaced 


superscalar 
microprocessors 



Program Source Code 



#include<reg51.h> 



void main(void) 

{ 

PI =0x44; 
P2=0x55; 



} 



/* special function register declarations for the 
intended 8051 derivative. The header file 
contains the definitions of special function 
registers (SFRs) and other functions. */ 
// Start of the Main function. 

/*Send 44H to port PI*/ 
/*Send 55H to port P2*/ 

// End of the main function. 






The screenshot of simulation window shown in Figure 4.1 the data 
delivery to port 1 and 2. 



Exploring the Capabilities of On- Chip Resources Programming 



39 



PP" triaM |jVision2 [C:\Documents and Settings\OWNERWesktop>keil\trial1 .c] 



File £d* View Project fcebug Flash Peripherals loots 3VCS ^ndow &*> 

(asm ojs «& fc 



-il^C* 



-S XI 



^#* 







K#m 



^jxj 



3] 



Register 



Value 



- Regs 

rO 
rl 
r2 

* 

; 

- Sys 

a 
b 



OkOO 
OkOO 
OkOO 
OkOO 
OkOO 
OkOO 
OkOO 
OkOO 

OkOO 
0x00 a 



Irks #.„ ^B... 



#include<reg5i.h> 



void nain(void) 

{ 

r Pl-0x44; 
P2-0X55; 



/* special function register declarations 

for the intended 8051 derivative. 

The header file contains the definitions of Special 

Function Registers (SFRs) and other functions. •/ 

// Start of che Rain function. 

/•Send 44H to pott Pl*/| 
/•Send SSH to port P2V 



) 



J± 



Parallel Port 1 



Port! 



« rs^T- 7 Bin 
pbK |ok44 ri?rrrr5rr 



Parallel Port 2 X 


Port2 

PZ 0x55 


7 B»» 







1 ki ki i*r r* 
n*rMrr*n? 


PhK|0x55 



31 



ajlRunning with Code Size Limit: 2K 

J Load "C:\\Documents and Settings\\OWNER\\Dosktop\MceilN\triaLl" 






ASM ASSIGN BreakDisable BreakEnable BreakKill BreakList BreakSet BreakAccess 
Bu4d A C*mrnmd /, find in Bet / ~|L* 



Ready 



L:8C:44 



. start 



•*■ GMail Drive 



J My Computer 



IV MkfOSoftWO.., 



$ 



RJW 



I* trial! 



Figure 4-1 Screenshot of simulation window showing the ports 



Program 4.2: Sending Out Different Contents to Port 1 

Different data bytes are sent to port 1 after delay. The results can be 
checked in the simulation window, which shows the changing of data on 
the port 1 lines. 

Program Source Code 



#include <REG52.H> 
void delay (void); 



void delay (void) 

{ 

int i; 

for (i=0;i<30000;i++); 

for (i=0;i<30000;i++); 

} 



invoking delay function 



40 



Importance of Ports 



void main (void) 

{ 

while(l) 

{ 

PI = 0x01 

delay (); 

Pl= 0x02; 

delay (); 

Pl=0x04; 

delay (); 

Pl=0x08; 

delay (); 

Pl=0xl0; 

delay (); 

Pl=0x20; 

delay (); 

PI =0x40; 

delay (); 

Pl=0x80; 

delay (); 

Pl=0x40; 

delay (); 

Pl=0x20; 

delay (); 



Starting of the main function. 



Out 01 on the port 1. 
Delay function. 
Out 02 on portl. 



} 



Pl=0xl0; 

delay (); 
Pl=0x08; 
delay (); 
Pl=0x04; 
delay (); 
Pl=0x02; 
delay (); 
Pl=0x01; 
delay (); 

} 



termination of the while loop, 
termination of the main function. 






Exploring the Capabilities of On- Chip Resources Programming 



41 



Program 4.3: Generating Square Wave on the Port 

A number is assigned to port 1 which simulates input operation. The 
port 1 contents are complemented and sent to the port 1. The square 
wave can be observed on port 1 by using CRO. 

Program Source Code 



#include<reg51.h> 
void delay (int); 
void delay (int k) 

{ 

int i,j; 

for (j=0;j<k+l;j++){ 

for (i=0;i<100;i++); 

}} 

void main (void) 

{ 

int N1=0; 

number. 

while(l) 

{ 
P1=N1 ; 

Nl =~N1; 

delay (10); 

PI = Nl; 
delay (10); 



// Start of the main function. 



Defining the integer value for the 



// Infinite loop 

: Assign Nl to port PI*/ 

/* Complement Nl*/ 
/* Delay which defines the on and 

off time for the Square wave. */ 

/*Send it to port PI*/ 



} 



End of while loop. 



} 



End of main. 






42 



Importance of Ports 



Program 4.4: Sending Data to the Ports by Assigning 
Values to a Character 

This program illustrates assigning values to the character and then 
sending it to the port. Here the characters a, b, c are assigned with the 
Hex numbers and these values are sent to ports. 

Program Source Code 

#include<REG51.H> 



void main(void) 

{ 

char a,b,c; 



Define the characters a, b and c. 



} 



while(l) 
{ 



} 



a=0x01; 

b=0x02; 

c=0x03; 

P0=a; 

Pl=b; 

P2=c; 



Assign 01H to 'a' */ 

Assign 02H to c b' */ 

Assign 03H to 'c' */ 

Send value assigned to 'a' to port : 

Send value assigned to 'b' to port 1 : 

Send value assigned to c c' to port 2 H 






Program 4.5: Configuring the Ports as Input 

By default all the ports act as output port. They can be configures 
as input by writing FFH to them. The programmer need not bother 
about the actual SFR address. Thanks to the header file included at 
the top. 

The actual input operation is simulated by assigning values to the 
variables. The actual DIP switch interfaced as input device is covered 
further in the text. 

Program below illustrates the simplest way to define the ports as an 
input port and how to read the input from the ports and the result is 
observed in the simulation window. 



Exploring the Capabilities of On- Chip Resources Programming 



43 



Program Source Code 

#include<REG52.H> 



void main (void) 

{ 

char N1,N2,N3; 

P0=0xFF; 
Pl=0xFF; 



while(l 
{ 



Defining the characters. 



set PO as input 
// set PI as input 



I 



} 



N1=P0; 
N2=P1 

N3=N1+N2; 
P2=N3; 



Input value of PO in Nl*/ 
'Input value of PI in N2*/ 
Addition of the two inputs 
Send value of N3 to port 2* 



Program 4.6: Software Delay Loops Combined 
with I/O Ports 

The program demonstrates generation of software delay using two 
loops operating on a single count. An integer x is declared and assigned 
a count equal to 10,000. "While(l)" loop keeps the program in continues 
loop. The other two loops are conditional with the first loop executes 
when "while(x > 1)" is valid, i.e., when x is greater than 1. The other 
loop executes when x is less than 10,000. Note the usage of decrement 

( ) and increment (++) operators. Both these loops are embedded in 

the main loop. 

To observe the output of this connect the port 1 to LEDs. The output 
can also be verified in the simulator window. 

Program Source Code 

^include <reg51.h> 



void main (void) 



44 Importance of Ports 

{ 

int x = 10000; 
while(l) 

{ 

while(x > 1) /* 10000 count delay */ 

{ 

PI = OxOf; /* set leds on PORT1 to 00001111 */ 

x--; /* decrement x */ 

} // end of first loop 

while(x < 10000) /* 10000 count delay */ 

{ 

PI = OxfO; /* set leds on PORT1 to 11110000 */ 

x++; /* increment x */ 

} // end of second loop. 

} // End of open loop. 

} // End of main. 

Program 4.7: Alternate Method of Software Delay 
Generation with Port Programming 

This program illustrates the use of "FOR" construct for delay gener- 
ation which toggles only one port pin (Pl.l). 

Note the use of ! operator for complementing the variable. 

Program Source Code 

*& *& *& ^i^ *& *& ^i^ *& *& ^i^ *& *& *& *& *& "^c "^^ *& ^^ *& ^i^ *& *& ^i^ *& *& *& *& *& "^c *& *& "^c "^c "^c "^c *& *& "^c *& *& *& ^i^ ^^ *& *& *& "^c *& *& *& *& *& *& "^c *& *& "^c *& *& *& 

#include<reg52.h> 

sbit vin = P1 A ; //Pin declaration vin = port 1 pin 

void main(void) 

{ 

int i; 

vin = 1; //Make port pin P1.0 high 

while(l) 

{ 

for(i=0;i<=3000;i++); // Delay generation 



Exploring the Capabilities of On- Chip Resources Programming 45 

for(i=0;i<=3000;i++); 

vin = !vin; //complement port pin P1.0 after 

delay 

} 



+5V 

o 



470 O 



Controller 



Port Pin 



v^v LED 



Figure 4-2 LED interface to microcontroller port pin 



Program 4.8: Shifting the Port Contents to Left 

This program shifts the contents of port to left. The result may be 
seen in the simulation window by opening the menu option for periph- 
erals. The port bits goes on changing one by one. 

Program Source Code 

#include <REG52.H> 
void main (void) 

{ 

int i; 
char Nl; 

while(l) 

{ 

Nl=0x01; 

while(Nl!=0x00) //Continue the loop till Nl not 

equal to 00H 
//When N1=00H program exits 
the loop 

{ 



46 LED Interfacing 

for(i=l;i<10000;i++); //delay 

P0=N1; //Send value of Nl to 

port 

N1=N1«1; //Left shift Nl by one 

bit position 

} 
} 

} /* try right shift by using right shift operator c >>' */ 

4.2 Simple Ideas for Port Expansion 

The users are worried when the number of I/O port lines poses a bot- 
tleneck for applications especially in the areas of robotics and industrial 
process control. In these types of application domains the user may either 
go for another microcontroller with more I/O pins or interface chips like 
PPI8255 to the existing ports. However, there are many simple methods 
to expand the port. Few of them tried by embedded system developers 
are given herewith the source URL, so that the user may adopt them 
for their applications. 

■ 2 Wire Input/Output for 8051 type CPUs [31]. 

The application note explains the use 12 C bus interfaced to shift 
registers for expansion of ports. 4094 shift registers have been used 
with the additional feature of tri-state output at power up until 
the CPU has written valid data, preventing power up "glitches" . 

■ 8051 I/O expansion using common shift register chips [32]. 

The application note gives complete schematic and assembly code 
to expand 8051 I/O using shift registers. 

4.3 LED Interfacing 

The simplest applications such as port testing or indication may only 
require on/off-type LEDs for displaying status information. For such ap- 
plications, LEDs can be controlled directly by a general-purpose I/O pin 
capable of sourcing or sinking the necessary current required for lighting 
the LED, typically between 2 mA and 10 mA. LEDs have exponential 
voltage-current characteristics, that means around the operating point 
there is rapid increase in current for little increase in voltage. Therefore 
ideally a constant current source is desirable to drive the LEDs. How- 
ever, the same can be simulated by using a series resistor connected to 
the port pin so that the voltage across the LED will be fairly constant. 



Exploring the Capabilities of On- Chip Resources Programming 



47 



■5V 



3301 i 



+Vcc 






1 330Q 



LED1 WV^ W W W W W W LED8 




Figure 4-3 Interfacing diagram for a LED 



Generally a common anode connection is chosen in a digital environ- 
ment because pull-down is much easy as compared to push-up. If an 
external power supply is used, then the corresponding brightness will be 
much better as compared to driving logic 1 through the microcontroller 
port pins. From a programmer's point of view this means by writing 
logic '0' the LED will glow (see Figure 4.3). 

Three things are required for working with the LEDs: the driving 
voltage, the current to be passed, and the forward voltage drop across 
the LED. For a blue LED with 12 V supply, in order to glow a single 
LED, a current of the order of 20 mA is required to be passed. With the 
forward voltage drop of 3.4 V, the value of the resistor can be calculated 
using simple Ohm's law as follows: 



R = Vs-Vl/I 



Where Vs = the supply voltage 

Vl = voltage across the LED 
I = Current through the LED 



48 Different Programs for LED Interfacing 

The details of LED interfacing to microcontroller have been covered 
at several references. The microcontrollers I/O port pin is configured as 
an output. The choice of the series resistor and its wattage is covered in 
many standard books. 

4.4 Relevance of LEDs in Today's Lightening 
Industry 

Street lighting is fast emerging as a potentially strong market for 
LEDs, since these devices have reached a level of output and efficiency to 
make them viable replacements for incumbent lighting technologies. The 
adavntages of LED-based street lights are reduced energy consumption, 
less maintenance, and better light quality [33]. Novel interfacing tech- 
niques based on microcontroller are emerging which ranges from simple 
low-cost current limiting resistors to dynamic constant current utilizing 
PWMs and analog-to-digital converters. With HB-LED lighting requir- 
ing the use of low-voltage electronic control, low-cost microcontrollers 
are useful in bringing additional compelling features to household light- 
ing. Microcontrollers are making it easier for lighting designers to in- 
corporate a reliable connectivity interface such as DALI and DMX512 
that will provide the backbone for adding remote user controls [34] . The 
above mentioned interfaces are based on packet-based system to deliver 
the data to the LED matrix. The technique has been covered in depth 
in this chapter. 

4.5 Different Programs for LED Interfacing 
Program 4.9: Blinking LED 

This program illustrates simple LED blinking at a constant interval. 
A simple technique of complementing a bit is used with changing soft- 
ware delay. The hardware shown Section 4.3 is used. 

Program Source Code 

^include <REG52.H> /* special function register declarations 

for the intended 8051 derivative */ 
void delay (void); /* declaring a delay routine for blinking 

interval 



void delay(void) 

{ 

int i; 



Exploring the Capabilities of On- Chip Resources Programming 



49 



for (i=0;i<30000;i++); 
for (i=0;i<30000;i++); 

} 

void main (void) 

{ 

bit my bit; 
mybit = 1; 



count 



while (1 

{ 

mybit = ! mybit; 
PI = mybit; 
delay (); 

} 
} 



// invoking main function. 



define the bit as a mybit. 
assign the mybit a logic high 
indefinite loop 



complement the bit 
send the complemented bit to port 1 
invoke the delay routine 
termination of the while loop 
termination of the main function 



Program 4.10: Scrolling LED 

This program illustrates the interfacing of LED with scrolling pattern. 
The display appears as if the LED is shifting. The LED connected to 
the port glows one by one. A software delay is used to define scrolling 
interval. 

Program Source Code 

*& *& *& *& *& *& *& "^c "^c *& ^i^ *& *& "^c "^c "^c "^c "^c "^c *& *& "^c ^i^ *& *& *& *& *& *& *& *& *& *& *& *& *& "^c *& *& "^c *& *& *& *& "^c *& *& *& *& *& *& *& *& *& *& 

#include <REG52.H> 



void main (void) 

{ 

int i; 
char Nl; 



define the integer number 
//define the character to assign the 
hex number 



while(l) 

{ 

Nl=0x01; 
while(Nl!=0x00) 

{ 

for(i=l;i<10000;i++); 



routine for scrolling interval 



50 



Different Programs for LED Interfacing 



} 



} 



} 



P0=N1; // display the LED corresponding 

toNl 
N1=N1>>1; //shift right by one 






Note: Similarly one can write the program for the Shifting the LED 
in the reverse order. 



Program 4.11: Exploring Bit Capabilities 
of the Microcontroller 

This program makes use of the microcontroller's bit programming 
capability. Here the single port pin is used as an output. The program 
toggles the single port pin to give a continuous on/off pattern on pin 
Pl.l. Input from P1.0 is simulated. 

Program Source Code 

"^l^ "^l^ *& *& "^l^ *& *& *& "^£ *& "^£ "^£ "^r£ *& *& *& "^£ "^l^ *& "^£ *& "^£ "^£ "^l^ *& "^£ *& "^£ *& "^£ "^£ *& "^£ *& "^C "^£ *& *& *& "^l^ "^l^ "^l^ "^l^ "£? "^£ *& "^£ *& "^l^ "^£ *& ^l^ *& *& "^l^ "^£ *& 



#include<reg52.h> 
sbit van= P1 A 0; 
sbit new = P1 A 1; 

void main(void) 

{ 

int vinod; 
vinod = 0x00; 
while(l) 

{ 

van = vinod; 

new = vinod; 
vinod=!vinod: 



} 



/* Pin declaration vinod = port 1 pin 0*/ 
/* Pin declaration new = port 1 pin 1*/ 



} 



// Define the int vinod 
Infinite loop (i.e.,countinuos loop) 



Simulating input from port pin P1.0 and 
assigning the same to character van */ 

/* send output to portl pinl */ 
//compliment vinod 
// end of loop 

// End of main 






Exploring the Capabilities of On- Chip Resources Programming 51 

4.6 More Projects on LED Interfacing 

to Microcontrollers 

Based on the programs given above many advanced projects are 
possible. Given below is the list of project ideas, which can be explored 
with little efforts by modifying the LED interfacing circuit. 

4.6.1 Running LEDs 

http://www.avrprojects. net/articles. php?lng=en&pg=43 

The code for the running LEDs has already been developed in this 
chapter. The project at the above URL describes running LED or LED 
chaser project. It has running LED light with 15 red 3 mm LEDs. Just 
have a look at the project and it is very simple to implement on our kit. 

4.6.2 Running Bicolor LED 

The above project can be very easily modified by connecting the 
readily available bicolor LED package such as TLUV5300 (Refer: 
www.vishay.com/leds/list/product-83056) which comprises green and 
red LEDs. Different patterns can be created by modifying the source 
code. 

4.6.3 Interfacing 6 LEDs 

Using 3 Microcontroller Pins by 

URL: http://www.scienceprog.com/connect-6-leds-using-3-microcon 
troller-pins/ A simple circuit is given for expanding the pin capabilities 
useful when using dual colour LEDs, i.e., 2 LEDs packed in one case 
but in different directions. AVR-GCC C code to control the LEDs is 
also given. With the similar scheme even 12 LEDs can be connected by 
using only 4 port pins. 

4.6.4 The LED Dimmer Demoboard 

http://www.standardics.nxp.com/support/boards/leddemo/ 

The LED dimmer demoboard demonstrates the capability of the I2C- 
bus to perform red/green/blue color LED lighting and mixing opera- 
tions. Two separate control cards comprise the demoboard: 

■ The Keypad Control Card contains a microcontroller, a 16-key 
keypad/controller, and a power supply/regulator module. 

■ The LED Control Card contains LEDs (red, green, blue, white, 
RGB) and the devices used to control them. 



52 DIP Switch Interfacing: Getting Input to Your Embedded System 

4.6.5 Fading RGB LED 

URL: http://www.avrprojects. net/articles. php?lng=en&pg=53 

The project at the above URL is done with the AVR microcontroller. 
But the same can be implemented with the little modification in the 
circuit diagram covered above. An RGB LED is an LED which has 
three LEDs integrated in one packaging. These LEDs have the colors 
red, green, and blue. With these three colors one can mix a good number 
of color and fading combinations using the 8 bit PWM drive. With 
8-bit PWM drive 256*256*256 combinations are possible, which leads 
to 16.777 million colors, and 256 different brightness. 

With the three LEDs driven with logic 1 at port pins gives white color. 
The RGB LED has generally four leads, one for each color and one 
for the common cathode which is connected to ground. The operating 
voltages for every LED is different, viz., Red LED 2 V, Green 3.5 V, 
and the Blue LED 3.5 V with each LED drawing around 20 mA current. 
The timers of the microcontroller can be used to drive the particular 
pattern which corresponds to fading of the LEDs. You may also use 
IC555 output which is available on the kit. 

4.6.6 LED Moving Font 

URL: http://www.woe.onlinehome.de/e_projects.htm 

Page title: World of Electronics - Electronic Projects 

The project at the above URL describes a microcontroller (8051-based) 
LED moving font board built up of separate modules consisting of 64 
LEDs each (8x8 matrix). There is a provision of cascading the modules 
according to the desired size of the font. Each module is controlled by 
the LED display driver MAX7219 (or MAX7221) which can drive 64 
LEDs. The display data is transferred serially to this display driver via 
the pins DIN, CLK, and LOAD. The pin DOUT can be connected to 
the input DIN of the following display driver, all CLK and all LOAD 
pins are connected together. The modules are controlled by an 8051- 
compatible microcontroller AT89C51 (LED moving font controller vari- 
ant 1 or AT89C2051 (LED moving font controller variant 2 from Atmel 
which provide 4 KB or 2KB flash memory on-chip. 

4.7 DIP Switch Interfacing: Getting Input 

to Your Embedded System 

Dual in-line package (DIP) switches are electronic packages that con- 
sist of a series of tiny switches. DIP switches are used to configure com- 
puters and peripherals such as circuit boards and modems. They are 
really useful for testing purpose. On our kit an eight input DIP switch 
is provided with all its inputs available through the male connector on 
the board. Any port can be connected to this DIP switch by simply 
connecting the associated male connectors. This scheme is very useful 
to simulate a digital input to the microcontroller. 



Exploring the Capabilities of On- Chip Resources Programming 



53 



8 

9 5 

S ° 

5 R 

2 T 



+5V 

Q 



10 K 
ResistorPack 






>s. 






DIP Switch 



Figure 4-4 DIP switch interfacing to microcontroller 



Program 4.12: DIP Switch Interfacing 

Program for getting the DIP switch status and outputting the same 
on LED. DIP switch status is read through port 1. LEDs are connected 
to port to display the status read. 

Program Source Code 

"^l^ "^l^ "^l^ "^l^ "^l^ *& "^l^ "^l^ *& "^l^ *& *& "^l^ "^l^ "^l^ "^l^ "^l^ "^l^ *& "^£ *& "^£ *& "^l^ *& *& *& "^£ "^l^ *& *& "^l^ "^l^ "^£ *& *& "^£ "^l^ "^l^ "^l^ "^l^ "^l^ ^l^ *& "^r£ "^£ "^£ "^£ "^£ "^£ *& *& *& 

#include <REG52.H> 
void main (void) 

{ 

char Nl; //Define the character for assignment of the 

hex number. 

PI = OxFF; // Define the port PI as a input port. 

while(l) 



{ 



N1=P1; 
P0=N1; 



} 



} 



Assign the value read from the port 1 to Nl. 
/* display the status of the DIP switch on the 
LEDs connected to port 0. */ 
// End of "while" 
// End of "main" 






54 



LCD Interfacing 



4.8 LCD Interfacing 

LCDs are commonly used as an output interface to embedded systems 
products like cell phone, data loggers and process control instruments. 
Figure 4.5 shows LCD controller Hitachi 44780 that provides a relatively 
simple interface between a processor and an LCD. Since the LCD inter- 
facing is used in almost all our applications, a datasheet and other details 
are given in annexure I. Three output pins, viz., P2.0, P2.1 and P2.2 are 
used for controlling the LCD. The data is passed on to the LCD using 
port 1. 

The most important thing in LCD interfacing is to apply a minimum 
of 450 ns wide high to low pulse to the enable pin of the LCD. This is 
used to activate the latch of Hitachi 44780 to grab the data on the port 
pin at that instance. 



ik : 



sw 



+Vcc 



10nF 



10K 



33 PI 



X 

XTAL ] 12 MHz 

H 



> 



33Pf 



Reset 



XTALl 



XTAL2 



Vcc 

A 

T 
8 
9 
S 
5 
2 



Vss 



I 



+5V 



+5V 



10K 



1 



1K 



Vcc 



Vss 



V 



HD 44780 
(16X12) 



LCD 



GO 



"j g * D 7 D e 

/|\ A /*. A A 



P 

P. 

P 
P 
P„ 

P. 

P-: 

P 

P 

P 
P 



Control 



Signals 



Back 

light 



Back light 

D, Do 
"* — W 



1 



Data lines 



Figure 4-5 LCD interfacing to 8051 microcontroller 



Exploring the Capabilities of On- Chip Resources Programming 



55 



Program 4.13: Displaying String of Characters 
on LCD 

This program displays the string "We Thank Springer Publishers 
From Authors" on the LCD. The comments are self-explanatory. 

Program Source Code 



#include <REG52.H> 
sbit RS = P2 A 0; 



sbit RW = P2 A 1; 
sbit EN = P2 A 2; 



/* special function register declarations 
/* for the intended 8051 derivative */ 
Control signal RESET of the LCD connected 
to pin P2.0 

Write (RW) Signal pin connected to pin P2.1 
Enable (EN) LCD control signal connected to 
pin P2.2 



int i; 

void delay (void); // Delay function 

void INIT(void); // Function for the commands to Initialization of 

the LCD 
void ENABLE (void); // Function for the commands to enable the LCD 
void LINE(int); /* Function for the commands to choose the line for 

displaying the characters on the LCD */ 



void LINE (int i) 

{ 

if (i==l 

{ 

RS=0; 

RW=0; 
Pl=0x80; 
ENABLE(); 
RS=1; 

} 
else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE(); 
RS=1; 

} 
} 



start of LINE function 



first make the reset signal low 
make RW low to give commands to the LCD 
force cursor to beginning of the first line 
enable the LCD 



force cursor to beginning of the second line 



56 



LCD Interfacing 



void delay () // Invoking the delay function. 

{ 

int j; 

for (j=0;j<10;j++) 

{ 

for (i=0;i<100;i++); 

}} 



void ENABLE (void) // Invoking the enable function 

{ EN=1; // Give high to low pulse to Enable the LCD. 
delay (); 

EN=0; 
delay (); 

} 



void INIT(void) 
{ 



// Initialization of the LCD by giving the proper 
commands. 



2 lines and 5*7 matrix LCD. 



} 



RS=0; 
RW=0; 

EN=0; 

PI = 0x38; 

ENABLE(); 

ENABLE(); 

ENABLE(); 

ENABLE(); 

PI = 0x06; //Shift cursor to left 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLEQ; 



Display ON, Cursor Blinking 
Clear display Screen. 



void main (void) 
{ 

char code dis[] = "We Thank Springer Publishers"; 

char code dis2[] = "From Authors"; // Array of characters 

to be display. 



Exploring the Capabilities of On- Chip Resources Programming 57 

char *p; // Pointer to point the data in the array. 

int j,x; 

while(l) 

{ 

for (x=l;x<3;x++) 

{ 

INIT(); 

LINE(l); // Display on the line 1 of the LCD. 

if (x==l) 

{ 

p=&dis; // point the character address from the array "dis" where 

it is stored. 

} 

else 

{ 

p=&dis2; // Point the Character address from the "dis2" where it 

is stored/ 

} 

for (j=0;j>8;j++){ 

Pl= *p++; // Increment the pointer by 1. 
ENABLE(); 

} 
LINE(2); // Display the second array on the second line on the LCD. 

} 
} 

} 

4.9 Interrupts in Microcontrollers 

Interrupts are of immense importance in any microcontroller-based 
system. A peripheral such as timer/counter, A to D converter, or even a 
memory or a keyboard can interrupt the microcontroller from its ongoing 
sequential execution to let it know that it requires attention. This may be 
due to several reasons such as timer overflowing, ADC returning data, or 
the signal on an input pin changing. Generally, many standard references 
compare the polling technique with the interrupt and concludes that the 
interrupt is a superior technique. However, in microcontroller paradigm, 
if the developer intends to use the polling technique, then he will have to 



58 Interrupts in Microcontrollers 

implement it in software. Ideally the peripheral can be made to set/reset 
a flag, the status of which requires to be checked using a conditional 
loop. But the interrupt offers a flexible and time-efficient response to 
the external events with the least software overhead. 
Interrupts in 8051 microcontroller are as follows: 

■ Timer Overflow 

■ Timer 1 Overflow 

■ Reception/Transmission of Serial Character 

■ External Event 

■ External Event 1 

4.9.1 Writing ISRs in C 

Program 4.14: 

This simple program illustrates the initialization sequence for the 
timer, serial I/O and interrupt. A function called "serial_int" is set as the 
handler for interrupt 4, which is the serial port interrupt. A character 
'V is sent to the serial buffer. Observe this in the simulation window of 
Keil IDE. 

Program Source Code 

// Serial Port Interrupt 

^include <reg52.h> 
^include <stdio.h> 

void main (void) 

{ 

int i; 

TMOD = (TMOD & OxFO) | 0x20; // Set Timer 1 

Mode 2 

SCON = 0x50; // Serial Communi- 

cation Mode 1 

EA = 1; // Enable Global 

Interrupt Bit 

ES = 1; // Enable Serial Port 

Interrupts 



Exploring the Capabilities of On- Chip Resources Programming 59 

TH1 = OxFD; // Load Timer 1 Baud Rate 

TR1 = 1; //Set Timer 1 Run control 

bit 



while (1) 

{ 

SBUF = 'V; //Send V continuously on 

//Serial Port 

for(i=0;i<=10;i++); /* Delay to avoid trans- 
mission overlapping */ 

} 
} 



// Serial Port Interrupt Service Routine. 

void timerO JSR (void) interrupt 4 

{ 

TI = 0; //Clear transmission 

interrupt flag 

********** J********************************************* 

Program 4.15: 

This program is modification of the Program 4.14. Unlike the inter- 
rupt technique used in Program 4.14, here the interrupt flag is polled 
continuously. Observe the transmission of 'v' in simulator window. 

Program Source Code 



Serial port Interrupt Programming 
#include<REG52.H> 
void main() 

{ 

TMOD=0x20; // Timer 1 Mode 2 

TH1=0XFD; // Baud rate = 9600 for 11.0592 



60 



Interrupts in Microcontrollers 



MHz XTAL 



TL1=0XFD; 



} 



SCON=0X50; 



TR1 = 1; 
TI = 0; 



while(l) 
{ 



SBUF = V; 

while(!TI); 
TI = 0; 



} 



//Serial Communication 
mode 1 

// Start Timer 1 
// Clear Transmit Interrupt 
flag 



// Send V continuously on 

Serial port 

Check TI flag till it is zero 
// Clear Transmit Interrupt 

flag 






Program 4.16: Implementation of Minutes Counter 

This program implements a seconds counter on the serial seven- 
segment LED. Timer is used for the generation of delay of a minute. 
With elapsing of the delay routine the count is incremented and dis- 
played on the serial seven-segment LED. The 4 seven- segment display is 
serially connected. Pins P3.7 is used for clock generation and the data 
is transferred serially over the pin P3.6. 

Program Source Code 

#include<REG52.H> 

void display (char a); 

void clear(void); 

void INIT (void); 

void delay (void); 

unsigned int count, milliseconds; // Unsigned Integers for the count. 

sbit dat=P3 A 6; // Set the pin to Sending the data bits over the pin 

P3.6 
sbit clk=P3 A 7; // Set the pin to send elk 



Exploring the Capabilities of On- Chip Resources Programming 61 

unsigned int delay 1; 

unsigned char s[10]= {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xd8,0x80, 

0x90}; 

void delay(void) // Invoking the Delay routine 

{ 

int c,d; 

for(c=0;c<2;c++) 

{for(d=0;d<2000;d++); 

}}.... 

void INIT (void) // Invoking the function to start the timer 

{ 
TMOD=0X01; 

TF0=0; /* Timer overflow flag reset first, Start the timer and 

set the interrupt when timer overflows */ 

TR0=0; 

delayl=50000; 

delay 1=~ delay 1; // Complement the delay count 

TL0=delayl%256; // Count loaded in the Timer lower byte. 

TH0=delay 1/256; // Load the higher byte of timer 

TR0=1; // Run the timer 



ET0=1; 

EA=1; // Global interrupt bit 

IP=0x00; 

} 

void clear (void) /* Invoking the function to clear the display */ 

{ 

int j; 

dat=l; 

for(j=0;j<32;j++) 

{ 

clk=0; // Sending the pulse to clear the display 

clk=l;clk=0; 

}} 

void display(char a) // Display the numbers on the seven-segment 

LEDs 

{ 

unsigned char mask; 

int y; 

mask=0x80; // Mask the higher digit 



62 



Interrupts in Microcontrollers 



for(y=0;y<8;y++ 

{ 

if(a&mask) 

dat=l; 

else 

dat=0; 

clk=0; 

clk=l;clk=0; 

mask=mask> > 1 ; 



/* If the unit digit goes overflow then switch the 
upper digit. */ 



// Invoking the main function 



void main(void) 

{ 

unsigned char m,n; 
clear (); 

count=0; milliseconds=0; 

INIT(); // Initializing the timer 

do 

{ 

clear (); 

n=count%10; 

m= ( (count/10) % 10); 
display(s[m]); // Display the count at higher digit position 

display(s[n]); // Display the count on the lower digit position 

delay (); 

} 

while (count < 60); 

TR0=0; 

while (1); 

} 



void) interrupt 1 



{ 

TR0=0; TF0=0; 
delayl=50000; 
delay f=~delayf; 
TL0=delayl%256; 
TH0=delayl/256; 



Function for the interrupt routine when timer 
overflows 

Reset the timer and the timer flag 



Exploring the Capabilities of On- Chip Resources Programming 63 



milliseconds++; // Increment the millisecond count by one 
if (milliseconds == 20) 

{ 

count ++; // Increment the count 

milliseconds=0; 

} 

TR0=1; // Run the timer 

4.9.2 A Word about Interrupt Latency 

Interrupt latency is the time between the generation of an interrupt 
by a device and the servicing of the device which generated the interrupt. 
In other words it is the time taken to service the interrupt or the longest 
time between when the interrupt occurs and when the microcontroller 
suspends the current processing context. 

Interrupt latency is an important issue in microcontroller-based sys- 
tem design for several reasons. Microcontroller-based system with a sin- 
gle interrupt will execute correctly (as per the intended logic of the 
developer) provided ISR execution time is smaller than the frequency 
of the interrupt. One of the most important issues in microcontroller- 
based embedded systems is the power consumption, since the system 
aims at remote installation with long battery life. From the low power 
consumption point of view, the crystal frequency should be at the low- 
est end of the permissible limit. This value is ultimately decided by 
the interrupt latency (generally the standard values should be adopted 
to give prescribed baud rates in serial communication). Improving the 
interrupt latency results into lowering down the throughput and increas- 
ing the processor utilization. On the other hand, reducing the processor 
utilization may increase interrupt latency but may decrease the overall 
throughput. 

Program 4.17: Estimating Interrupt Latency 
Program Source Code 



^include <REG52.H> /* special function register declarations */ 

/* for the intended 8051 derivative */ 

sbit RS = P2 A 0; 
sbit RW = P2 A 1; 



64 



Interrupts in Microcontrollers 



— TDOAo. 



sbit EN = P2 A 2; 



sbit interruptl = P3 A 3; 

sbit IN =P2 A 3; 
void delay (int); 
void INIT(void); 
void ENABLE(void); 
void LINE(int); 
int ONTIME(int); 



// External interrupt 



void LINE (int i) 

{ 

if (i==l) 

{ 
RS=0; 

RW=0; 

Pl=0x80; 

ENABLE(); 

RS=1; 

} 
else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE(); 
RS=1; 

} 
} 

void delay () 

{ 

int i,j; 

for (j=0;j<10;j++){ 

for (i=0;i<100;i++); 

}} 

void ENABLE (void) 

{ 

EN=1; 

delay (); 



Enabling the Line function 



Invoking the Enable function for the LCD 



Exploring the Capabilities of On- Chip Resources Programming 65 

EN=0; 
delay (); 

} 

void INIT(void) // Initialization of the LCD by giving the proper 

commands 

{ 

RS=0; 
RW=0; 

EN=0; 

PI = 0x38; // 2 lines and 5*7 matrix LCD 

ENABLEO 

ENABLE() 

ENABLE() 

ENABLE() 

PI = 0x06; // Shift cursor to left 

ENABLEO; 

PI = OxOE; // Display ON, Cursor Blinking 

ENABLE(); 

PI = 0x01; // Clear display Screen 

ENABLE(); 

} 

int ONTIME() // Invoking the ONTIME function 

{ 

TMOD=0x01; // Intialize as 16 bit timer(mode l)(Timer 1) 

TL0=0x00; 

TH0=0x00; 

TR0=1; // start the timer 

IN=1; /*input to 8052 from 555 osc*/ 

while(IN); 

while(!IN); 

while(IN); 

TR0=0; // stop the timer 



return((TH0*256)+TL0); // return the ISR Execution count 
} 



void main (void){ 

int latency, unit, tens, hundred, thousand, 



66 Interrupts in Microcontrollers 

tenthou, unitl, tensl, hundredl, thousand 1, tenthoul; 
char code dis[] = "ISR Execution Time="; 
char code dis2[] = "Interupt Latency="; 
char *p; 
int i,j; 

while(l) 

{ 

TMOD=0x01; // Initialize the timer to count the total program 

execution time 
THl=0x00; 
TLl=0x00; 
TR1=1; // Start the timer 1 



if(interruptl==l) 

{ 

i = ONTIME(); 

unit = (i%10); 

tens = (i/10)%10; 

hundred = (i/100)%10; 

thousand = (i/1000)%10; 

tenthou = (i/10000)%10; 

unit = unit + 0x30; // Sending the ASCII data to the LCD 

tens = tens + 0x30; 

hundred = hundred + 0x30; 

thousand= thousand + 0x30; 

tenthou = tenthou + 0x30; 

INIT(); 
LINE(l); 

p=&dis; 

for (j=0;j<8;j++){ 
Pl= *p++; 

ENABLE(); 

} 

LINE(2); 

Pl=tenthou; 

ENABLE(); 

Pl=thousand; 

ENABLE(); 

Pl=hundred; 

ENABLE(); 



Exploring the Capabilities of On- Chip Resources Programming 67 

Pl=tens; 

ENABLE(); 
Pl=unit; 

ENABLE(); 

} 
else 

{ 

p=&dis2; 

for (j=0;j<8;j++){ 

Pl= *p++; // Pointer to point the data from the array 

ENABLE(); // Enabling the LCD 

} 
LINE (2); // Display the content on the second line of the LCD 

TR1=0; // stop the timer 2 

latency=(((THl-TH0)*256)-(TLl-TL0)); //Timer count is subtra- 
cted from timer 1 
unitl = (latency % 10); 
tensl = (latency/10)%10; 
hundredl = (latency/100)%10; 
thousandl = (latency/1000)%10; 
tenthoul = (latency/10000)%10; 
unitl = unitl + 0x30; 
tensl = tensl + 0x30; 
hundredl = hundredl + 0x30; 
thousand 1= thousandl + 0x30; 
tenthoul = tenthoul + 0x30; 
LINE(2); 

Pl=tenthou; // display the latency 

ENABLE(); 
Pl=thousand; 
ENABLE(); 
Pl=hundred; 
ENABLE(); 
Pl=tens; 
ENABLE(); 
Pl=unit; 
ENABLE(); 

} 
} 

} 



Chapter 5 
Hyperterminal-Based Control 



5.1 Hyperterminal 

Hyper Terminal is a terminal emulator program that runs in MS 
Windows. It offers a text-based command prompt interface on a 
remote device. The remote device is a serial device, and it could be 
a router, connected directly to the PC's serial port OR a network 
device. Hyper Terminal is generally used for the local serial interface for 
communications or the network. In the case of the network, HyperTer- 
minal is simply using the telnet protocol. In order to communicate with 
the device, the HyperTerminal must be configured on the right COM 
port (either COM1 or COM2) and at appropriate baud rate (most of 
the time 9600 for applications written here). 

Having designed to emulate various types of text terminal configurable 
to make a over a serial port the serial parameters to be selected are: 

■ Baud rate 

■ Parity (odd, even, none) 

■ Stop bits 

■ Flow control 

5.2 Packet-based Control Scheme 

The beauty of the programs covered in this section is that they present 
an insight with regard to the new protocol development. The remote 
host, i.e., microcontroller board connected to COM1, has various com- 
mand blocks which will be invoked based on the parameters passed from 
the HyperTerminal. The command blocks are packed and a particu- 
lar packet corresponding to the desired control sequence that is made 
alive as soon as the associated command parameter is received from the 
HyperTerminal. 



69 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 69-83. 
© 2007 Springer. 



70 Mechanism and Lots of Possibilities 

Two things are required to keep in mind in these applications: 
maintaining the compatibility of PC serial port to microcontroller; 
and selection of proper baud rate. A standard serial interfacing for PC, 
RS232C, requires negative logic, i.e., logic '1' is — 3 V to —12 V and logic 
'0' is +3V to +12 V. In order to convert a TTL logic, say, TxD and 
RxD pins of the microcontroller chips, a converter chip is required. A 
MAX232 chip is a very popular chip used in the circuit boards for all the 
applications covered in this chapter. It provides 2-channel RS232C port 
and requires external lOuF capacitors. The polarity of the capacitor is 
crucial which the user must note. Another possibility in lieu of MAX232 
is DS275, which does not require an external capacitor. 

5.3 Mechanism and Lots of Possibilities 

The mechanism of packet-based interface works as follows. The num- 
ber of control possibilities are listed in case of each control module and 
categorized in terms of packets. For instance, in case of the LED inter- 
face board, various display sequences are defined as packets. In case of 
stepper motor-based interface the packet definitions include the clock- 
wise, anticlockwise rotations in the first instance and step size as the 
secondary instance, both the things defined together. As per the firing 
of the commands from the Hyper Terminal the firmware residing in the 
microcontroller flash will invoke the appropriate control action. 

The following simple steps will help you to configure the 
Hyper Terminal. 

1. Open the Hyper Terminal, by clicking 

Start >Programs>Accessories>Communications>Hyper Terminal. 

2. This will prompt you to create a new connection. The new connec- 
tion can also be created by clicking File > New Connection. Enter 
a name for the connection and click OK. 

3. Select the serial port where the device is connected to the PC 
(COM1 in our case). Click OK. 

4. Enter the following configuration for the connection: 



Bits per second 9600 

Data bits 8 

Parity None 

Stop bit 1 

Flow control None 



Click OK. 



Hyperterminal- Based Control 



71 



5. After clicking OK or apply all, the above configuration will be 
loaded and the commands can be entered at the command prompt. 

This HyperTerminal-based interface offers great possibilities from con- 
trol point of view. With little modification in the hardware it is possible 
to go for web enabling of the embedded products by adding an Ethernet- 
based interface. Internet-based data logging and control, microcontroller- 
based server, and client applications are possible with optimized usage 
of resources due to packet methodology. 



5.4 



Application 1: Packet-based Interface 
for LEDs 



The circuit diagram of the packet-based LED interface is as shown in 
Figure 5.1. The commands to be emulated from the Hyper Terminal and 
the corresponding control action is given in the program source code. 



+5V 



33041 



330O J*x 

W- 



»» 



ft 



33PF 



12MHz QH XTAL 

-3H 



+5V 



" 33PF 



P 



P 



R.D 



I'D 



AT89S52 



XTAL1 



XTAL2 



GND 



T 



K>nf4_ 



IO M f» 



+5V 



10(.if 



ne 



vcc 



T IN 



V, 



R,IN 



R,OUT £j 

r . N T,0UT 

< 

Or S T s OUT 

C,+ 



R a IN 



V- 



X 

I 



DB9 
CONNECTOR 



Figure 5. 1 Circuit diagram of packet-based interface for LED 



Program Source Code 



/* Displaying different LED sequence pattern based on the packet 

received */ 

#include<REG52.h> 



72 



Application 1: Packet-based Interface for LEDs 



unsigned char led; 
int interpret; 
char packet [4]; 
char index; 
void init(void); 
void delay (int m); 

void init() 

{ 

TMOD=0X20; 
THl=0xFD; 
SCON=0x50; 
TR1=1; 

} 

void main(void) 

{ 

int k=0; 

char i; 

init(); 

ES=1; 

EA=1; 

led=0xff; 

for (i=0;i<4;i++){ 

packet [i]=0; 

} 

index=0; 
interpret=0; 

while(l) 

{ 
{ 

P0= led; 
delay (1000); 

} 

}} 
void delay (int m) 

{ 

int z; 
z=m: 



select baud rate 9600 : 



start timer 



Global interrupt bit enabled 



Function for the Delay. 



Hyperterminal-Based Control 73 

while (m>0) 

{ m ;} 

} 

void serialisr() interrupt 4 

{ 

unsigned char y; 

char i; 

RI=0; 

y=SBUF; // write the data in srial buffer. 

TI=0; 

SBUF=y; // read the data from serial buffer. 

while (!TI); // Check the flag 

TI=0; 

packet [index] =y ; 

index++; 

if (y==V) 

{ 

interpret =1; 

index = 0; 

} 

else interpret = 0; 
if (interpret==l) 

{ 

switch(packet [0] ) 

{ 

case 'A': 

led=0x55; // 01010101 
break; 

case 'B': 

led=0x33; 
break; 

case 'C: 

led=0x55; 
delay(lOO); 
led=0x33; 
break; 

case 'D': 

led=0x00; 



74 Application 2: Packet-based Interface for Stepper Motor Control 

delay(lOO); 

led=0x02; 

delay(lOO); 
led=8; 
delay (100); 

led=16; 

delay(lOO); 

led=16; 
delay (100); 
led=32; 
delay (100); 
led=64; 
delay (100); 
led=256; 
delay (100); 
break; 

} 

for (i=0;i<4;i++) 

{ 

packet [i]=0; 

} 

interpret=0; 

} 
} 

5.5 Application 2: Packet-based Interface 

for Stepper Motor Control 

The circuit diagram of the packet-based stepper motor interface is as 
shown in Figure 5.2. The commands to be emulated from the Hyper- 
Terminal and the corresponding control action are given in the pro- 
gram source code. The interface is based on UN2003 driver popularly 
used for many stepper motor control applications. It is a 7-bit, 50 V 
500 mA TTL-input NPN Darlington driver. The drivers does not need 
power supply; the VDD pin is the common cathode of the seven in- 
tegrated protection diodes. The details are covered in may web-based 
resources [35]. 



Hyperterminal- Based Control 



75 




Figure 5.2 Circuit diagram of stepper motor interface 



Program Source Code 



#include<REG52.h> 

unsigned char mot [4] = {0x0a, 0x06, 0x05, 0x09}; 

unsigned char run, clkwise; 

int interpret, mode, count; 

char packet [5]; /*p[0] is control char*/ 

char index; /*others may contain data last must contain end char, 

i.e., 'z' 7 
void init(void); 
void delay (int m); 
void init() 

{ 

TMOD=0x20; 

THl=0xFD; /*select baud rate 9600*/ 

SCON=0x50; 

TR1=1; /* start timer*/ 

} 



76 Application 2: Packet-based Interface for Stepper Motor Control 

void main (void) 

{ 

int k=0; 

char i; 

init(); ES=1; EA=1; 
run=l; 
clkwise = 1; 
for (i=0;i<5;i++){ 
packet [i]=0; 

} 

index=0; 

interpret=0; 

while(l) 

{ 

while(mode==0){ /* continues rotation*/ 
while(run==l) 
{if(clkwise==l){ 
for (i=0;i<4 ; i++) /* clkwise dir*/ 
{ P0= mot [i]; 
delay (1000); 

}} 

else 

{for (i=3;i>=0 ; i ) /*anticlkwise dir*/ 

{ P0= mot [i]; 

delay (1000); 

} 

} 

} 
} 
} 

while(mode==l) /*number of step's given by user*/ 

{ 

while((run==l)&&(count>0)) 

{ 

if(clkwise==l){ 

for ( i=0;i<4 ; i++) 

{ 

P0= mot [i]; 

delay (1000); 

} 
} 



Hyperterminal- Based Control 



77 



else 



{ 



} 



} 



for ( i=3;i>=0 ; i ) 

{ 

P0= mot [i]; 

delay (1000); 

} 

} 

count ; 

} 



void delay (int m) 

{ int z; 

z=m; 

while (m>0) 

{ m ;} 

} 

void serialisr() interrupt 4 

{ 

unsigned char y; 
char i; 
RI=0; 
y=SBUF; 

TI=0; SBUF=y; while (!TI);TI=0; 

packet [index] =y ; 
index++; 
if (y=='Z') { 

interpret =1; /* indicates end of packet : 
index = 0; 

} 

else interpret = 0; 
if (interpret==l) 

{ 

switch(packet [0] ) 

{ 

case 'S': 

run=0; 
break; 



contents of buffer 

* / 



in y 

/*similtaneusly 

display*/ 



78 Application 3: Home Automation from PC HyperTerminal 

case 'R': 

run=l; 

break; 

case 'A': 

clkwise=0; 
break; 

case 'C: 

clkwise=l; 
break; 

case 'D': 

if (packet[l]=='0') 

mode=0; 

break; 
case 'E': 

if (packet[l]=='l') 

mode=l; 

break; 
case 'F': /*variable size packet*/ 

count=(packet[3]-0x30)+((packet[2]-0x30)*10)+((packet[l]- 
0x30)*100); 

break; /*packet[3]=units */ 

} 

for (i=0;i<5;i++){ 
packet [i]=0; 

} 

interpret=0; 

} 

5.6 Application 3: Home Automation from PC 

HyperTerminal 

Home Automation from PC Terminal 

With the deep penetration of PCs in today's modern homes, the 
trend of PC- based home automation is growing. There are different 
home automation systems that consist of controller and device control- 
ling modules (relays, light dimmers, etc.). New protocols such as X10 
system that communicates through mains wiring is gaining popularity. 



Hyperterminal-B ased Control 



79 



89S52 
Microcontroller 



Multiple 



RS- 232 
Interface 




Figure 5. 3 Block schematic of the hyper terminal based home automation system 



33Pt 



I 

|~|l2MHz 



• , 33Pf 



o o 



Vcc 

XTAL1 



XTAL2 
CND 



AT 89S 52 



P.. P.. P»' P - P « 



O o 

o o 

o 



OB 9 
ComMdn 



10|iF 



u q fcr 2 t 

> si& I 

i- or 

MAX 232 
* i + i 

o > o o o > 



r 

10uF"T- 



~\<- 



1 



lO^F 



W 



u 



u 



MOC3030 

'Sat 



s 



< 



MOC man 



V lr (230V) 
o o 



F 
P 



p 


PC 




p» 


OVEN 






p 


VtfesNng 

Mactvne 


Pa 




Dryer 



CD PLAYER 
=1 



V^ (230V) 



App'iance 



Cirrutf Diagram ot Horn* Airtwruton from PC 



Figure 5.4 Circuit diagram 



80 Application 3: Home Automation from PC HyperTerminal 

However, any embedded developer would definitely love to write his own 
protocol for the home automation system. Here is the one which com- 
municates with the 89S52-based microcontroller board through Hyper- 
Terminal of PC. Again the packet-based methodology has been used. 
The drivers for various appliance control such as lights, garage door, 
audio system, TV, etc., resides in the microcontroller flash and are 
invoked based on the command character passed on from the Hyper- 
Terminal. The microcontroller-based interfacing board comprises opto- 
isolator MOC3030 which has built-in zero crossing detection. 

Program Source Code 

^i^ "^c "^z *& "^c "^z *& "^c *& *& *& *& *& "^z *& "£? *& *& *& "^z *& "^z "^z *& *& ^i^ *& *& "£? "£? "£? "£? "£? "^z "^c "£? "^z *& "£? *& *& *& *& *& "^z *& "£? *& *& "^z *& "^c "^z *& "^c "^z *& *& *& *& *& 

#include<REG52.h> 

unsigned char light; 

int interpret; 

/* The pins of the port are connected to power line of various 

home appliances through the control circuitry to control them by 

on/off the power supply. */ 

sbit lightl=P0 A 0; // Pin connected to the control circuit of the 

Light 1. 
sbit light2=P0 A l; 

sbit TV=P0 A 2; // Pin connected to control circuit of power supply 

of TV. 

sbit PC = P0 A 3; 
sbit oven = P0 A 4; 
sbit washing = P0 A 5; 
sbit coller = P0 A 6; 
sbit CD = P0 A 7; 

char packet [4]; 
char index; 
void init(void); 
void delay (int m); 
void init() 

{ 

TMOD=0X20; 

THl=0xFD; /*select baud rate 9600*/ 

SCON=0x50; 



Hyperterminal-Based Control 81 

TR1=1; /* start timer*/ 

} 

void main (void) 

{ 

int k=0; 

char i; 

init(); ES=1; EA=1; 

for (i=0;i<4;i++){ 

packet [i]=0; 

} 

index=0; 
interpret =0; 

while(l) 

{ 
{ 

P0=lightl; 
delay(lOOO); 

} 

}} 

void delay (int m) 

{ int z; 

z=m; 

while ( m >0) 

{ m ;} 

} 

void serialisr() interrupt 4 

{ 

unsigned char y; 
char i; 

RI=0; 

y=SBUF; 

TI=0; SBUF=y; while (!TI);TI=0; 

packet [index] =y; 

index++; 

if (y=='z') {interpret =1; index = 0;} 

else interpret = 0; 



82 



Application 3: Home Automation from PC HyperTerminal 



if (interpret==l) 

{ 

switch (packet [0]) 

{ 



case 'A': 

lightl=l; 

break; 

case 'B': 

lightl=0; 

break; 

case 'C: 

light2=l; 

break; 

case 'D': 
light2=0; 
Washing machine 

break; 
case 'E': 

TV=1; 
break; 
case C F': 

TV=0; 
break; 
case 'G': 

PC=1; 
break; 
case 'H': 

PC=0; 
break; 
case T: 
oven= 1 ; 
break; 
case 'J': 
oven=0; 

break; 
case 'K': 
washing=l; 
break; 
case 'L': 



switch on the bulbl 



// switch off the bulbl 



// switch on the bulb2 



switch off the bulb2// // switch on 



// switch on the TV 



// switch off The TV 



// switch on PC 



// switch off the PC 



switch on oven 



// switch off oven 



// switch on the washing machine 



Hyperterminal- Based Control 



83 



washing=0; 

break; 
case 'M': 
coller=l; 

break; 
case 'N': 
coller=0; 

break; 
case 'O': 
CD=1; 

break; 
case 'P': 
CD=0; 

break; 

} 



switch off the washing machine 



// switch on cooler 



// switch off the cooler 



switch on CD player 



switch off CD player 



for (i=0;i<8;i++){ 
packet [i]=0; 

} 

interpret=0; 

}} 






Chapter 6 

Embedding Microcontroller in Routine 
Applications 



This chapter illustrates how embedding microcontroller in day-to-day 
applications altogether changes the throughput of the product. 

6.1 Application 1: Podium Timer 

The podium timer is designed for giving the indication of timeout for 
a series of timed speeches. The 4x4 hex keyboard enables the user to 
set the time and start the timer. Once the timer is ON, it constantly 
indicates the time on the LCD. Before 3 minutes (which is also program- 
mable) of actual timeout, it gives an indication by means of short beep. 
As soon as the time set is elapsed, the unit enables the buzzer indicating 
the timeout. 

Program Source Code 



#include <REG52.H> 

sbit RS = P2 A 0; 
sbit RW = P2 A 1; 
sbit EL = P2 A 2; 

sbit buzz = P2 A 3; 
sbit Rl = P3 A 0: 
sbit R2 = P3 A 1 
sbit R3 = P3 A 2: 
sbit R4 = P3 A 3: 
sbit CI = P3 A 4: 
sbit C2 = P3 A 5: 
sbit C3 = P3 A 6: 



/* special function register declarations 
for the intended 8051 derivative */ 



85 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 85-122. 
© 2007 Springer. 



86 Application 1: Podium Timer 

sbit C4 = P3 A 7; 
void Delay(int); 
void INIT(void); 
void ENABLE(void); 
void LINE(int); 
int keyb(void); 
void settime(void); 
void starttimer(void); 
void check_timeout(int); 
int settimel=10; 

void settime(void) 

{ 

int ten_pos=0, unit_pos=0; 

while(!(ten_pos=keyb())); 
while(!(unit_pos=keyb())); 
Pl=(((ten_pos))+0x30); 
ENABLE(); 

Pl=((unit.pos)+0x30); 

ENABLE(); 

Delay (2000); 

settimel= ten_pos*10 + unit.pos; 
} 

void starttimer() 

{ 

int set_temp= settime; 

check_timeout(3); //check for the warning timeout default 3 min before 

end time 

check_timeout(set_temp) ; 

set _temp-; 

Pl=(((set_temp)/10)+0x30); 

ENABLEi 



Pl=((set_temp/10)%10+0x30); 
ENABLE(); 



Embedding Microcontroller in Routine Applications 87 

Delay (2000); 

I 

void check_timeout(g) 

{ 

if(g == 3) 

{ 
buzz=l; 

Delay (100); 

buzz=0; 

} 

if (g == 0) 
buzz=l; 
Delay (400); 
buzz=0; 

} 

void main (void) 

{ 

char test [] = "Podium timer" ; 

char code set_msg[]="l-> set time"; 

char code start_msg[]="2-> start timer"; 

char *p; 

hit j; 

INiT(); 
LINE(l); 
p=&test; 
for(j=0;j<17;j++) 

{ 
if(j==0)LINE(l); 

if(j==8)LINE(2); 
Pl= *p+ + ; 

ENABLE(); 
Delay (200); 

} 
while(l){ 

RS = 1; 

p=&set_msg; 

for(j=0;j<17;j++) 

{ 



88 Application 1: Podium Timer 

if(j==0)LINE(l); 
if(j==8)LINE(2); 
Pl= *p++; 
ENABLE(); 
Delay (200); 

} 

RS= 1; 

p=&start_msg; 
for(j=0;j<17;j++) 

{ 

if(j==0)LINE(l); 

if(j==8)LINE(2); 
Pl= *p++; 

ENABLE(); 
Delay (200); 

} 

j=0; 

j=keyb(); 
if(j>0); 

if(j==l){ 
settime(); 

} 

if(j==2){ 
starttimer(); 

} 

} 
} 

void Delay(int k) 

{ 

int i,j; 

for (j=0;j<k+l;j++){ 
for (i=0;i<100;i++); 

}} 

void ENABLE (void) 

{ 
EL=1; 

Delay(l); 



Embedding Microcontroller in Routine Applications 



89 



EL=0; 
Delay(l); 

} 

void LINE(int i){ 

if (i==l) { 

RS=0; 

RW=0; 

Pl=0x80; 

ENABLE(); 
RS=1; 

} 

else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE(); 
RS=1; 

} 

} 

void INIT(void) 



{ 



} 



RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLE() 

ENABLEQ 

ENABLEQ 

ENABLEQ 

PI = 0x06; 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLEQ; 



Initialization of the LCD by giving the proper 
commands. 



// 2 lines and 5*7 matrix LCD. 



//Shift cursor to left 



Display ON, Cursor Blinking 
Clear display Screen. 



int keyb(void){ 
int key=0; 
Cl=l; 



90 



Application 2: Front Desk Notifier 



C2=1;C3=1;C4=1;R1=0;R2=1;R3=1;R4=1; 
if (C1==0) key = 1 
if (C2==0) key = 2 
if (C3==0) key = 3 

if (C4==0) key = 4 
return(key); 

} 






+5V 



33PF 



12MHz XTAL 



ih 



.. 33PF 



Vcc 



XTAL1 



XTAL 2 



CM 

00 



GND 



T 



P» 



P 



P, 



P. 




+5V 



10K 



EN 

R/W 

RS 

HD 44780 

16X2 
D, LCD 

Do 



1K 



KEY PAD 

4X4 
MATRIX 






Buzzer 



BC547 



Figure 6. 1 Circuit diagram of the podium timer 



6.2 Application 2: Front Desk Notifier 

The project aims to build an automated system that will alert the 
food assistance staff that a customer has arrived for service. It can also 
be used for a housewife who wants to know if someone has arrived at the 
gate. An IR transceiver pair has been used for detecting the presence 
of the person at the front desk. The program polls the port pins and 



Embedding Microcontroller in Routine Applications 



91 



33PF 



12MHz □ XTAL 



33PF 



V 



+5v 



Vcc 



XTAL1 
XTAL2 



Pi, 

P1.0 

"2.2 

P 



2.Q 



AT 89S52 



GND 



2.5 



T 



Vcc 



D7 



V 



a 



V 



M 



DO 



LCD 



EN 

R/W 

RS 



1K 



+5v 




10K 



* 




Buzzer 



BC547 



Figure 6.2 Circuit diagram of front desk notifier system 

displays a message on the LCD that "Someone is arrived" as well as 
activates a buzzer. The system is also ideal for a bank cashier. 

Program Source Code 



^include <REG52.H> /*special function register declarations 1 

/* for the intended 8051 derivative */ 



sbit RS = P2 A 0; 
sbit RW = P2 A 1; 
sbit EN = P2 A 2; 
sbit IN= P2 A 4; 
sbit Buzz=P2 A 5; 



void delay (int); 
void INIT(void); 
void ENABLE(void); 
voidLINE(int); 



input from the sensor present at gate : 
output indication to housewife*/ 

/* Stop Exection with Serial Intr. 



92 Application 2: Front Desk Notifier 

void LINE(int i){ 
if (i==l) { 
RS=0; 
RW=0; 
PI =0x80; 
ENABLE(); 
RS=1; 

} 
else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE(); 
RS=1; 

} 
} 

void delay () 

{ 

int i,j; 

for (j=0;j<10;j++){ 

for (i=0;i<100;i++); 

}} 



void ENABLE(void) 

{ 
EN=1; 

delay(); 

EN=0; 
delay (); 

} 

void INIT(void) // Initialization of the LCD by giving the proper 

commands. 

{ 

RS=0; 

RW=0; 

EN=0; 

PI = 0x38; // 2 lines and 5*7 matrix LCD. 



Embedding Microcontroller in Routine Applications 



93 



} 



ENABLE() 

ENABLE() 

ENABLE() 

ENABLEQ 

PI = 0x06; //Shift cursor to left 

ENABLE(); 

PI = OxOE; // Display ON, Cursor Blinking 

ENABLE(); 

PI = 0x01; // Clear display Screen. 

ENABLEQ; 



void main (void){ 

char code array [] = "Some is there on the gate"; 

char code arrayl[]="No one is there on the gate"; 

int b,j; 

Buzz=0; 

while(l) 

INIT(); 

LINE (1); 

{ 

if( IN==1) 

{ 

Buzz=l; 



some one is there if in = 1 



// switch on the buzzer to indicate some 
one is there on gate 



for (b=0;b<30;b++ 

{ 

if (b==8) 

LINE(2); 

Pl=array[b]; 

ENABLE(); 

} 



RS=0; 
Pl=0x01; 

ENABLE(); 

RS=1; 

LINE(l); 

for (b=16;b<33;b++) 

{ 

if (b==24) 



94 



Application 3: Cafeteria Food Alert/ Microcontroller-based Menu Card 



LINE(2); 

Pl=arrayl[b]; 

ENABLE(); 

} 

} 
else 

{ 

for (b=0;b<30;b++) 

{ 

if (b==8) 

LINE(2); 
Pl=arrayl[b]; 

ENABLE(); 

} 
RS=0; 

Pl=0x01; 

ENABLE(); 

RS=1; 

LINE(l); 

for (b=16;b<33;b++) 

{ 

if (b==24) 

LINE(2); 

Pl=arrayl[b]; 

ENABLE(); 

} 

} 
} 
} 



display no one there on gate 






6.3 



Application 3: Cafeteria Food 
Alert/Microcontroller-based Menu Card 



This economic unit is an ideal solution for small hotels. The customer 
can place an order of the item by pressing a key corresponding to the 
item he or she would like to order. The other half of the unit is the 
LCD display which is kept in the kitchen. The item will be displayed on 
the LCD and subsequently served to the customer. An interrupt will be 
invoked in case the customer wants bill or to place an item which is not 
there in menu or in case of any other events. 



Embedding Microcontroller in Routine Applications 



95 



33PF 

II— 



12MHz[ fAL 



33 PF 



£ 



+5v 

_L 



HD 44780 



Vcc 



XTAL1 



A 
T 
8 
9 
XTAL2 S 
5 
2 



GND 
'o.o 



•2 2 

P 2 , 

P,, 

P,o 
Po, 



Control 



Signals 



Data 
lines 



10K 



10K 



KEY PAD 
(4X4) 



V 



EN 

R/W 

RS 



Vcc 




D7 LCD 
(16X2) 

DO 



1K 



? 



5V 



10K 



+5V 



-C BC547 




Buzzer 



Figure 6. 3 Circuit diagram of microcontroller-based menu card 



Program Source Code 

*^r£ *& ~^£ *& *& *& "^l^ "^l^ "^£ *& *& *& *& *& "^£ "^C "^£ *& "^£ "^r£ *& "^£ "^l^ "^l^ *& "^l^ *& *& *& "^£ *& "^l^ "^l^ *& *& "^l^ "^£ "^£ "^l^ *& *& "^£ *& *& "^r£ "^£ "^£ "^£ *& "^£ *& *& "^£ *& "^£ *& "^l^ 



^include <REG52.H> 

^include <stdio.h> 

/* for the intended 8051 derivative 



special function register declarations 



sbit RS : 
sbit RW 
sbit EL : 
sbit BU 

sbit Rl = 
sbit R2 = 
sbit R3 = 
sbit R4 = 



P2 A 0; 
: P2 A 1; 

P2 A 2; 
P2 A 4; 



P0 A 
P0 A 1 
P0 A 2 
P0 A 3 



sbit CI = P0 A 4; 
sbit C2 = P0 A 5; 



96 Application 3: Cafeteria Food Alert/ Microcontroller-based Menu Card 

sbit C3 = P0 A 6; 
sbit C4 = P0 A 7; 

void delay(int); /* Stop Execution with Serial Intr. */ 

void INIT(void); 
void ENABLE (void); 
void LINE(int); 
int keyb(void); 

void LINE (int i){ 
if (i==l) { 
RS=0; 
RW=0; 
Pl=0x80; 
ENABLE 
RS=1; 

} 
else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE 

RS=1; 

} 
} 

void delay (int k) 

{ 

int i,j; 

for (j=0;j<k+l;j++){ 

for (i=0;i<100;i++); 

}} 

void ENABLE (void) 

{ 
EL=1; 

delay(l); 

EL=0; 

delay(l); 

} 



Embedding Microcontroller in Routine Applications 



97 



2 lines and 5*7 matrix LCD. 



void INIT(void) // Initialization of the LCD by giving the proper 

commands. 

{ 

RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLE() 

ENABLE() 

ENABLE() 

ENABLE() 

PI = 0x06; 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLE(); 

} 

int keyb(void){ 

int key=0; 

Cl=l 
C2=l 
C3=l 
C4=l 



//Shift cursor to left 

Display ON, Cursor Blinking 
Clear display Screen. 



R1=0: 
R2=l 
R3=l 
R4=l 

if (CI: 
if (C2 = 
if (C3= 

if (C4= 

Rl=l 
R2=0: 
R3=l 
R4=l 



0) key 
0) key 
0) key 
=0) key 



1 

2: 
3: 
4: 



98 



Application 3: Cafeteria Food Alert/ Microcontroller-based Menu Card 



if (C1==0) key = 5 
if (C2==0) key = 6 
if (C3==0) key = 7 
if (C4==0) key = 8 

Rl=l; 
R2=l; 
R3=0; 
R4=l; 



if (C1==0) key = 9; 
if (C2==0) key = 10 
if (C3==0) key = 11 
if (C4==0) key = 12 

Rl=l; 
R2=l; 
R3=l; 

R4=0; 

if (C1==0) key = 13 

if (C2==0) key = 14 
if (C3==0) key = 15 
if (C4==0) key = 16 
return(key); 

} 



void main(void) { 

char arrayl[] = "tea"; 

char array2 [] = "wheat" ; 

char array3 [] = "rice" ; 

char array4 [] = "dal" ; 

char array 5 [] = "jaggery" ; 

char array6 [] = "coffee" ; 

char array7[] = "item is not there in menu"; 

char array8[] = "Get the bill"; 

char *p; 

int j,i; 

INITQ; 

LINE(l); 

j=0; 



Embedding Microcontroller in Routine Applications 99 



while(l){ 

j=0; 

j = keyb(); 

if(j==l){ 

for (i=0;i<8;i++){ 

p=&arrayl; 

Pl= *p+ + ; 

ENABLE(); 

}} 
if(j==2){ 

for (i=0;i<8;i++){ 

p=&array2; 

Pl= *p+ + ; 

ENABLE(); 

}} 

if(j==3){ 

for (i=0;i<8;i++){ 
p=&array3; 
Pl= *p++; 

ENABLE(); 

}} 

if(j==4){ 

for (i=0;i<8;i++){ 
p=&array4; 
Pl= *p++; 

ENABLE(); 

}} 

if(j==5){ 

for (i=0;i<8;i++){ 
p=&array5; 
Pl= *p++; 

ENABLE(); 

}} 
if(j==6){ 

for (i=0;i<8;i++){ 
p=&array6; 
Pl= *p+ + ; 

ENABLEi 
}} 



100 Application 4- Chimney Sentinel 

if(j==7){ 
for (i=0;i<8;i++){ 
p=&array7; 
Pl= *p++; 
ENABLE(); 

}} 

if(j==8){ 

for (i=0;i<8;i++){ 
p=&array8; 
Pl= *p++; 
ENABLE(); 

}} 

delay (400); 

ENABLE(); 
delay (400); 

} 

6.4 Application 4: Chimney Sentinel 

The reports of incidents of fire due to wood-burning appliances are 
reported every year. This causes lots of damage to the human being as 
well as property. The device consists of a probe comprising a tempera- 
ture sensor LM35 inserted in the chimney. This is in turn interfaced to 
ADC0808 and AT89S52 microcontroller-based monitoring unit. When 
the temperature rises the preset value set by the user, a fire is detected, 
and the unit sounds an alarm. There is also a provision to display the 
temperature on the LCD. 

Program Source Code 

^include <REG52.H> /* special function register declarations */ 

^include <stdio.h> 

/* for the intended 8051 derivative */ 

sbit RS = P2 A 0; 

sbit RW = P2 A 1; 

sbit EL = P2 A 2: 



Embedding Microcontroller in Routine Applications 101 

sbit BUZZ=P2 A 3; 
sbit SOC= P2 A 4; 

sbit a =P2 A 5; 
sbit b = P2 A 6; 
sbit c =P2 A 7; 

void delay (int); 
void INIT(void); 
void ENABLE (void); 
void LINE(int); 

void LINE (int i){ 
if(i==l){ 

RS=0; 

RW=0; 

P0=0x80; 

ENABLE(); 

RS=1; 

} 
else 

{ 

RS=0; 

RW=0; 

P0=0xC0; 

ENABLE(); 
RS=1; 

} 
} 

void delay (int k) 

{ 

int i,j; 

for (j=0;j<k+l;j++) 

{ 

for (i=0;i<10000;i++); 

} 

} 

void ENABLE (void) 

{ 
EL=1; 



102 



Application 4-' Chimney Sentinel 



delay(l); 

EL=0; 

delay(l); 

} 

void INIT(void) 

{ 



// Initialization of the LCD by giving the proper 
commands. 



} 



RS=0; 

RW=0; 

EL=0; 

PI = 0x38; // 2 lines and 5*7 matrix LCD. 

ENABLE() 

ENABLE() 

ENABLE() 

ENABLE() 

PI = 0x06; //Shift cursor to left 

ENABLE(); 

PI = OxOE; // Display ON, Cursor Blinking 

ENABLE(); 

PI = 0x01; // Clear display Screen 

ENABLEQ; 



void main (void) 

{ 

int unit, tens, hundred, unitl, tensl, hundredl; 

unsigned char d; 

a=0; 

b=0; 

c=0; 

while(l) 

{ 

Pl=0xff; 
SOC=l; 

delay (8); 
SOC=0; 
delay (8); 



Embedding Microcontroller in Routine Applications 103 

SOC=l; 

delay (8); 

d=Pl; 
if(d>40) 

{ 

BUZZ=1; // switch on the buzzer if temp is greater than 40 

} 

else 

{ 

BUZZ=0; 

} 

unit = (d%10); 

tens = (d/10)%10; 

hundred = (d/100); 

unit = (unit + 0x30); 

unit 1 =unit+unit ; 

tens = (tens + 0x30); 

tensl=tens+tens; 

hundred = (hundred + 0x30); 

hundred 1 = hundred +hundred ; 

INIT(); 
LINE(l); 

P0=hundredl; 

ENABLE(); 

P0=tensl; 

ENABLE(); 

P0='.'; 

ENABLE(); 

PO=unitl; 

ENABLE(); 

PO='c'; 

ENABLEi 

} 
} 



104 



Application 5: Who ? s First Timer 



LCD 

CeO 067 ft* *v &i 



I :». 



"~> 



V — V — ¥ 



K 



♦5v 



10K 

' ■■■i 



E~ 



Pt» ''or Pm Pj Rj . 



Vac 

XTAL1 

* P.* »".. P.. P- P.. * 



AT89 S 52 



P t , 



5^? 



^^ fi? 



3% r* j3 a 

J L_JL_! t — at 



C* D.' A ft C S« 



C1K 




■j^?« ADC 0808 

j^ * C 4 t I. * K t «. 

*\ *\ '! a l l \ *l 6 I 



IK 
■Wmv 



"C»wy 






BlizemS 



JKtiH^Sqwwk*) 



Figure 6.4 Circuit diagram of microcontroller based chimney sentinel unit 



6.5 Application 5: Who's First Timer 

This unit is ideal as a timer for quiz competitions. The person who 
first presses the key will be detected and his or her name will be displayed 
on LCD. The unit also sounds a buzzer to indicate that key has been 
pressed. The application is designed for eight users but can be modified 
easily to accommodate mode number of users. 

Program Source Code 



#include <REG52.H> 
^include <stdio.h> 



* special function register declarations 

* for the intended 8051 derivative */ 



sbit RS = 
sbit RW 
sbit EL : 



P2 A 0; 
: P2 A 1; 
P2 A 2; 



Embedding Microcontroller in Routine Applications 



105 



sbit Rl = P0 A 0; 




sbit R2 = P0 A 1; 


sbit R3 = P0 A 2; 


sbit R4 = P0 A 3; 


sbit CI = P0 A 4; 


sbit C2 = P0 A 5; 


sbit C3 = P0 A 6; 


sbit C4 = P0 A 7; 


sbit buzzl= P3 A 0; 


sbit buzz2= P3 A 1 




sbit buzz3= P3 A 2 




sbit buzz4= P3 A 3 




sbit buzz5= P3 A 4; 


sbit buzz6= P3 A 5 




sbit buzz7= P3 A 6 




sbit buzz8= P3 A 7 




void delay (int); 
void INIT(void); 


void ENABLE (void); 


void LINE(int); 
int keyb(void); 


void LINE(int i){ 

if (i==l) { 
RS=0; 


RW=0; 


P 1=0x80; 


ENABLE(); 
RS=1; 


} 
else 


{ 

RS=0; 


RW=0; 


Pl=0xC0; 


ENABLE(); 
RS=1; 


} 





106 



Application 5: Who ? s First Timer 



} 



void delay (int k) 

{ 

int i,j; 

for (j=0;j<k+l;j++){ 

for (i=0;i<100;i++); 

}} 

void ENABLE (void) 

{ 
EL=1; 

delay(l); 

EL=0; 

delay(l); 

} 

void INIT(void) 



{ 



} 



RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLEO 
ENABLEQ 
ENABLE() 
ENABLE() 
PI = 0x06; 

ENABLEO; 
PI = OxOE; 
ENABLE(); 
PI = 0x01; 

ENABLEO; 



// Initialization of the LCD by giving the proper 
commands. 



2 lines and 5*7 matrix LCD. 



//Shift cursor to left 

// Display ON, Cursor Blinking 



Clear display Screen 



int keyb(void){ 

int key=0; 

Cl=l 

C2=l 

C3=l 

C4=l 



//8user 



Embedding Microcontroller in Routine Applications 107 

R1=0: 
R2=l 
R3=l 
R4=l 

if (C1==0) 

{ 

key = 1; 

buzzl=0; 

} 

if (C2==0) 

{ 

key = 2; 

buzz2=0; 

} 

if (C3==0) 

{ 

key = 3; 

buzz3=0; 
} 

if (C4==0) 

{ 

key = 4; 

buzz4=0; 

} 
Rl=l 

R2=0: 

R3=l 

R4=l 

if (C1==0) 

{ 

key = 5; 

buzz5=0; 

} 

if (C2==0) 

{ 

key = 6; 

buzz6=0; 

} 

if (C3==0) 



108 



Application 5: Who ? s First Timer 



{ 

key = 7; 

buzz7=0; 

} 

if (C4==0) 
{key = 8; 
buzz8=0; 

} 

return(key); 

} 

void main(void) 
char arrayl[] = 
char array2[] = 
char array3[] = 
char array4[] = 
char array5[] = 
char array6[] = 
char array7[] = 
char array8[] = 



{ 

jivan" ; 
kunal" : 
rupesh' 
chari" ; 
roy" ; 
jesni"; 
vinod" 
John" ; 



char *p,key; 
int j,i; 

INIT(); 
LINE(l); 

j=0; 

while(l){ 

j=0; 

j = keyb(); 

if(key==l){ 
for (i=0;i<8;i++){ 
p=&; array 1; 
Pl= *p++; 

ENABLE(); 

}} 

if(key==2){ 

for (i=0;i<8;i++){ 
p=&array2; 
Pl= *p++; 
ENABLEQ; 



Embedding Microcontroller in Routine Applications 109 

}} 

if(key==3){ 
for (i=0;i<8;i++){ 
p=&array3; 
Pl= *p++; 

ENABLE(); 

}} 

if(key==4){ 

for (i=0;i<8;i++){ 
p=&array4; 
Pl= *p++; 
ENABLE(); 

}} 

if(key==5){ 

for (i=0;i<8;i++){ 
p=&array5; 
Pl= *p+ + ; 

ENABLE(); 

}} 

if(key==6){ 

for (i=0;i<8;i++){ 
p=&array6; 
Pl= *p+ + ; 

ENABLE(); 

}} 

if(key==7){ 

for (i=0;i<8;i++){ 
p=&array7; 
Pl= *p++; 

ENABLE(); 

}} 

if(key==8){ 

for (i=0;i<8;i++){ 
p=&array8; 
Pl= *p++; 
ENABLE(); 

}} 

delay (400); 

} 
} 

"^£ "^£ "^l^ "^£ *& *& "^£ "£? "^£ "^£ "£? "£? "£? "£? "^£ "^£ *& "^£ *& "^£ "^£ *& *& "^l^ "^l^ *& "^£ *& "^£ *& "^C "^£ *& "^£ "^£ *& "^£ "^£ *& "^£ "^£ *& "^£ *& "^£ "^l^ "^l^ "^l^ ^l^ "^l^ "^£ "^£ *& "^£ *& "^£ "^£ 



110 



Application 6: Counting Cars 



Buzzed 




+Vcc 



1K 



Key 1 



User! 



Buzzer-2 



KEY-2 

User 2 



P 



+Vcc 



10K 



I 



+VCC VSS VEE 

LCD (16X2) 



RS WW EN 



j > A , . 



7Y 



Q_ D. Q. □_ 

AT 89 S 52 




Q. £L 



Q. Q_ qT oT qT dT qTu. Q.Q- 



User3 



User4 



User5 



User7 



Bu??Br-7 



hu.' -■-■ ir t-i 



KLY U 

User6 



Figure 6.5 Circuit diagram of Who's first timer 



6.6 Application 6: Counting Cars 

As shown in Figure 6.6, IR transceiver is connected to the port pin 
PO.O (sensor) through which the number of cars are counted as they pass 
through the passage and interrupt the IR link. The count is displayed 
on the LCD connected to port PI. The system is able to count the cars 
maximum up to 9999. 

Program Source Code 



^include <REG52.H> /* special function register declarations 
^include <stdio.h> /* for the intended 8051 derivative */ 

sbit sensor = P0 A 0; // IR sensor input 

sbit RS = P2 A 0; 

sbit RW = P2 A 1; 

sbit EL = P2 A 2; 

unsigned int unit, ten, hundred, tenth, count; 



Embedding Microcontroller in Routine Applications 



111 



void delay (int); 
void INIT(void); 
void ENABLE(void); 
void LINE(int); 

int updatecount(void); /* Function for update the count after passing 

the car through the passage*/ 



int updatecount() 
{if (sensor==l) 



{ 

count =count+l; 

} 

else 

{ 

count = count +0; 

} 

return (count); 



When the input pin detects the pulse incre- 
ment the count by one otherwise keep it as it 



was 



* 



// increment count by 1 



// keep count unchanged 
returns the updated count value for next reference 



} 

void LINE (int i) /* function to define the display characters on LCD 

on specified line */ 

{ 



} 



if (i==i 
{ 

RS=0; 
RW=0; 
PI =0x80; 
ENABLE(); 
RS=1; 

} 

else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE(); 

RS=1; 

} 



Force cursor to beginning of the first line 
Enable LCD 
Reset the LCD 



Force cursor to beginning of the second line 



112 



Application 6: Counting Cars 



void delay (int k) // Delay function 

{ 

int i,j; 

for (j=0;j<k+l;j++) // Delay loop 

{ 

for (i=0;i<10000;i++); 

} 
} 



Function to Enable the LCD 

// Give high to low pulse to enable pin of 
the LCD 



LCD of 2 lines and 5x7 matrix 



void ENABLE(void) 

{ 
EL=1; 

delay(l); 

EL=0; 

delay(l); 

} 



void INIT(void) // Function to Initialize the LCD 

{ 

RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLEO 
ENABLE() 
ENABLE() 
ENABLE() 
PI = 0x06; 

ENABLEO; 
PI = OxOE; 
ENABLE(); 
PI = 0x01; 
ENABLEO; 
} 

void main (void) 

{ 

int count =0; 



Shift cursor to right 
Display on, cursor blinking 



Embedding Microcontroller in Routine Applications 



113 



int k; 

char *p; 

char array[] = "No of Cars="; /* Array to display the characters "No 

of Cars=" on the LCD */ 
INITi 



while (1 

{ 

count= updatecount(); /* Assign the returned new value to update the 

count */ 

/* Points the next location on the LCD to 
display the character*/ 



p=&array; 



// Increment the pointer 



for (k=0;k<17;k++) 

{ 

if (k==0) 

LINE(l); 

Pl= *p+ + ; 

ENABLE(); 

LINE(2); 

unit =(count%10); 

ten=(count/10)%10; /* Display no of cars and the count on LCD 

on respective decimal position. The character 
to display should be in ASCII form.*/ 

hundred= (count/ 100)% 10; 

tenth= (count/ 1000); 

Pl= (tenth+0x30); 

ENABLE(); 

Pl= (hundred+0x30); 

ENABLE(); 

Pl= (ten+0x30); 

ENABLE(); 

Pl= (unit+0x30); 



Send the ASCII data to LCD 



ENABLEQ; 



}} 



114 



Application 7: Anonymous Voting 



33PF 
^1— 



DXTAL 



^r 



^ 33PF 



+5V 



Vcc 



XTAL 
XTAL2 



P2.7 
P2.1 
P2.0 

P2.0 

P1.0 



AT89S52 



Po.o 



GND 



X 



\ 



EN Vcc 

R/W 
RS 



VEE 



Vss 
D7 LCD 

HD44780 
Do (16x2) 



+5V 

r 



10K 



+Vcc 




Photo transistor 



Road 



Figure 6. 6 Circuit diagram of the system for counting cars 

6.7 Application 7: Anonymous Voting 

A useful device for taking the audience poll regarding a lecture or any 
other issue is described in this application. This device will be passed 
on to each and every member of the audience one by one. A message 
appears on the LCD as regards to whether the lecture is satisfactory or 
otherwise. Accordingly the user has to press key 1 or 2. The poll will be 
displayed as soon as key 3 is pressed. 

Program Source Code 



#include <REG52.H> 
^include <stdio.h> 



P2 A 0; 
: P2 A 1; 
P2 A 2; 

sbit BU = P2 A 4: 



sbit RS : 
sbit RW 
sbit EL : 



/* special function register declarations 
/* for the intended 8051 derivative */ 



// LCD control signals 



// Buzzer as a output 



_ r>nAn. 



sbit Rl = P0 A 0; 



Hex keypad connections 



Embedding Microcontroller in Routine Applications 



115 



sbit R2 = P0 A 1; 


sbit R3 = P0 A 2; 


sbit R4 = P0 A 3; 


sbit CI = P0 A 4; 


sbit C2 = P0 A 5; 


sbit C3 = P0 A 6; 


sbit C4 = P0 A 7; 


void Delay (int); 


void INIT(void); 


void ENABLE (void); 


void LINE(int); 


int keyb(void); 


void LINE (int i) 


{ 


if (i==l) { 


RS=0; 


RW=0; 


PI =0x80; 


ENABLE(); 


RS=1; 


} 


else 


{ 


RS=0; 


RW=0; 


Pl=0xC0; 


ENABLE(); 


RS=1; 


} 


} 


void delay (int k) 


{ 


int i,j; 


for (j=0;j<k+l;j++){ 


for (i=0;i<100;i++); 



/* Function for the LCD display line selection 
and giving the respective commands to LCD * 



Delay function 



}} 



116 



Application 7: Anonymous Voting 



void ENABLE(void) 

{ 
EL=1; 

delay(l); 

EL=0; 

delay(l); 

} 



Function to Enable the LCD. Give high 
to low pulse on EL. 



{ 



} 



void INIT(void) /* Initialization of the LCD by sending the 

commands sequentially */ 



RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLE() 

ENABLEQ 

ENABLEQ 

ENABLEQ 

PI = 0x06; 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLEQ; 



int keyb(void) 

{ 

int key=0; 

Cl=l 
C2=l 
C3=l 
C4=l 



Keyboard scanning function. Checks which 
key is pressed. 



R1=0: 
R2=l 
R3=l 
R4=l 



Embedding Microcontroller in Routine Applications 



117 



if (C1==0) key = 1 
if (C2==0) key = 2 
if (C3==0) key = 3 
if (C4==0) key = 4 



Rl=l 
R2=0 
R3=l 
R4=l 



if (C1==0) key = 5 
if (C2==0) key = 6 
if (C3==0) key = 7 
if (C4==0) key = 8 



Rl=l 
R2=l 
R3=0 
R4=l; 



if (C1==0) key = 9; 
if (C2==0) key = 10 
if (C3==0) key = 11 
if (C4==0) key = 12 



Rl=l 
R2=l 
R3=l 
R4=0; 

if (C1==0) key = 13 
if (C2==0) key = 14 
if (C3==0) key = 15 
if (C4==0) key = 16 
return (key); 

} 

void main (void) 

{ 

char votel[] = "Lecture is satisfactory: Press 1"; /* Array for the 

characters to display 
on the LCD. */ 

char vote2[] = "Lecture is not up to mark: Press 2"; 



118 



Application 7: Anonymous Voting 



char *p; // Pointer to point the next character in the 

array 
int j,i; 
INIT(); 
LINE(l); 

j=0; 

while(l) 

{ /* When key 1 is pressed matter raised is ok */ 

j=0; 

j = keyb(); 

if (J==l){ 

p=&votel; // Memory address define to array and defined a pointer to 

point that data. 

for(i=0;i<17;i++) 

{ 

if(i==0) // Display the data on the first line on the LCD 

screen 
LINE(l); 
if(i==8) 

LINE(2); // Display the data on the second line on the LCD screen 
Pl= *p++; // Pointer is incremented and the data pointed by pointer 

is sent on the port 1. 
ENABLE(); 
Delay (200); 

} 

if (j==2){ /* If key 2 is pressed then the vote is for the matter 

is not enough */ 
p=&vote2; 
for(i=0;i<17;i++) 

{ 

if(i==0) 

LINE(l); 

if(i==8) 

LINE(2); // Display the content on line 2 

Pl= *p++; // Increment the pointer 

ENABLE(); 

Delay (200); 

} 

} 

}}} //End of the main 



"^l^ "^l^ *& *& "^£ "^£ *& "^£ "^£ *& "^£ "^£ "^r£ "^£ *& "^r£ "^£ "^l^ *& "^£ *& "^£ "^£ *& "^£ *& *& *& "£? *& "^£ *& "^£ "^£ "^£ "^£ *& *& "^£ *& "^£ "^£ *& "^£ "^£ *& "^£ *& *& "^£ *& "^£ "^£ *& "^£ "^£ *& 



Embedding Microcontroller in Routine Applications 



119 



33PF 



12MHzQ] XTAL 



33PF 




& 10K 



6.8 



Figure 6. 7 Circuit diagram of unit for anonymous voting 

Energy Efficient Lighting 
Using Microcontroller 



Sometimes the incandescent light bulb is referred to as a "heat bulb," 
because 90% of the electricity delivered to it comes out as heat. Precisely 
we have used this property to build a laboratory type PID application to 
illustrate the code in Chapter 6. However, the theme of the present chap- 
ter is energy efficient lighting using microcontrollers. With the growing 
concern about the energy crisis, almost all the industrialized countries 
are now coming out with new methods to save energy, especially electri- 
cal energy. It is estimated that the yearly usage of lighting for a single 
office room is 1000 h which leads to 20 KWh/m 2 for a light source which 
gives 20W/m 2 . With a microcontroller-based light switching or even 
dimming applications a 50% savings can be achieved. Recently, Freescale 
Semiconductor has come out with a new 8-bit HC908LB8 microcontroller 
that offers single-chip solution for energy-efficient lighting systems. How- 
ever, the applications developed in this chapter are based on AT89S52 
microcontroller. 



Application 8: Optimize the Electric Power 
Consumption in the Corridors 

In the long corridors of the hotels, unnecessary electricity is consumed 
on the lights. Ideally when no one is there the lights should be switched 
off. As the person passes from one end to the other the corresponding 



120 



Energy Efficient Lighting Using Microcontroller 



H2V 



33W 



Array 

Of 

IRLED, 



-12V 





A 


s? 






a* 


C 


^ 33ft 


O 
R 


5? 


R 
I 


SP 


D 



5P 


R 


5? 






i 




r ? 







470 i 






: v 



: v 



\ 






Array CM IR Photo transistors 



4701! 



iVee 



P 

P ° A 
p » T 

p a 

9 

p S 

P 5 

2 

p 



vss 



p 



p 



V, I23CV} 




3301 ( 



V„ (230V) 



£H? 



a 1 . 

MOCWttl 



BuiDi 



*Vcc 



V, (230V) 



2^ 



i>Hv 



BulES 



Figure 6. 8 Circuit diagram of the system for auto switching of lights in the corridor 



lights should be switched on so that he or she will be guided toward the 
corridor end. This problem is solved by using arrays of pairs of IR LEDs 
and phototransistor throughout the corridor placed at equal interval as 
shown in the block schematic. The array of IR LEDs are in a continuous 
emitting mode. The corresponding IR phototransistors are aligned at 
45° for maximizing sensitivity. Value of the resistance (1M(] to 470fi) 
connected to the collector of the phototransistor decides its sensitivity. 
When the IR link breaks due to the person passing the corridor, a low to 
high going transition is detected by the port lines. The corresponding 
bulbs connected to port 1 are made ON and OFF so as to light the 
corridor as the person makes his way to the other end. 

Program Source Code 



#include <REG52.H> t 

^include <stdio.h> 

/* for the intended 8051 derivative 



special function register declarations 



_ DnAi 



sbit sensorl= PO 0; 



/* Output from the 8 sensors is connected to 
the port pins of the port */ 



sbit sensor2= P0 A 1 
sbit sensor3= P0 A 2 
sbit sensor4= P0 A 3 



Embedding Microcontroller in Routine Applications 



121 



sbit sensor5 : 
sbit sensor6 : 
sbit sensor 7- 
sbit sensor^ 



P0 A 4; 
P0 A 5; 
P0 A 6; 
P0 A 7; 



/* Connecting the relays to on/off the power to the port 1 

sbit RL1= P1 A 0: 

sbit RL2= P1 A 1 

sbit RL3= P1 A 2 

sbit RL4= P1 A 3 

sbit RL5= P1 A 4 

sbit RL6= P1 A 5 

sbit RL7= P1 A 6 

sbit RL8= P1 A 7 



void main (void) 

{ 
P0=0x00; 

Pl=0x00; 

while(l) 

{ 

if (sensor 1==1) 

RL1=1; 



// Main function 



Sense the first sensor 



If its output is high then switch the relay on 



else if (sensor2==l) // otherwise check the second sensor. 

{ 

RL1=0; // Off relay 1 and on relay 2 
RL2=1; 

} 

else if (sensor3==l) 

{ 

RL3=1; 
RL2=0; 

} 

else if (sensor4==l) 

{ 

RL4=1; 
RL3=0; 

} 

else if (sensor5==l) 



122 Energy Efficient Lighting Using Microcontroller 

{ 

RL5=1; 
RL4=0; 

} 

else if (sensor6==l) 

{ 

RL6=1; 
RL5=0; 

} 

else if (sensor7==l) 

{ 

RL7=1; 
RL6=0; 

} 

else if (sensor8==l) 

{ 

RL8=1; 
RL7=0; 

} 
} 

} 



Chapter 7 

Microcontroller-based Measurement 
and Control Applications 



7.1 Application 1: Reading a PWM Waveform 

Using Microcontroller 

There are many applications in which the microcontroller is used as a 
PWM generator for controlling purpose. For instance, the servo motor 
control or even the temperature controller can be driven on the basis of 
ON time modulation. However, in the following application, the PWM 
waveform generated by IC 555 timer is monitored by the microcontroller 
AT89S52 through port pin 2.4. The ON-time and OFF-time of the PWM 
are displayed on the LCD. The application may be used to interface 
resistive sensors like thermistor to display the temperature directly. The 
main advantage of the PWM-based measurement is the possibility of 
theoretically infinite resolution of the measurement. 

Program Source Code 

^include <REG52.H> /* special function register declarations */ 

/* for the intended 8051 derivative */ 
sbit RS = P2D; 
sbit RW = P2 A 1; 
sbit EN = P2 A 2: 



sbit IN = P2 A 4; /*input from 555 oscillator*/ 

void delay (int); 
void INIT(void); 
void ENABLE(void); 
voidLINE(int); 



123 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 123-138. 
© 2007 Springer. 



124 Application 1: Reading a PWM Waveform Using Microcontroller 

int ONTIME(int); 
int offtime(int); 

void LINE (int i){ 
if (i==l) { 
RS=0; 
RW=0; 
Pl=0x80; 
ENABLE(); 
RS=1; 

} 

else 

{ 

RS=0; 

RW=0; 

Pl=0xC0; 

ENABLE(); 
RS=1; 

} 
} 

void delay () 

{ 

int i,j; 

for (j=0;j<10;j++){ 

for (i=0;i<100;i++); 

}} 

void ENABLE (void) 

{ 

EN=1; 

delay (); 
EN=0; 
delay (); 

} 

void INIT(void) // Initialization of the LCD by giving the proper 

commands 

{ 

RS=0; 
RW=0; 

EN=0; 



Microcontroller-based Measurement and Control Applications 



125 



} 



PI = 0x38; 

ENABLE() 

ENABLEQ 

ENABLEQ 

ENABLEQ 

PI = 0x06; 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLEQ; 



2 lines and 5*7 matrix LCD 



//Shift cursor to left 



Display ON, Cursor Blinking 
Clear display screen 



int ONTIME(int m){ 
if (m==l) 

{ 
IN=1; 

TMOD=0x01; 

TR0=0; 

TF0=0; 

TL0=0x00; 

TH0=0x00; 

while(IN); 

while(!IN); 



to measure On time 



input to 8052 from 555 osc : 



check for rising edge 



TR0=1; 

while(IN); 
TR0=0; 

} 

if(m= =2) 

{ 
IN=1; 

TMOD=0x01; 

TR0=0; 

TF0=0; 

TL0=0x00; 

TH0=0x00; 



check for falling edge 



to measure offtime' 



while(!IN); 
while(IN); 



check for falling edge 



TR0=1; 



126 Application 1: Reading a PWM Waveform Using Microcontroller 



while(!IN); // check for rising edge 

TR0=0; 

} 
return((TH0*256)+TL0); 

} 

void main (void){ 

int unit, tens, hundred, thousand, tenthou, x; 

char code dis3[] = "Fre in HZ="; 

char *p; 

int i,j,k,freq,l; 

while(l) { 

for (x=l;x<=3;x++){ 

if(x==l) 

{ 

i = ONTIME(x); 

k=i; 

} 

if( x = =2) 

{ 

i = offtime(x); 

l=i; 

} 

if ( x = =3) 

{ 
freq=k+l; 

i=l/freq ; //convert time to frequency 

} 

unit = (i%10); 
tens = (i/10)%10; 
hundred = (i/100)%10; 
thousand = (i/1000)%10; 
tenthou = (i/10000)%10; 
unit = unit + 0x30; 
tens = tens + 0x30; 
hundred = hundred + 0x30; 
thousand = thousand + 0x30; 
tenthou = tenthou + 0x30; 



Microcontroller-based Measurement and Control Applications 127 



INIT(); 

LINE(l); 

p=&dis3; // display freq on LCD 

for (j=0;j<8;j++){ 

Pl=* p+ + ; 

ENABLE(); 
} 

LINE(2); 

Pl=tenthou; 

ENABLE(); 

Pl=thousand; 

ENABLE(); 

Pl=hundred; 

ENABLE(); 

Pl=tens; 

ENABLE(); 

Pl=unit; 

ENABLE(); 

} 



7.2 Single Set-point On/Off Controller 

An on/off controller is the simplest form of temperature control 
device. In the following application, the process consists of a simple 
heating unit based on Neon bulb. The sensor used is LM35, the output 
of which is conditioned by using OP07. The digitization is done by using 
ADC7135. The end of conversion is sensed by using the port pin 3.4 of 
AT89S52. The data is taken in using port PO. The set-point is kept at 
40, but the same can be varied based on the application needs. The LCD 
displays the set-point as well as current temperature. The controlling 
is done by using a relay driven by port line P2.3 through transistor 
2N2222. 



128 



Single Set-point On/Off Controller 




o 

o 
o 

o 



o 

o 

+3 

o 
o 



Oh 



*"1 



Microcontroller-based Measurement and Control Applications 



129 



LCD 

Module 
Do D 7 




M89552 
Microcontroller 




Relay 



r 



Do 



D 7 



ADC 7135 



LM 
35 



Figure 7.2 Block schematic of microcontroller based on/off controller 



Program Source Code 

#include<REG52.H> 
void busy _count (void); 

void LINE(int a); 
void ENABLE(void); 
void init(void); 
//void init Jed (void); 
sbit elk = P3 A 5; 
sbit BUSY=P3 A 4; 
sbit RS = P2 A 0; 
sbit RW = P2 A 1; 
sbit EL = P2 A 2; 
sbit RL = P2 A 3; 
int count _u, count _t; 



void main() 

{ 

TMOD=0x50; 
BUSY=1; 

init(); 
busy_count(); 

} 



start timer in function*/ 



130 



Single Set-point On/Off Controller 



start counter 1 



void busy _count (void) 

{ 

int count, count 1; 
TR0=0; 
TH0=0x00; 
TL0=0x00; 
count=0x00; 
while(BUSY); 
while(!BUSY); 
while(BUSY) 

{ 
TR0=1; 

} 
while(!BUSY) 

{ 
TR0=0; 

} 
count=((TH0*256)+TL0); 

countl=count— 10000; 

count_u=count%10; 

count_t=(count/10)%10; 

RS=1; 

LINE(l); 

if (count >40) 



when busy goes low stop counter' 



//if temperature is greater than 40 than turn off 
the relay 



{ 
RL=1; 

} 
else 

{ 

RL=0; 

} 
Pl=(count_t+0x30); 

ENABLE(); 

Pl=(count_u+0x30); 

ENABLEi 

} 



void init(void){ 
RS=0; 
RW=0; 
EL=0; 



Microcontroller-based Measurement and Control Applications 131 

PI = 0x38; 

ENABLE() 

ENABLE() 

ENABLE() 

ENABLE() 

PI = 0x06; 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLE(); 

} 

void LINE(int i){ 
if (i==l) { 
RS=0; 
RW=0; 
Pl=0x80; 
ENABLE (); 
RS=1; 

} 
else 

{ 

RS=0; 

RW=0; 

Pl=OxCO; 

ENABLE(); 
RS=1; 

} 

} 

void ENABLE(void) 

{ 
EL=0; 

//delay(l); 

EL=1; 

//delay(l); 

EL=0; 



132 



Single Set-point On/Off Controller 



HK 



+ 



X 

(fi 



W 


o Q 


> 


«o 




1" A 




g « 


M 


wa 


> 


sa 




-:r* 



g 
o 





H 


H* 


> 


O 


uj ro 


m 

4 














nr 



o 

o 
o 

to 

o 
o 

CD 
i 

fH 

'o 

o 
o 
o 

o 



4h 

o 



Co 

bJO 

ct 



2 
O 

O 






Microcontroller-based Measurement and Control Applications 



133 



+Vcc 

o 



10K 



1 



1 



Vcc 



Vss 



VEE 



HD 44780 (16X2) 
LCD 



CO 



Q Q UL C£ LU 

^^\ A * 7K 



33PF 

12MH [ ] XTAL 



+Vcc 

L 



33PF 



d 
a 
1 

a 



Vcc p D D p p 

■2.0 ~2 7 "0.4 '0.5 "0 6 

XTAL1 



XTAL2 
GND 



AT 89S52 



D o 



Battery 3.6V 



33PF =J= =^ 



1 



SCL 



?— i 



33PF 



1N41 



1N41 



H<F 



100a 



1 , 1N41 



6 5 



PCF 8583 
12 3 4 



T 



10 M F 

it* 



1 



+ Vcc 



10K 



SDA 



8 7 6 5 

AT 2404 

12 3 4 



10K 



Figure 7.4 Circuit diagram for I C interface 



7.3 



Application 3: I 2 C Interface with Serial 
EPROM 



In the context of microcontroller-based process control applications, 
many embedded designers are experiencing the inadequacy of the on-chip 
memory. The simplest alternative is to interface an external EPROM. 
I 2 C-based serial peripherals offers maximum circuit efficiency with the 
interface simplicity. The prime advantage of this interface is that only 
two lines (clock and data) are required for full duplexed communica- 
tion between multiple devices. The operating range of the interface is 
typically 100 KHz to 400 KHz. I 2 C protocol assigns a unique address to 
every peripheral. The peripheral can act as a receiver and/or transmitter 
depending on its functionality. 



134 Application 3: I 2 C Interface with Serial EPROM 

The application developed here illustrates the I 2 C-enabled code devel- 
opment for the PCF8583 Real-Time Clock and AT2404 Serial EPROM. 
In many data logging applications the data needs to be collected with 
the time stamp. The RTC PCF8583 will facilitate the time stamping 
operation while the acquired data can be stored in the serial EPROM 
AT2404. 

Program Source Code 

"^£ "^r£ *& *& "^£ *& *& *& "^l^ "^l^ "^l^ "^l^ "^l^ "^l^ *& *& "^l^ *& *& ^l^ *& *& *& *& *& *& *& *& *& "^£ *& *& "^l^ *& *& ^l^ *& "^£ ^l^ *& *& *& *& "^l^ "^l^ *& "^l^ *& *& *& "^r£ *& *& *& 

^include <reg52.H> 

sbit sda=P0 A 0; 
sbit scl=P0 A l; 
sbit led=Pl A 0; 

sbit RS=P0 A 4; 
sbit RW=P0 A 5; 
sbit EN=P0 A 6; 

int x; 

unsigned char dat; 

int ack(void); 

void start (void); 

void stop (void); 

void delay (void); 

void enable(void); 

void add (int); 

void ini(void); 

void reset (void); 

unsigned char read(void); 

void lcd(unsigned char); 

void start (void) 

{ 

sda=l; 
delay (); 
scl=l; 
delay (); 
sda=0; 
delay (); 

} 



Microcontroller-based Measurement and Control Applications 135 



void stop (void) 

{ 

sda=0; 
delay (); 
scl=l; 
delay (); 
sda=l; 
delay (); 

} 

void delay (void) 

{ 

int i; 

for(i=0;i<30000;i++); 

for(i=0;i<200;i++); 

} 

void add(d) 

{ 

int i; 

for(i=0;i<8;i++) 

{ 

scl=0; 
delay (); 
sda=d>>7; 
scl=l; 
delay (); 
d=d«l; 

} 
scl=0; 

delay (); 

} 

int ack(void) 

{ 
scl=0; 

delay (); 

sda=l; 

delay (); 



136 Application 3: I 2 C Interface with Serial EPROM 

scl=l; 
delay (); 
return sda; 

} 

void reset (void) 

{ 

int i; 

for(i=0;i<9;i++) 

{ 
scl=0; 

delay (); 

scl=l; 

delay (); 

if(sda==l) 

break; 

} 
} 

unsigned char read (void) 

{ 

unsigned char var=0; 
int i; 

for(i=0;i<8;i++) 

{ 

scl=0; 
delay (); 

scl=l; 

var=var|sda; 
delay (); 
var=var<<l; 

} 
scl=0; 

delay (); 

return var; 

} 

void ini(void) 

{ 

RW=0; 
RS=0; 



Microcontroller-based Measurement and Control Applications 137 

P2=0x38; 
enable(); 

enable () 

enable() 

enable () 

P2=0x06; 

enable (); 

P2=0x0E; 

enable (); 

P2=0x01; 

enable(); 

RS=1; 

} 

void lcd(unsigned char dat) 

{ 

int hun, ten, unit; 
hun=dat/100; 

ten=((dat/10)%10); 
unit = dat % 10; 

hun=( hun +0x30); 

P2=hun; 

enable (); 

delay (); 

ten=ten+0x30; 

P2=ten; 

enable(); 

delay (); 

unit=unit+0x30; 

P2=unit; 

enable (); 

delay (); 

} 

void enable (void) 

{ 

EN=1; 
delay (); 
EN=0; 
delay (); 

} 



2 



138 Application 3: VC Interface with Serial EPROM 



void main(void) 

{ 

ini(); 
while(l) 

{ 

Pl=0x00; 

reset (); 
start (); 

add(OxAO); 
led=l; 
x=ack(); 
led = x; 
delay (); 
delay (); 

led=l; 

if ( x = =0) 

{ 
add(0x05); 

x=ack(); 

led = x; 

delay (); 

delay (); 

} 

led=l; 



start (); 
add(OxAl); 

dat=read(); 
lcd(dat); 
scl=l; 
sda=l; 

stop(); 

} 

} 

"^z *& "^z *& "^c "^z *& "^c "£? *& *& *& *& "^c *& "£? "^z *& *& "£? *& "^z *& *& "^c *& *& "^z *& "^c "^z *£c "^c "^z "^c "£? *& *& "^z *& "^c "^z *& *& "^z *& "^z "^z *& "^z *& "^c "^z *& 



Chapter 8 

Securing Your Embedded System Application 



8.1 Security Challenges in Embedded Systems 

The applications of embedded systems are growing in the areas such 
as cell phones, cars, spacecraft, biomedical sensitive, and defense. The 
main concern for deployment in these application sectors is security. 
Security has been the subject of intensive research in the context of 
general-purpose computing and communications systems. In computing 
and networking products there are established devices and algorithmic 
methodologies for ensuring the security of the code. The security con- 
cerns about the embedded systems are well covered in many references 
[38; 39; 40; 41; 42; 43]. Security is often misconstrued by embedded sys- 
tem designers as the addition of features such as specific cryptographic 
algorithms and security protocols to the system. In reality, it is a new 
dimension that designers should consider throughout the design process, 
along with other metrics such as cost, performance, and power. The chal- 
lenges unique to embedded systems require new approaches to security 
covering all aspects of embedded system design from architecture to 
implementation. Security processing, which refers to the computations 
that must be performed in a system for the purpose of security, can 
easily overwhelm the computational capabilities of processors in both 
low- and high-end embedded systems [38]. This challenge, which we 
refer to as the "security processing gap," is compounded by increases 
in the amounts of data manipulated and the data rates that need to 
be achieved [38]. Equally daunting is the "battery gap" in battery- 
powered embedded systems, which is caused by the disparity between 
rapidly increasing energy requirements for secure operation and slow 
improvements in battery technology. The final challenge is the "assur- 
ance gap," which relates to the gap between functional security measures 
(e.g., security services, protocols, and their constituent cryptographic 
algorithms) and actual secure implementations. 



139 

J.S. Parab et al. (eds.), Exploring C for Microcontrollers, 139-150. 
© 2007 Springer. 



140 Application 1: Authentication for Your Embedded System Application 

The case studies developed in this chapter specifically focus on the 
security aspects of the embedded systems. The first case study offers 
the security by checking the user's login ID and password just like a 
typical interface presented by multi-user OS. The second case study 
allows the user to let in provided he or she enters the password in a 
given time. While the third application illustrates the methodology of 
writing the routines in the same manner as that of computer BIOS, 
which has inherent code security. 

8.2 Application 1: Authentication 

for Your Embedded System Application 

The setup shown in Figure 8.1 is used for this application. The pro- 
gram prompts the user to enter his user ID by displaying a message 
"LOGIN" on the LCD. The user is expected to enter his ID using the 
PC keyboard. Then the program displays a message "password" on the 
LCD to prompt the user to enter the password. After entering the pass- 
word, the program will check whether the entered information is correct 
or not. 

The system can also be used for cabinet lock-up or for any keyboard- 
based security implementation. 

Program Source Code 

^include <REG52.H> /* special function register declarations */ 

/ * for the intended 8051 derivative */ 

^include <stdio.h> /* prototype declarations for I/O functions */ 

sbit RS = P2 A 0; 
sbit RW = P2 A 1; 
sbit EL = P2 A 2; 

void INITt (); 

void delay (int); 

void INIT(void); 

void ENABLE(void); 

void LINE(int); 

char array[]= "LOGIN:"; 

char pass[]="EMBEDED"; 

char Access[] = "CORRECT"; 

char denied[] = "WRONG"; 



Securing Your Embedded System Application 141 



void INITtQ // function to Initialize the timer 

{ 

TMOD=0x20; 
THl=0xFD; 
SCON=0x50; 
TR1=1; 

} 

void LINE (int i) // Enable the line function 

{ 

if (i==i) 

{ 

RS=0; 

RW=0; 

Pl=0x80; 

ENABLE(); 
RS=1; 

} 



else 



} 



{ 

RS=0; 
RW=0; 
Pl=0xC0; 

ENABLE(); 
RS=1; 

} 



void delay (int k) // invoking delay function 

{ 

int i,j; 

for (j=0;j<k+l;j++) 

{ 
for (i=0;i<10000;i++); 

} 
} 

void ENABLE (void) // invoking the enable function 

{ 

EL=1; 



142 Application 1: Authentication for Your Embedded System Application 

delay(l); 

EL=0; 

delay(l); 

} 



void INIT(void) 

{ 
RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLE(); 

ENABLEQ; 

ENABLEQ; 

ENABLEQ; 

PI = 0x06; 

ENABLE(); 

PI = OxOE; 

ENABLE(); 

PI = 0x01; 

ENABLE(); 

} 



initialization of LCD display 5 



void main (void) // main function 

{ 

char b,var; 
char *p; 
int i,j,k; 
while (1) 

{ 

INIT(); 

LINE (1); 

for (b=0;b<8;b++) 

{ 
p=&array; 

Pl= *p++; /* increment the pointer and point the 

data from the array 



ENABLE 
} 



Securing Your Embedded System Application 143 



{ 

INITt(); 

RI=0; 

var=SBUF; 

while(IBI); 

RI=0; 
while(l) 

{ 

for (i=0;i<8;i++) 

{ 

if((pass[i])==(var[i])) 

for(j=0;j<8;j++) 

{ 

LINE(l); 

p=&Access; 

Pl= *p+ + ; 

ENABLE(); 

} 

else 

{ 

LINE(l); 
p=&denied; 
Pl= *p++; 

ENABLE(); 
} 

RS=0; 
Pl=0x01; 
ENABLE(); 
RS=1; 

} 
} 
}}} 



144 



Application 2: Timeout Waiting for Input Data 



Authentication for your Embeded System Application 



DB 9 Connector 



10 nF 



LCD 
H D 44780 (16X2) 

DBO-DB7 Rs Rw En 



+5v 
33PF 

n — 

r% □ XTAL 

i T T 



11.0592 MHz 



r 



T 



Vcc PORT1 P 20 P.i 
XTAL1 



XTAL2 
GND 



Q_ 

s 

x 

01 



3 
x 



AT 89 S 52 



16 



15 14 



13 



12 



11 



10 



> o o 



X 



O 
CtL 



CM 



O 

CN 



MAX 232 



o > o 






O 



3 

c 

CN 



rr 



10 M F 



t 



10 M F 



"T 

+ VCC 



-f6 7 



Figure 8. 1 Setup for security authentication of embedded system 



8.3 



Application 2: Timeout Waiting for Input 
Data 



In this application, the security is implemented by allowing the user 
to enter 10 predetermined characters (password or secret word) in a 
predetermined time period. Thus this application ensures a tight secu- 
rity implementation as compared to the previous as the time clause is 
important. 



Securing Your Embedded System Application 



145 



+5V 



33PF 



^ 



12MHz [ ] XTAL 



33PF 



Vcc 



XTAL1 



XTAL2 



oo 



GND 



T 



p*. 



p,. 



p„ 
p»„ 



10K 

WSwV 



I w*V»V\ 

• IMWV 



+ 5V 



10K 



FN 



R/W 



RS 



D, 



Do 



HD 4478Q 
16X2 

LCD 



1K 



* KEY PAD 

4 X 4 
MATRIX 



+5V 



Buzzer 



BC547 



Figure 8.2 Schematic for the setup for timeout waiting 



It can also be used for normal data logging applications. While in- 
putting the data, if the data does not arrive after some allowed time, 
the wait is abandoned and some other action is taken. The request can 
be retransmitted or some error message is sent to the user. 

The program implemented here waits for the user to type 10 charac- 
ters. The timeout for the first character is 10 seconds, and then 2 seconds 
for each character thereafter. If the user does not respond within this 
time, a timeout message is displayed on LCD. 

Program Source Code 

*& *& "^£ *& "^£ *& "^l^ *& *& "^l^ "^l^ "^l^ "^l^ "^l^ "^l^ "^l^ "^l^ *& *& "^r£ "J^ *& "^l^ "^l^ *& "^l^ *& *& "^l^ "^£ "^£ *& "^£ *& *& *& "^£ "^£ "^£ *& *& "^r£ *& "^£ "^r£ *& *& "^l^ "^l^ *& "^l^ "^l^ *& "^l^ "^l^ "^l^ "^l^ "^l^ *& "^l^ "^l^ "^l^ 



#include <REG52.H> 

^include <stdio.h> 

/* for the intended 8051 derivative 



special function register declarations 



146 



Application 2: Timeout Waiting for Input Data 



sbit RS = 
sbit RW 
sbit EL : 
sbit BU 



P2 A 0; 

: P2 A 1; 

P2 A 2; 

P2 A 4; 



LCD control signals 



Buzzer 



sbit Rl 
sbit R2 
sbit R3 
sbit R4 



P0 A 
P0 A 1 
P0 A 2 
P0 A 3 



Keypad connection 4x4 matrix keyboard 



sbit CI 
sbit C2 
sbit C3 
sbit C4 



P0 A 4 
P0 A 5 
P0 A 6 
P0 A 7 



void delay (int); /* Stop Exection with Serial Intr. */ 

void INIT(void); 

void ENABLE (void); 

void LINE(int); 

int keyb(void); 

char getascii(int); // ASCII convertion to send data on LCD 



char getascii(int k) 
{ 

int ascii; 
if(k<10) 

ascii=k+0x30; 
if (k==10) 
ascii=0x30; 
return (ascii); 



} 



// Invoking the ASCII conversion function 



converts the data in to ASCII format 



Returns the ASCII value to the main 
routine 



void LINE (int i) 
I 



if (i==l 

{ 
RS=0; 



function for selecting the line to display 
the data on LCD 



Securing Your Embedded System Application 



147 



} 



RW=0; 
PI =0x80; 
ENABLE(); 
RS=1; 

} 

else 

{ 

RS=0; 

RW=0; 

Pl=OxCO; 

ENABLE(); 

RS=1; 

} 



void delay (int k) 

{ 

int i,j; 

for (j=0;j<k+l;j++) 

{ 

for (i=0;i<100;i++); 

}} 

void ENABLE (void) 

{ 
EL=1; 

delay(l); 

EL=0; 

delay(l); 

} 

void INIT(void) 



// Delay function 



{ 



RS=0; 

RW=0; 

EL=0; 

PI = 0x38; 

ENABLE() 

ENABLEQ 

ENABLEQ 

ENABLE () 



Invoking the function to enable the LCD 



Sequential commands for the LCD 
initialization 



148 



Application 2: Timeout Waiting for Input Data 



} 



PI = 0x06; 
ENABLE(); 
PI = OxOE; 
ENABLE(); 
PI = 0x01; 
ENABLEQ; 



int keyb(void) 

{ 

int key=0; 



Invoking the Keyboard scanning function 



Cl=l 
C2=l 
C3=l 
C4=l 

R1=0: 
R2=l 
R3=l 
R4=l 



if (CI: 

if (C2= 
if (C3= 

if (C4= 



=0) key 
0) key 
0) key 
=0) key 



1 

2: 
3: 
4: 



Rl=l 
R2=0: 
R3=l 
R4=l 



if (CI: 
if (C2: 

if (C3: 
if (C4: 



=0) key 
=0) key 
0) key 
=0) key 



5: 
6: 

7: 
8: 



Rl=l 
R2=l 
R3=0: 
R4=l 



Securing Your Embedded System Application 



149 



if (C1==0) key = 9; 
if (C2==0) key = 10 
if (C3==0) key = 11 
if (C4==0) key = 12 



Rl=l 
R2=l 
R3=l 
R4=0 



if (C1==0) key = 13 
if (C2==0) key = 14 
if (C3==0) key = 15 
if (C4==0) key = 16 
return (key); 

} 



void main (void) 

{ 

int j; 

char arr ay []= "Enter 10 characters"; 

char time out [] = "Request time out" ; 

INIT(); 

char *p; 

int k; 

while(l){ 

p=&array; 

for (k=0;k<17;k++) 

{ 

if (k==0) LINE(l); 

if (k==8) LINE(2); 

Pl= *p+ + ; 

ENABLE(); 

j = keyb(); 

Delay(lOOOO); //10 sec delay 

lf(j=0) // no key pressed 



Main function 



{ 

p=&time out; 

for (k=0;k<17;k++) 

{ 



150 



Application 2: Timeout Waiting for Input Data 



if (k==0) LINE(l); 
if (k==8) LINE(2); 
Pl= *p++; 

ENABLE(); 

} 

elseif{ 

for (i=0;i<9;i++) 

{ 
Pl=getascii(j); 

delay (2000); 

j = keyb(); 

if(j=0) 

{ p=&time out; 



//for remaining 9 characters delay is 2 sec 



2 sec 



if no character is received within 2 sec 
then flash "request time out on LCD screen 
for (k=0;k<17;k++) 

{ 

if (k==0) LINE(l); 

if (k==8) LINE(2); 
Pl= *p++; 

} 
ENABLEi 



} 
}} 






References 



1. http://en.wikipedia.org/wiki/Microcontroller from Wikipedia, the 
free encyclopedia 

2. http://www.webopedia.eom/TERM/M/microcontroller.html 

3. http://www.definethat.com/define/1727.htm 

4. http://www.pcmag.com/encyclopedia_term/0,2542,t=microcontrol- 
ler&i=46924,00.asp 

5. http://foldoc.org/7microcontroller 

6. Report on World Microcontrollers Market by Frost & Sullivan 
research service, published on 30 December 2005 

7. http://www.intel4004.com/busicom.htm A testimonial from 
Federico Faggin, its designer, on the first microprocessor's thirtieth 
birthday 

8. http://www3.sk.sympatico.ca/jbayko/cpul.html Section One: 
Before the Great Dark Cloud 

9. http://www.cpushack.net/Historyofthe8051.html The Unofficial 
History of 8051 by Jan Waclawek (wek at efton.sk) edited by John 
Culver 

10. World Microcontrollers Market F591-26, Agency /Source: Frost & 
Sullivan http://www.newswiretoday.com/news/7122/) 

11. Applications for Efficiency: The Green Story, www.freescale.com 

12. The 8-bit microcontroller- A hit product that supports digi- 
tal still cameras (DSCs) from behind the scenes 8-bit micro- 
controllers and the important role they play inside digital 
cameras, Vol. 24 (14 September 2004) http://www.necel.com/ 
en/channel/vol_0024/vol_0024_2.html#chapterl) 



151 



152 References 

13. http://www.bourneresearch.com/: Bourne Research is a trusted 
source of market intelligence, with a specialized focus on MEMS 
(MicroElectroMechanical Systems), Nanotechnology, and the con- 
vergence of both. 

14. SI A Raises Chip Sales Forecast, Written by Steven Waller, 
Wednesday, 07 June 2006 http://e-and-f. com/index. php?option= 
com_content&task=view&id=40&Itemid=2 

15. http://www.cs.ucr.edu/content/esd/slide_index.html 

16. http://www.industrialnewsroom.com/fullstory/26253 Cygnal 
Releases World's Highest Performance 8051 Microcontroller 

17. http://www.xemics.com/ or http://www.semtech.com/products/ 
wireless&sensing/trans/xemic.jsp XE8000 Application Specific 
Microcontrollers series 

18. http://www.eeproductcenter.com/micro/brief/showArticle.jhtml? 
articleID= 196700958 Microcontrollers integrate power-saving 
technology, Gina Roos, eeProductCenter, 12/19/2006 

19. http://www.microcontroller.com Microcontrollers and DSPs - Will 
They Converge? by Bill Giovino 

20. http://www.edn. com/index. asp?layout=article&stt=000&articleid= 
CA333669&pubdate=ll%2F13%2F2003: Microcontrollers gain 
DSP attributes in "hybrid" architecture By Graham Prophet 
EDN Europe, 11/13/2003 

21. http://www.omimo.be/magazine/99q2/Hitachi.pdf The RISC 
Challenge in DSP Processing by Dr. Manfred Schlett 

22. http://www.mcjournal.com/articles/arcl01/arcl01.htm Real-Time 
Debugging Highly Integrated Embedded Wireless Devices, by David 
Ruimy Gonzales and Brian Branson 

23. http://www.keil.com/dd/chip/3469.htm Silicon Laboratories, Inc. 
C8051F120 

24. www.futurlec.com/News/Dallas/InternetIC.html New Microcon- 
troller is web-enabled Dallas Semiconductor Re-Engineers, Its 
Microcontrollers for Network Computing 

25. http://www.aldec.com/products/ipcores/ IP cores by Aldec Inc. 

26. http://blogs.zdnet.com/emergingtech/wp-mobile.php?p=227&more 
= 1 Emerging Technology Trends 



References 153 

27. http:// www. embedded. com/showArticle.jhtml?articleID=194300451 
Tutorial: Improving the transient immunity of your microcontroller- 
based embedded design Part 1 Defining the problem: A step 
by step tutorial on EMI, ESD, and EFT problems in embedded 
designs and a range of possible solutions. By Ross Carlton, Freescale 
Semiconductor, Inc 

28. http://www.keil.com/support/man_c51.htm On Line Manual of Keil 
for C51 products 

29. "Choosing a Microcontroller for Embedded System Applica- 
tions", Mel Tsai http://www.egr.msu.edu/classes/ece482/Reports/ 
appnotes/98spr/tsaimelv/appnote.html 

30. Application Note: Choosing a Microcontroller for Embedded Sys- 
tems Applications Mel Tsai http://www.mtsai.net/documents/ 
appnote/appnote.html 

31. http://www.airborn.com.au/8051/2wio8051.html 2 Wire Input/ 
Output for 8051 type CPU's 

32. www.8052.com/users/garypeek/ : "I/O EXPANSION ROUTINES 
FOR 8051 FAMILY MICROCONTROLLERS; WRITTEN BY 
GARY" 

33. On the verge: LEDs ready to challenge incumbent light sources in 
the street lighting market: Tim Whitaker http://ledsmagazine.com/ 
articles/features/3/ 10/4/1: LED's magazine 

34. Microcontrollers provide connectivity of HB-LED lighting prod- 
ucts: Dugald Campbell http://www.ledsmagazine.com/articles/ 
features/2/11/1/1 LEDs Magazine 

35. http://www.alldatasheet.co.kr/datasheet-pdf/pdf_kor/STMICROE- 
LECTRONICS/ULN2003.html Data sheet of ULN2003 

36. www.aurel32.net/elec/pcf8583.pdf Data-sheet of PCFR8583 

37. http : // www . atmel . com/dyn/products/product_card . asp?part_id= 
2806 Data-sheet of AT24C04 

38. Security in embedded systems: Design challenges, Srivaths Ravi, 
Anand Raghunathan, Paul Kocher, Sunil Hattangady, ACM Trans- 
actions on Embedded Computing Systems (TECS) archive, Vol- 
ume 3, Issue 3 (August 2004) table of contents, pp. 461-491, 2004, 
ISSN:1539-9087 



154 References 

39. Ross J. Anderson, Markus G. Kuhn, Low-Cost Attacks on Tamper 
Resistant Devices, Proceedings of the 5th International Workshop 
on Security Protocols, p. 125-136, April 07-09, 1997 

40. W. A. Arbaugh, D. J. Farber, J. M. Smith, A secure and reliable 
bootstrap architecture, Proceedings of the 1997 IEEE Symposium 
on Security and Privacy, p. 65, May 04-07, 1997 

41. Matt Blaze, A cryptographic file system for UNIX, Proceedings of 
the 1st ACM Conference on Computer and Communications Secu- 
rity, pp. 9-16, 3-5 November 1993, Fairfax, Virginia, USA 

42. D. Boneh, R. DeMillo, and R. Lipton, 2001. On the importance of 
eliminating errors in cryptographic computations. Cryptology 14(2): 
101-119 

43. Jerome Burke, John McDonald, Todd Austin, Architectural sup- 
port for fast symmetric-key cryptography, Proceedings of the 9th 
International Conference on Architectural Support for Programming 
Languages and Operating Systems, pp. 178-189, November 2000, 
Cambridge, Massachusetts, USA 



Index 



2N2222, 127 

A 

A to D converter, 7, 48, 57 
ADC0808, 100 
ADC7135, 127 

Adding your program source code, 24-25 
Anonymous voting, 114-118 
APIs, 14 

Architectural trend, 10-14 
Art of C programming for microcon- 
trollers, 29-34 
ASCII, 66, 113, 146 
Assurance gap, 139 
AT2404, 134 
AT89C2051, 30, 52 
AT89C51, 30, 52 



B 



Basic C program structure, 34 
Baud rate, 17, 63, 69 
Bicolour LED, 51 
Blinking LED, 48 
Buzzer, 58, 91, 104, 114 



Conventional C, 20-21 
Convergence of DSP with micro, 12 
Copying startup code to your project, 

22, 24 
Corridor, 120 
Counting cars, 110-114 



D 



Darlington driver, 74 

Development flow for the Keil IDE, 

21-26 
Differences from ANSI C, 34 
DIP switch, 52-53 
Dominance of soft IP cores, 14 
DSP, 2-3, 12 
Dumping the code in microcontroller's 

on-chip memory, 28 



E 



Energy consumption, 13, 16, 48 
Energy efficient lighting, 119 
Estimating interrupt latency, 63-67 
Ethernet, 14, 71 



C 



Cafeteria Food Alert, 94-100 
Chimney sentinel, 100-104 
COM port, 69 
Common anode, 47 
Communication systems, 8 
Comparison of the packages, 38 
Compiler capabilities, 29 
Compiling the program, 27 
Configuring ports as input, 42-43 



Fading RGB LED, 52 
FOR construct, 44 
Freescale semiconductor, 9, 119 
Front desk notifier, 90-94 



G 



Getting familiar with the IDE, 19 
Growth economics, 7 



155 



156 



Index 



H 



Hardware and software issues, 17 
Header files, 30 
Hidden debugger, 12-13 
Hitachi 44780, 54 
Home automation, 78 
Hyperterminal based control, 69-78 



I2C bus, 46 

Incandescent light bulb, 119 

Increment /decrement operator, 43 

Interfaces offered by Keil IDE, 21 

Interrupt 4, 58 

Interrupt latency, 63-67 

Interrupts, 57 

IR LED, 120 

ISRs, 58 



JTAG interface, 13 



K 



Keil IDE, 20-21 

Keil types, 35 

Keil variable extensions, 36 

Keyboard, 57, 85, 140 



Minutes counter, 60-63 
MOC3030, 80 
Multiuser OS, 140 

O 

OFF time, 123 

ON time, 123 

Opening a new project, 22 

Optoisolator, 80 



Packet based control, 69 

Password, 140 

PCF8583, 134 

Phototransistor, 120 

Pico power microcontrollers, 11 

Podium timer, 85-90 

Ports, 37 

Power consumption, 11, 119 

PPI8255, 46 

Program the microcontroller, 28 

Protocol, 5, 69, 78, 133 

PWM, 123 



R 



RS232C, 70 
RTC, 134 
Running LED, 51 



LCD, 54-57 

LED, 46-52 

LED dimmer demoboard, 51 

LED moving font, 52 

Lightening industry, 48 

LM35, 100, 127 

LOGIN, 140 

Low power design, 11 

M 

Market trend, 8 

MAX232, 70 

MCU turf, 10 

Microcontroller, 1 

Microcontroller applications, 5-7 

Microcontroller based menu card, 94-95 



Scrolling LED, 49-50 

Security challenges, 139 

Selecting a device for the target, 22 

Serial EPROM, 133-138 

Seven segment LED, 60 

Shift register, 46 

Shifting, 45-46 

Simulated mode, 27 

Simulated port testing, 37 

Single set point, 127 

Software delay loop, 43 

Special Function Register, 35, 38, 42 

Square wave, 41 

Standard types, 35 

Stepper motor control, 74-78 

Street light, 48 



Index 



157 



w 



Thermistor, 123 
Timeout waiting, 144 

V 

Variable types, 34 
Von-Neumann architecture, 10 



Web enabled microcontrollers, 13-14 
Who's first timer, 104 
Working with Keil IDE, 20 



X 



X10, 78