You are on page 1of 166

SIX WEEKS INDUSTRIAL TRAINING

TRAINING REPORT
AT

“EON INFOTECH”
1
IN
“EMBEDDED SYSTEMS”

ON

2
“Automatic Room Counter ”

3
Submitted By:
Name: Sukanya Deka
College Roll No.:2908215
University Roll No.:

4
5
ACKNOWLEDGMENT

Industrial training indisputably plays the most important role in an engineering


student’s life to make him a successful engineer. It provides the student with an
opportunity to gain valuable experience on the practical application of their technical
knowledge.
6
I express my gratitude to all the people at Eon infotech Limited who helped me gain
the valuable knowledge and experience. I have no doubt now that my choice of
training at eon infotech was right. The exposure and experience gained at eon has
been unique. The eon family teaches strict self-discipline and a goal oriented
approach.

7
I would like to thank my honorable guide at techno school, Mr.Rohit Gupta for
getting me acquainted with the work ethics of the organization and motivating me at
each and every step so that I achieve my goals here with perfection.

I would also like to thank all the staff members of techno school who have
encouraged and inspired me in achieving higher goals.

8
9
10
INTRODUCTION TO COMPANY

11
“We envision ourselves in the leadership position in providing embedded product-
realisation solutions in India by 2008”.

OUR VISION EXPLAINED:


As we use this term, leadership means more revenue, more profit, more innovation that serves

12
our customer’s needs, and a more attractive place to work than any competitor. Achieving this
ambitious objective will require that we double our revenue and profit every year for the next
two years, and then double them every two years thereafter. It will require that we become less
India oriented, more externally focused, have a mix of products and services, and continue to
maintain a special focus on the wireless communications domain, which is our core competence.
It will require us to deliver, time and again, world class solutions at Indian prices. The business
will be sufficiently de-risked through a judicious customer spread and a component of revenue
coming through projects with predictable cash flows. We sincerely believe that if we work

13
together, we can create this change and in the process create a firm that will be admired by our
stockholders, customers, employees, and the community.”

14
THE EON STRATEGY

The story of Eon is the story of an organization that is succeeding in the marketplace by living
the Five Pillars of its STRATEGY in all its engagements

At Eon Infotech Limited, we have only one raison d’etre – “To Make Our Customer’s Vision
Possible”. Putting ourselves in our customer’s shoes, we seek first to understand her needs, and
then work closely with her to deliver technology solutions that satisfy those needs. This single-
minded focus has helped us succeed in the marketplace consistently. At Eon, we have placed the
15
customer at the centre of our mission statement. Every morning, all we do is to just go out and
live our mission statement.

2. Speed
We realize that speed is one of the key values we can bring to our customers. We are a young,
nimble-footed team that can deliver you solutions much faster than bigger players. Our typical
delivery times are 40% lesser than any other organization in our domain. In a world where speed
is the one of the most critical determinants of success, this is no mean value to our customers

16
3. R&D
Research and Development is our lifeline, and gives us the competitive advantage in this fiercely
contested marketplace. 10% of our budget goes into Research and Development every year.
Some of the finest engineering brains within Eon are currently working on technologies of
tomorrow.

4. Quality Practices, Standards and Management

17
Quality is a way of life at Eon. The trinity of Quality Standards, Quality Practices and Quality
Management guides us in all our engagements. We are a systems driven, ISO 9001:2000
Organization.

5. Prices
A lean Indian Company, we bring you World-Class solutions at, naturally, Indian prices.

18
EMBEDDED SOFTWARE DEVELOPMENT
19
Eon has successfully delivered a number of embedded software solutions to its
clients. Some of the projects executed by Eon in this domain are:
*Radio Telephony integration projects
*Remote control applications
*Applications including GIS/GPS interface with real time
Systems
*Legacy Interface development
*Test and Measurement equipment control applications over

20
*HPIB/IEEE488.2 interface
*Data Encryption techniques

PRODUCTS

21
Eon has supplied embedded and application software products to defence forces
and law enforcement agencies, and developed fail-safe railway safety systems
using embedded technologies. The defence systems group has a focus on the law
enforcement market. Besides current products, this group identifies new
opportunities by interacting closely with the end user and by understanding their
needs. The defence system group was started in march 2000 and today contributes
significantly to total revenue.

Recent major breakthrough products launched by EON are:

22
Force Multiplier Command Post ( FMCP )
FMCP is the most advanced situation awareness
and battlefield management systems to be fielded
in the world. FMCP provides state-of-the-art
command and control through common core
software and varying user interfaces which allow
it to be employed at every level from individual
vehicles and personnel to formation headquarters.

23
Radio - Telephony Integration ( EP-100 )
A radio telephone interface, which allows the
wireless users to access their telephone line while
on the move. This is available in half duplex as
well as full duplex versions.

24
Automatic Vehicle Location System
( POLMATE )
A satellite based automatic vehicle location, fleet
management and emergency response system.
POLMATE uses clients' already existing two-way
radios for communication .

25
Personnel Locator System ( SEARCHMATE )
A GPS based personnel locator system to search
and rescue skiers trapped in an avalanche. This
included developing a personnel kit (a wearable
micro) which all the members carry. The system is
compatible with most VHF/UHF radios from
various manufacturers.

26
Intelligent Electronic Fence System
( SMARTFENCE )
Highly scaleable PC based intelligent electronic
fence system for equipping new or existing fences
with the capability to detect, locate and classify
intruders. Solution particularly appropriate for use
in large fenced areas, for example, national
borders, around airports, military bases, or
embassies .

27
28
Wireless Data Communication System
( SYSCOM600 ) Syscom600 System is designed
to provide data capability to HF and VHF stations
located in difficult terrain. This system has the
capability to receive and send digital information
over HF/VHF/UHF radios, thus allowing users to
use computers to carry on real time online chat
between stations, send and receive Image files as
well as text files. The entire communication is

29
encrypted with an encryption algorithm
"Agamya", which is a 576 bit Indian encryption
algorithm.

30
EMBEDDED SYSTEM
An embedded system is a computer system
designed to perform one or a few dedicated
31
functions. often with real-time computing constraints. It is embedded as part of a complete device
often including hardware and mechanical parts. By contrast, a general-purpose computer, such as
a personal computer (PC), is designed to be flexible and to meet a wide range of end-user needs.
Embedded systems control many devices in common use today.

Embedded systems are controlled by one or more main processing cores that are typically either
microcontrollers or digital signal processors (DSP). The key characteristic, however, is being
dedicated to handle a particular task, which may require very powerful processors. For example,
air traffic control systems may usefully be viewed as embedded, even though they involve

32
mainframe computers and dedicated regional and national networks between airports and radar
sites. (Each radar probably includes one or more embedded systems of its own.)

Since the embedded system is dedicated to specific tasks, design engineers can optimize it to
reduce the size and cost of the product and increase the reliability and performance. Some
embedded systems are mass-produced, benefiting from economies of scale.

Physically, embedded systems range from portable devices such as digital watches and MP3
players, to large stationary installations like traffic lights, factory controllers, or the systems

33
controlling nuclear power plants. Complexity varies from low, with a single microcontroller
chip, to very high with multiple units, peripherals and networks mounted inside a large chassis or
enclosure.

In general, "embedded system" is not a strictly definable term, as most systems have some
element of extensibility or programmability. For example, handheld computers share some
elements with embedded systems such as the operating systems and microprocessors which
power them, but they allow different applications to be loaded and peripherals to be connected.
Moreover, even systems which don't expose programmability as a primary feature generally need

34
to support software updates. On a continuum from "general purpose" to "embedded", large
application systems will have subcomponents at most points even if the system as a whole is
"designed to perform one or a few dedicated functions", and is thus appropriate to call
"embedded".

35
VARIETY OF EMBEDDED SYSTEMS

Embedded systems span all aspects of modern life and there are many examples of their use.

36
Telecommunications systems employ numerous embedded systems from telephone switches for
the network to mobile phones at the end-user. Computer networking uses dedicated routers and
network bridges to route data.

Consumer electronics include personal digital assistants (PDAs), mp3 players, mobile phones,
videogame consoles, digital cameras, DVD players, GPS receivers, and printers. Many
household appliances, such as microwave ovens, washing machines and dishwashers, are
including embedded systems to provide flexibility, efficiency and features. Advanced HVAC
systems use networked thermostats to more accurately and efficiently control temperature that

37
can change by time of day and season. Home automation uses wired- and wireless-networking
that can be used to control lights, climate, security, audio/visual, surveillance, etc., all of which
use embedded devices for sensing and controlling.

Transportation systems from flight to automobiles increasingly use embedded systems. New
airplanes contain advanced avionics such as inertial guidance systems and GPS receivers that
also have considerable safety requirements. Various electric motors — brushless DC motors,
induction motors and DC motors — are using electric/electronic motor controllers. Automobiles,
electric vehicles, and hybrid vehicles are increasingly using embedded systems to maximize

38
efficiency and reduce pollution. Other automotive safety systems include anti-lock braking
system (ABS), Electronic Stability Control (ESC/ESP), traction control (TCS) and automatic
four-wheel drive.

Medical equipment is continuing to advance with more embedded systems for vital signs
monitoring, electronic stethoscopes for amplifying sounds, and various medical imaging (PET,
SPECT, CT, MRI) for non-invasive internal inspections.

39
In addition to commonly described embedded systems based on small computers, a new class of
miniature wireless devices called motes are quickly gaining popularity as the field of wireless
sensor networking rises. Wireless sensor networking, WSN, makes use of miniaturization made
possible by advanced IC design to couple full wireless subsystems to sophisticated sensors,
enabling people and companies to measure a myriad of things in the physical world and act on
this information through IT monitoring and control systems. These motes are completely self
contained, and will typically run off a battery source for many years before the batteries need to
be changed or charged.

40
HISTORY

41
In the earliest years of computers in the 1930–40s, computers were sometimes dedicated to a
single task, but were far too large and expensive for most kinds of tasks performed by embedded
computers of today. Over time however, the concept of programmable controllers evolved from
traditional electromechanical sequencers, via solid state devices, to the use of computer
technology.

One of the first recognizably modern embedded systems was the Apollo Guidance Computer,
developed by Charles Stark Draper at the MIT Instrumentation Laboratory. At the project's
inception, the Apollo guidance computer was considered the riskiest item in the Apollo project

42
as it employed the then newly developed monolithic integrated circuits to reduce the size and
weight. An early mass-produced embedded system was the Autonetics D-17 guidance computer
for the Minuteman missile, released in 1961. It was built from transistor logic and had a hard
disk for main memory. When the Minuteman II went into production in 1966, the D-17 was
replaced with a new computer that was the first high-volume use of integrated circuits. This
program alone reduced prices on quad nand gate ICs from $1000/each to $3/each[citation needed],
permitting their use in commercial products.

43
Since these early applications in the 1960s, embedded systems have come down in price and
there has been a dramatic rise in processing power and functionality. The first microprocessor for
example, the Intel 4004, was designed for calculators and other small systems but still required
many external memory and support chips. In 1978 National Engineering Manufacturers
Association released a "standard" for programmable microcontrollers, including almost any
computer-based controllers, such as single board computers, numerical, and event-based
controllers.

44
As the cost of microprocessors and microcontrollers fell it became feasible to replace expensive
knob-based analog components such as potentiometers and variable capacitors with up/down
buttons or knobs read out by a microprocessor even in some consumer products. By the mid-
1980s, most of the common previously external system components had been integrated into the
same chip as the processor and this modern form of the microcontroller allowed an even more
widespread use, which by the end of the decade were the norm rather than the exception for
almost all electronics devices.

45
The integration of microcontrollers has further increased the applications for which embedded
systems are used into areas where traditionally a computer would not have been considered. A
general purpose and comparatively low-cost microcontroller may often be programmed to fulfill
the same role as a large number of separate components. Although in this context an embedded
system is usually more complex than a traditional solution, most of the complexity is contained
within the microcontroller itself. Very few additional components may be needed and most of
the design effort is in the software. The intangible nature of software makes it much easier to
prototype and test new revisions compared with the design and construction of a new circuit not
using an embedded processor.

46
CHARACTERISTICS

1. Embedded systems are designed to do some


specific task, rather than be a general-purpose
computer for multiple tasks. Some also have real-
time performance constraints that must be met, for

47
reasons such as safety and usability; others may have low or no performance
requirements, allowing the system hardware to be simplified to reduce costs.
2. Embedded systems are not always standalone devices. Many embedded systems consist
of small, computerized parts within a larger device that serves a more general purpose.
For example, the Gibson Robot Guitar features an embedded system for tuning the
strings, but the overall purpose of the Robot Guitar is, of course, to play music. [5]
Similarly, an embedded system in an automobile provides a specific function as a
subsystem of the car itself.

48
3. The program instructions written for embedded systems are referred to as firmware, and
are stored in read-only memory or Flash memory chips. They run with limited computer
hardware resources: little memory, small or non-existent keyboard and/or screen.

The Fundamentals of Design of an Embedded System

49
50
51
THE C PROGRAMMING LANGUAGE
C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at
the Bell Telephone Laboratories for use with the Unix operating system.

Although C was designed for implementing system software, it is also widely used for
developing portable application software.

52
C is one of the most popular programming languages and there are very few computer
architectures for which a C compiler does not exist. C has greatly influenced many other popular
programming languages, most notably C++, which originally began as an extension to C.

DESIGN:

C is an imperative (procedural) systems implementation language. It was designed to be


compiled using a relatively straightforward compiler, to provide low-level access to memory, to
provide language constructs that map efficiently to machine instructions, and to require minimal
53
run-time support. C was therefore useful for many applications that had formerly been coded in
assembly language.

Despite its low-level capabilities, the language was designed to encourage machine-independent
programming. A standards-compliant and portably written C program can be compiled for a very
wide variety of computer platforms and operating systems with little or no change to its source
code. The language has become available on a very wide range of platforms, from embedded
microcontrollers to supercomputers.

54
CHARACTERISTICS:

Like most imperative languages in the ALGOL tradition, C has facilities for structured
programming and allows lexical variable scope and recursion, while a static type system prevents
many unintended operations. In C, all executable code is contained within functions. Function
parameters are always passed by value. Pass-by-reference is simulated in C by explicitly passing
pointer values. Heterogeneous aggregate data types (struct) allow related data elements to be
combined and manipulated as a unit. C program source text is free-format, using the semicolon
as a statement terminator (not a delimiter).
55
C also exhibits the following more specific characteristics:

• variables may be hidden in nested blocks


• partially weak typing; for instance, characters can be used as integers
• low-level access to computer memory by converting machine addresses to typed pointers
• function and data pointers supporting ad hoc run-time polymorphism
• array indexing as a secondary notion, defined in terms of pointer arithmetic
• a preprocessor for macro definition, source code file inclusion, and conditional
compilation.

56
• complex functionality such as I/O, string manipulation, and mathematical functions
consistently delegated to library routines
• A relatively small set of reserved keywords
• A lexical structure that resembles B more than ALGOL, for example:
o { ... } rather than either of ALGOL 60's begin ... end or ALGOL 68's
( ... )
o = is used for assignment (copying), like Fortran, rather than ALGOL's :=
o == is used to test for equality (rather than .EQ. in Fortran, or = in BASIC and
ALGOL)

57
o Logical "and" and "or" are represented with && and || in place of ALGOL's ∧
and ∨ operators; note that the doubled-up operators will never evaluate the right
operand if the result can be determined from the left alone (this is called short-
circuit evaluation), and are semantically distinct from the bit-wise operators & and
|
 However Unix Version 6 & 7 versions of C used ALGOL's /\ and \/
operators (in ASCII), but for determining the infimum and supremum
respectively.[1]

58
o a large number of compound operators, such as +=, -=, *= and ++ etc. (Equivalent
to the ALGOL 68 operators +:=, -:=, *:= and +:=1 )

USES-

C's primary use is for "system programming", including implementing operating systems and
embedded system applications, due to a combination of desirable characteristics such as code
portability and efficiency, ability to access specific hardware addresses, ability to "pun" types to
59
match externally imposed data access requirements, and low runtime demand on system
resources. C can also be used for website programming using CGI as a "gateway" for
information between the Web application, the server, and the browser. Some factors to choose C
over Interpreted languages are its speed, stability and less susceptibility to changes in operating
environments due to its compiled nature.

One consequence of C's wide acceptance and efficiency is that compilers, libraries, and
interpreters of other programming languages are often implemented in C.

60
C is sometimes used as an intermediate language by implementations of other languages. This
approach may be used for portability or convenience; by using C as an intermediate language, it
is not necessary to develop machine-specific code generators. Some compilers which use C this
way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and Vala. However, C was
designed as a programming language, not as a compiler target language, and is thus less than
ideal for use as an intermediate language. This has led to development of C-based intermediate
languages such as C--.

61
C has also been widely used to implement end-user applications, but as applications became
larger, much of that development shifted to other languages.

SYNTAX:

Unlike languages such as FORTRAN 77, C source code is free-form which allows arbitrary use
of whitespace to format code, rather than column-based or text-line-based restrictions.
Comments may appear either between the delimiters /* and */, or (in C99) following // until
the end of the line.

62
Each source file contains declarations and function definitions. Function definitions, in turn,
contain declarations and statements. Declarations either define new types using keywords such
as struct, union, and enum, or assign types to and perhaps reserve storage for new variables,
usually by writing the type followed by the variable name. Keywords such as char and int
specify built-in types. Sections of code are enclosed in braces ({ and }, sometimes called "curly
brackets") to limit the scope of declarations and to act as a single statement for control structures.

As an imperative language, C uses statements to specify actions. The most common statement is
an expression statement, consisting of an expression to be evaluated, followed by a semicolon; as

63
a side effect of the evaluation, functions may be called and variables may be assigned new
values. To modify the normal sequential execution of statements, C provides several control-
flow statements identified by reserved keywords. Structured programming is supported by if(-
else) conditional execution and by do-while, while, and for iterative execution (looping). The
for statement has separate initialization, testing, and reinitialization expressions, any or all of
which can be omitted. break and continue can be used to leave the innermost enclosing loop
statement or skip to its reinitialization. There is also a non-structured goto statement which
branches directly to the designated label within the function. switch selects a case to be
executed based on the value of an integer expression.

64
Expressions can use a variety of built-in operators (see below) and may contain function calls.
The order in which arguments to functions and operands to most operators are evaluated is
unspecified. The evaluations may even be interleaved. However, all side effects (including
storage to variables) will occur before the next "sequence point"; sequence points include the end
of each expression statement, and the entry to and return from each function call. Sequence
points also occur during evaluation of expressions containing certain operators( &&, ||, ?: and the
comma operator). This permits a high degree of object code optimization by the compiler, but
requires C programmers to take more care to obtain reliable results than is needed for other
programming languages.

65
Although mimicked by many languages because of its widespread familiarity, C's syntax has
often been criticized. For example, Kernighan and Ritchie say in the Introduction of The C
Programming Language, "C, like any other language, has its blemishes. Some of the operators
have the wrong precedence; some parts of the syntax could be better."

Some specific problems worth noting are:

66
• Not checking number and types of arguments when the function declaration has an empty
parameter list. (This provides backward compatibility with K&R C, which lacked
prototypes.)
• Some questionable choices of operator precedence, as mentioned by Kernighan and
Ritchie above, such as == binding more tightly than & and | in expressions like x & 1 ==
0.
• The use of the = operator, used in mathematics for equality, to indicate assignment,
following the precedent of Fortran, PL/I, and BASIC, but unlike ALGOL and its

67
derivatives. Ritchie made this syntax design decision consciously, based primarily on the
argument that assignment occurs more often than comparison.
• Similarity of the assignment and equality operators (= and ==), making it easy to
accidentally substitute one for the other. In many cases, each may be used in the context
of the other without a compilation error (although some compilers produce warnings).
For example, the conditional expression in if (a=b) is only true if a is not zero after the
assignment.

68
• A lack of infix operators for complex objects, particularly for string operations, making
programs which rely heavily on these operations (implemented as functions instead)
somewhat difficult to read.
• A declaration syntax that some find unintuitive, particularly for function pointers.
(Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration
reflects use".)

OPERATORS:

69
C supports a rich set of operators, which are symbols used within an expression to specify the
manipulations to be performed while evaluating that expression. C has operators for:

• arithmetic (+, -, *, /, %)
• equality testing (==, !=)
• order relations (<, <=, >, >=)
• boolean logic (!, &&, ||)
• bitwise logic (~, &, |, ^)
• bitwise shifts (<<, >>)

70
• assignment (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=)
• increment and decrement (++, --)
• reference and dereference (&, *, [ ])
• conditional evaluation (? :)
• member selection (., ->)
• type conversion (( ))
• object size (sizeof)
• function argument collection (( ))
• sequencing (,)
71
• subexpression grouping (( ))

“HELLO,WORLD” EXAMPLE:

The "hello, world" example which appeared in the first edition of K&R has become the model
for an introductory program in most programming textbooks, regardless of programming
language. The program prints "hello, world" to the standard output, which is usually a terminal
or screen display.

72
The original version was:

main()
{
printf("hello, world\n");
}

A standard-conforming "hello, world" program is:

#include <stdio.h>

73
int main(void)
{
printf("hello, world\n");
return 0;
}

The first line of the program contains a preprocessing directive, indicated by #include. This
causes the preprocessor—the first tool to examine source code as it is compiled—to substitute
the line with the entire text of the stdio.h standard header, which contains declarations for

74
standard input and output functions such as printf. The angle brackets surrounding stdio.h
indicate that stdio.h is located using a search strategy that prefers standard headers to other
headers having the same name. Double quotes may also be used to include local or project-
specific header files.

The next line indicates that a function named main is being defined. The main function serves a
special purpose in C programs: The run-time environment calls the main function to begin
program execution. The type specifier int indicates that the return value, the value that is
returned to the invoker (in this case the run-time environment) as a result of evaluating the main

75
function, is an integer. The keyword void as a parameter list indicates that the main function
takes no arguments.

The opening curly brace indicates the beginning of the definition of the main function.

The next line calls (diverts execution to) a function named printf, which was declared in
stdio.h and is supplied from a system library. In this call, the printf function is passed
(provided with) a single argument, the address of the first character in the string literal "hello,
world\n". The string literal is an unnamed array with elements of type char, set up

76
automatically by the compiler with a final 0-valued character to mark the end of the array
(printf needs to know this). The \n is an escape sequence that C translates to a newline
character, which on output signifies the end of the current line. The return value of the printf
function is of type int, but it is silently discarded since it is not used. (A more careful program
might test the return value to determine whether or not the printf function succeeded.) The
semicolon ; terminates the statement.

77
The return statement terminates the execution of the main function and causes it to return the
integer value 0, which is interpreted by the run-time system as an exit code indicating successful
execution.

The closing curly brace indicates the end of the code for the main function.

DATA STRUCTURES:

78
C has a static weak typing type system that shares some similarities with that of other ALGOL
descendants such as Pascal. There are built-in types for integers of various sizes, both signed and
unsigned, floating-point numbers, characters, and enumerated types (enum). C99 added a boolean
datatype. There are also derived types including arrays, pointers, records (struct), and untagged
unions (union).

C is often used in low-level systems programming where escapes from the type system may be
necessary. The compiler attempts to ensure type correctness of most expressions, but the
programmer can override the checks in various ways, either by using a type cast to explicitly

79
convert a value from one type to another, or by using pointers or unions to reinterpret the
underlying bits of a value in some other way.

Pointers

C supports the use of pointers, a very simple type of reference that records, in effect, the address
or location of an object or function in memory. Pointers can be dereferenced to access data
stored at the address pointed to, or to invoke a pointed-to function. Pointers can be manipulated
using assignment and also pointer arithmetic. The run-time representation of a pointer value is

80
typically a raw memory address (perhaps augmented by an offset-within-word field), but since a
pointer's type includes the type of the thing pointed to, expressions including pointers can be
type-checked at compile time. Pointer arithmetic is automatically scaled by the size of the
pointed-to data type. (See Array-pointer interchangeability below.) Pointers are used for many
different purposes in C. Text strings are commonly manipulated using pointers into arrays of
characters. Dynamic memory allocation, which is described below, is performed using pointers.
Many data types, such as trees, are commonly implemented as dynamically allocated struct
objects linked together using pointers. Pointers to functions are useful for callbacks from event
handlers.

81
A null pointer is a pointer value that points to no valid location (it is often represented by address
zero). Dereferencing a null pointer is therefore meaningless, typically resulting in a run-time
error. Null pointers are useful for indicating special cases such as no next pointer in the final
node of a linked list, or as an error indication from functions returning pointers.

Void pointers (void *) point to objects of unknown type, and can therefore be used as "generic"
data pointers. Since the size and type of the pointed-to object is not known, void pointers cannot
be dereferenced, nor is pointer arithmetic on them allowed, although they can easily be (and in
many contexts implicitly are) converted to and from any other object pointer type.

82
Careless use of pointers is potentially dangerous. Because they are typically unchecked, a pointer
variable can be made to point to any arbitrary location, which can cause undesirable effects.
Although properly-used pointers point to safe places, they can be made to point to unsafe places
by using invalid pointer arithmetic; the objects they point to may be deallocated and reused
(dangling pointers); they may be used without having been initialized (wild pointers); or they
may be directly assigned an unsafe value using a cast, union, or through another corrupt pointer.
In general, C is permissive in allowing manipulation of and conversion between pointer types,
although compilers typically provide options for various levels of checking. Some other
programming languages address these problems by using more restrictive reference types.

83
Arrays

Array types in C are traditionally of a fixed, static size specified at compile time. (The more
recent C99 standard also allows a form of variable-length arrays.) However, it is also possible to
allocate a block of memory (of arbitrary size) at run-time, using the standard library's malloc
function, and treat it as an array. C's unification of arrays and pointers (see below) means that
true arrays and these dynamically-allocated, simulated arrays are virtually interchangeable. Since
arrays are always accessed (in effect) via pointers, array accesses are typically not checked
against the underlying array size, although the compiler may provide bounds checking as an

84
option. Array bounds violations are therefore possible and rather common in carelessly written
code, and can lead to various repercussions, including illegal memory accesses, corruption of
data, buffer overruns, and run-time exceptions.

C does not have a special provision for declaring multidimensional arrays, but rather relies on
recursion within the type system to declare arrays of arrays, which effectively accomplishes the
same thing. The index values of the resulting "multidimensional array" can be thought of as
increasing in row-major order.

85
Although C supports static arrays, it is not required that array indices be validated (bounds
checking). For example, one can try to write to the sixth element of an array with five elements,
generally yielding undesirable results. This type of bug, called a buffer overflow or buffer
overrun, is notorious for causing a number of security problems. Since bounds checking
elimination technology was largely nonexistent when C was defined, bounds checking came with
a severe performance penalty, particularly in numerical computation. A few years earlier, some
Fortran compilers had a switch to toggle bounds checking on or off; however, this would have
been much less useful for C, where array arguments are passed as simple pointers.

86
Multidimensional arrays are commonly used in numerical algorithms (mainly from applied linear
algebra) to store matrices. The structure of the C array is well suited to this particular task.
However, since arrays are passed merely as pointers, the bounds of the array must be known
fixed values or else explicitly passed to any subroutine that requires them, and dynamically sized
arrays of arrays cannot be accessed using double indexing. (A workaround for this is to allocate
the array with an additional "row vector" of pointers to the columns.)

C99 introduced "variable-length arrays" which address some, but not all, of the issues with
ordinary C arrays.

87
Macros

Many assemblers support predefined macros, and others support programmer-defined (and
repeatedly redefinable) macros involving sequences of text lines that variables and constants are
embedded in. This sequence of text lines may include a sequence of instructions, or a sequence
of data storage pseudo-ops. Once a macro has been defined using the appropriate pseudo-op, its
name may be used in place of a mnemonic. When the assembler processes such a statement, it
replaces the statement with the text lines associated with that macro, then processes them just as

88
though they had appeared in the source code file all along (including, in better assemblers,
expansion of any macros appearing in the replacement text).

Since macros can have 'short' names but expand to several or indeed many lines of code, they
can be used to make assembly language programs appear to be much shorter (require less lines of
source code from the application programmer, as with a higher level language). They can also be
used to add higher levels of structure to assembly programs, optionally introduce embedded de-
bugging code via parameters and other similar features.

89
Many assemblers have built-in (or predefined) macros for system calls and other special code
sequences, such as the generation and storage of data realized through advanced bitwise and
boolean operations used in gaming, software security, data management, and cryptography.

Macro assemblers often allow macros to take parameters. Some assemblers include quite
sophisticated macro languages, incorporating such high-level language elements as optional
parameters, symbolic variables, conditionals, string manipulation, and arithmetic operations, all
usable during the execution of a given macro, and allowing macros to save context or exchange
information. Thus a macro might generate a large number of assembly language instructions or

90
data definitions, based on the macro arguments. This could be used to generate record-style data
structures or "unrolled" loops, for example, or could generate entire algorithms based on
complex parameters. An organization using assembly language that has been heavily extended
using such a macro suite can be considered to be working in a higher-level language, since such
programmers are not working with a computer's lowest-level conceptual elements.

Macros were used to customize large scale software systems for specific customers in the
mainframe era and were also used by customer personnel to satisfy their employers' needs by
making specific versions of manufacturer operating systems; this was done, for example, by

91
systems programmers working with IBM's Conversational Monitor System/Virtual Machine
(CMS/VM) and with IBM's "real time transaction processing" add-ons, CICS, Customer
Information Control System, and ACP/TPF, the airline/financial system that began in the 1970s
and still runs many large Global Distribution Systems (GDS) and credit card systems today.

It was also possible to use solely the macro processing capabilities of an assembler to generate
code written in completely different languages, for example, to generate a version of a program
in Cobol using a pure macro assembler program containing lines of Cobol code inside assembly
time operators instructing the assembler to generate arbitrary code.

92
This was because, as was realized in the 1970s, the concept of "macro processing" is independent
of the concept of "assembly", the former being in modern terms more word processing, text
processing, than generating object code. The concept of macro processing in fact appeared in and
appears in the C programming language, which supports "preprocessor instructions" to set
variables, and make conditional tests on their values. Note that unlike certain previous macro
processors inside assemblers, the C preprocessor was not Turing-complete because it lacked the
ability to either loop or "go to", the latter allowing the programmer to loop.

93
Despite the power of macro processing, it fell into disuse in high level languages while
remaining a perennial for assemblers.

This was because many programmers were rather confused by macro parameter substitution and
did not disambiguate macro processing from assembly and execution

Macro parameter substitution is strictly by name: at macro processing time, the value of a
parameter is textually substituted for its name. The most famous class of bugs resulting was the
use of a parameter that itself was an expression and not a simple name when the macro writer

94
expected a name. In the macro: foo: macro a load a*b the intention was that the caller would
provide the name of a variable, and the "global" variable or constant b would be used to multiply
"a". If foo is called with the parameter a-c, an unexpected macro expansion occurs.

USAGE:

There have always been debates over the usefulness and performance of assembly language
relative to high-level languages. Assembly language has specific niche uses where it is
important; see below. But in general, modern optimizing compilers are claimed[citation needed] to
95
render high-level languages into code that can run as fast as hand-written assembly, despite the
counter-examples that can be found. The complexity of modern processors and memory sub-
system makes effective optimization increasingly difficult for compilers, as well as assembler
programmers [11][12]. Moreover, and to the dismay of efficiency lovers, increasing processor
performance has meant that most CPUs sit idle most of the time, with delays caused by
predictable bottlenecks such as I/O operations and paging. This has made raw code execution
speed a non-issue for many programmers.

96
There are some situations in which practitioners might choose to use assembly language, such as
when:

• a stand-alone binary executable is required, i.e. one that must execute without recourse to
the run-time components or libraries associated with a high-level language; this is
perhaps the most common situation. These are embedded programs that store only a
small amount of memory and the device is intended to do single purpose tasks. Such
examples consist of telephones, automobile fuel and ignition systems, air-conditioning
control systems, security systems, and sensors.

97
• interacting directly with the hardware, for example in device drivers and interrupt
handlers.
• using processor-specific instructions not exploited by or available to the compiler. A
common example is the bitwise rotation instruction at the core of many encryption
algorithms.
• creating vectorized functions for programs in higher-level languages such as C. In the
higher-level language this is sometimes aided by compiler intrinsic functions which map
directly to SIMD mnemonics, but nevertheless result in a one-to-one assembly
conversion specific for the given vector processor.

98
• extreme optimization is required, e.g., in an inner loop in a processor-intensive algorithm.
Game programmers take advantage of the capabilities of hardware features in systems,
enabling the games to run faster.
• a system with severe resource constraints (e.g., an embedded system) must be hand-
coded to maximize the use of limited resources; but this is becoming less common as
processor price decreases and performance improves.
• no high-level language exists, on a new or specialized processor, for example.
• writing real-time programs that need precise timing and responses, such as simulations,
flight navigation systems, and medical equipment. For example, in a fly-by-wire system,

99
telemetry must be interpreted and acted upon within strict time constraints. Such systems
must eliminate sources of unpredictable delays, which may be created by (some)
interpreted languages, automatic garbage collection, paging operations, or preemptive
multitasking. However, some higher-level languages incorporate run-time components
and operating system interfaces that can introduce such delays. Choosing assembly or
lower-level languages for such systems gives the programmer greater visibility and
control over processing details.
• complete control over the environment is required, in extremely high security situations
where nothing can be taken for granted.

100
• writing computer viruses, bootloaders, certain device drivers, or other items very close to
the hardware or low-level operating system.
• writing instruction set simulators for monitoring, tracing and debugging where additional
overhead is kept to a minimum
• reverse-engineering existing binaries that may or may not have originally been written in
a high-level language, for example when cracking copy protection of proprietary
software.

101
• reverse engineering and modifying video games (also known as ROM Hacking), which is
possible with a range of techniques. The most widely employed is altering the program
code at the assembly language level.
• writing self modifying code, to which assembly language lends itself well.
• writing games and other software for graphing calculators.
• writing compiler software that generates assembly code, and the writers should therefore
be expert assembly language programmers themselves.
• writing cryptographic algorithms that must always take strictly the same time to execute,
preventing timing attacks.

102
TYPICAL APPLICATIONS:

Hard-coded assembly language is typically used in a system's boot ROM (BIOS on IBM-
compatible PC systems). This low-level code is used, among other things, to initialize and test
the system hardware prior to booting the OS, and is stored in ROM. Once a certain level of
hardware initialization has taken place, execution transfers to other code, typically written in
higher level languages; but the code running immediately after power is applied is usually
written in assembly language. The same is true of most boot loaders.

103
Many compilers render high-level languages into assembly first before fully compiling, allowing
the assembly code to be viewed for debugging and optimization purposes. Relatively low-level
languages, such as C, often provide special syntax to embed assembly language directly in the
source code. Programs using such facilities, such as the Linux kernel, can then construct
abstractions utilizing different assembly language on each hardware platform. The system's
portable code can then utilize these processor-specific components through a uniform interface.

Assembly language is also valuable in reverse engineering, since many programs are distributed
only in machine code form, and machine code is usually easy to translate into assembly language

104
and carefully examine in this form, but very difficult to translate into a higher-level language.
Tools such as the Interactive Disassembler make extensive use of disassembly for such a
purpose.

A particular niche that makes use of assembly language is the demoscene. Certain competitions
require the contestants to restrict their creations to a very small size (e.g. 256B, 1KB, 4KB or 64
KB), and assembly language is the language of choice to achieve this goal.[15] When resources,
particularly CPU-processing constrained systems, like the earlier Amiga models, and the
Commodore 64, are a concern, assembler coding is a must: optimized assembler code is written

105
"by hand" and instructions are sequenced manually by the coders in an attempt to minimize the
number of CPU cycles used; the CPU constraints are so great that every CPU cycle counts.
However, using such techniques has enabled systems like the Commodore 64 to produce real-
time 3D graphics with advanced effects, a feat which might be considered unlikely or even
impossible for a system with a 0.99MHz processor.

106
107
8051
MICROCONTROLLER

108
MICOCONTROLLER VS. MICROPROCESSOR
Some Key differences:
. uControllers are self-contained with RAM, ROM, EEPROM,
. sometimes with A/D, D/A converters, Serial Ports, etc.
.
. Processors are more general purpose, with Memory, converters
. communication harware external to the uprocessor, and added
. to the design as needed.

microcontroller versus microprocessor:-

109
Usually, microprocessor is only the core. It is a CPU, sometime a memory controller, and
that's it. You have to use it with other components. You need to add memory, IO, devices, ...

Microcontrolers are targetted toward embedded applications. The point is to try to use the
less possible external components. So, generally, microcontrolers have memory (program
memory and some RAM), IO ports, counters, UART, ... all integrated into a single chip.

Microprocessors ure usually faster than microcontrolers. They are sometime much higher
price. Though, we are now seing microcontrolers with higher speed and lower prices. A good
examples are the ARM7-compatible microcontrolers.

110
The main point again, microprocessor are just that, a 'processor'. Microcontrolers are a
microprocessor plus a dozen other functions in the chip. When you buy a microprocessor,
you're free to (you have to) use the components you want around the processor. With a
microcontroler, you usually choose between different flavors of microcontrolers (more/less
memory, 0/1/2 UART, more or less timers, SPI, ...) but you're stuck with all those functions.
For example, if you do not want a UART, but the microcontroler you want (say it's the one
that have enough memory as you require) have one, you get the extra feature and can not
select not to have it in the chip. It's kind of buying something you don't want. Though, this
may look as a disadvantage, it is generally not the case, because of 2 things:

1st - The microcontroller pins used by those IO can be used as general purpose IO if the

111
function is not needed. For example, you're free to use the UART, and have a dedicated TX
and RX pin on the microcontroller, or not to use the UART, and in this case, use those 2 pins
as general purpose IO. This is usually done by programing a bit to 0 or 1 in the
microcontroller. This is true for most peripherals.

2nd - It cost a lot less to include a ton of features in the microcontroller, and having the user
select the ones he want or not (by setting a bit to 0 or 1), than creating custom devices.
That's why the microcontrolers are becoming dirt-cheap.

112
8051 MICROCONTROLLER:-

About the 8051:-

The Intel 8051 is an 8-bit microcontroller which means that most available operations are limited
to 8 bits. There are 3 basic "sizes" of the 8051: Short, Standard, and Extended. The Short and
113
Standard chips are often available in DIP form, but the Extended 8051 models often have a
different form factor, and are not "drop-in compatable". All these things are called 8051 because
they can all be programmed using 8051 assembly language, and they all share certain features
(although the different models all have their own special features).

Some of the features that have made the 8051 popular are:

• 8-bit data bus


• 16-bit address bus

114
• 32 general purpose registers each of 8 bits
• 16 bit timers (usually 2, but may have more, or less).
• 3 internal and 2 external interrupts.
• Bit as well as byte addressable RAM area of 16 bytes.
• Four 8-bit ports, (short models have two 8-bit ports).
• 16-bit program counter and data pointer

8051 models may also have a number of special, model-specific features, such as UARTs, ADC,
OpAmps, etc...

115
Typical applications:-

8051 chips are used in a wide variety of control systems, telecom applications, robotics as well
as in the automotive industry. By some estimations, 8051 family chips make up over 50% of the
embedded chip market.

116
117
FIG 1.1

PIN 9: PIN 9 is the reset pin which is used reset the microcontroller’s internal registers and ports
upon starting up. (Pin should be held high for 2 machine cycles.)

PINS 18 & 19: The 8051 has a built-in oscillator amplifier hence we need to only connect a
crystal at these pins to provide clock pulses to the circuit.

118
PIN 40 and 20: Pins 40 and 20 are VCC and ground respectively. The 8051 chip needs +5V
500mA to function properly, although there are lower powered versions like the Atmel 2051
which is a scaled down version of the 8051 which runs on +3V.

PINS 29, 30 & 31: As described in the features of the 8051, this chip contains a built-in flash
memory. In order to program this we need to supply a voltage of +12V at pin 31. If external
memory is connected then PIN 31, also called EA/VPP, should be connected to ground to
indicate the presence of external memory. PIN 30 is called ALE (address latch enable), which is
used when multiple memory chips are connected to the controller and only one of them needs to

119
be selected. We will deal with this in depth in the later chapters. PIN 29 is called PSEN. This is
"program select enable". In order to use the external memory it is required to provide the low
voltage (0) on both PSEN and EA pins.

Ports:-

There are 4 8-bit ports: P0, P1, P2 and P3.

120
PORT P1 (Pins 1 to 8): The port P1 is a general purpose input/output port which can be used for
a variety of interfacing tasks. The other ports P0, P2 and P3 have dual roles or additional
functions associated with them based upon the context of their usage.

PORT P3 (Pins 10 to 17): PORT P3 acts as a normal IO port, but Port P3 has additional
functions such as, serial transmit and receive pins, 2 external interrupt pins, 2 external counter
inputs, read and write pins for memory access.

121
PORT P2 (pins 21 to 28): PORT P2 can also be used as a general purpose 8 bit port when no
external memory is present, but if external memory access is required then PORT P2 will act as
an address bus in conjunction with PORT P0 to access external memory. PORT P2 acts as A8-
A15, as can be seen from fig 1.1

PORT P0 (pins 32 to 39) PORT P0 can be used as a general purpose 8 bit port when no external
memory is present, but if external memory access is required then PORT P0 acts as a
multiplexed address and data bus that can be used to access external memory in conjunction with
PORT P2. P0 acts as AD0-AD7, as can be seen from fig 1.1

122
Oscillator Circuits:-

The 8051 requires the existence of an external oscillator circuit. The oscillator circuit usually
runs around 12MHz, although the 8051 (depending on which specific model) is capable of
running at a maximum of 40MHz. Each machine cycle in the 8051 is 12 clock cycles, giving an
effective cycle rate at 1MHz (for a 12MHz clock) to 3.33MHz (for the maximum 40MHz clock).

123
REGISTERS:-

The Accumulator
The Accumulator, as its name suggests, is used as a general register to accumulate the results
of a large number of instructions. It can hold an 8-bit (1-byte) value and is the most versatile
register the 8051 has due to the shear number of instructions that make use of the accumulator.
More than half of the 8051s 255 instructions manipulate or use the accumulator in some way.
The "R" registers

124
The "R" registers are a set of eight registers that are named R0, R1, etc. up to and
including
R7.These registers are used as auxillary registers in many operations.
The "B" Register
The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1- byte)
value.The "B" register is only used by two 8051 instructions: MUL AB and DIV AB. Thus, if you
want to quickly and easily multiply or divide A by another number, you may store the other
number in "B" and make use of these two instructions.Aside from the MUL and DIV instructions,

125
the "B" register is often used as yet another temporary storage register much like a ninth "R"
register.
The Data Pointer (DPTR)
The Data Pointer (DPTR) is the 8051s only user-accessable 16-bit (2-byte) register.
The
Accumulator, "R" registers, and "B" register are all 1-byte values.
DPTR, as the name suggests, is used to point to data. It is used by a number of commands
which allow the 8051 to access external memory. When the 8051 accesses external memory it
will access external memory at the address indicated by DPTR.

126
The Program Counter (PC)
The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction
to execute is found in memory. When the 8051 is initialized PC always starts at 0000h and is
incremented each time an instruction is executed. It is important to note that PC isnt always
incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by
2 or 3 in these cases.The Program Counter is special in that there is no way to directly modify
its value.
The Stack Pointer (SP)

127
The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The
Stack Pointer is used to indicate where the next value to be removed from the stack should be
taken from.
When you push a value onto the stack, the 8051 first increments the value of SP and then
stores the value at the resulting memory location.When you pop a value off the stack, the 8051
returns the value from the memory location indicated by SP, and then decrements the value of
SP.
This order of operation is important. When the 8051 is initialized SP will be initialized to 07h. If
you immediately push a value onto the stack, the value will be stored in Internal RAM address
128
08h. This makes sense taking into account what was mentioned two paragraphs above: First
the 8051 will increment the value of SP (from 07h to 08h) and then will store the pushed value
at that memory address (08h).

129
SPECIAL FUNCTION REGISTER

130
The Special Function Register (SFR) is the upper area of addressable memory, from
address 0x80 to 0xFF. This area of memory cannot be used for data or program storage, but is
instead a series of memory-mapped ports and registers. All port input and output can therefore
be performed by memory mov operations on specified addresses in the SFR. Also, different
status registers are mapped into the SFR, for use in checking the status of the 8051, and
changing some operational parameters of the 8051.
The 4 ports, register A,B, and stack pointer SP have already been explained above.
The rest of
the SFR are explained below.
131
DPL/DPH (Data Pointer Low/High, Addresses 82h/83h):
The SFRs DPL and DPH work together to represent a 16-bit value called the Data Pointer. The
data pointer is used in operations regarding external RAM and some instructions involving code
memory. Since it is an unsigned two-byte integer value, it can represent values from 0000h to
FFFFh (0 through 65,535 decimal).

132
133
PCON(power control,addresses 87h):

The Power Control SFR is used to control the 8051's power control modes. Certain operation
modes of the 8051 allow the 8051 to go into a type of "sleep" mode which requires much less
power. These modes of operation are controlled through PCON. Additionally, one of the bits in
PCON is used to double the effective baud rate of the 8051's serial port.

134
TCON (Timer Control, Addresses 88h, Bit-Addressable):
The Timer Control SFR is used to configure and modify the way in which the 8051's two timers
operate. This SFR controls whether each of the two timers is running or stopped and contains a
flag to indicate that each timer has overflowed. Additionally, some non-timer related bits are
135
located in the TCON SFR. These bits are used to configure the way in which the external
interrupts are activated and also contain the external interrupt flags which are set when an
external interrupt has occured.

136
TMOD (Timer Mode, Addresses 89h):

The Timer Mode SFR is used to configure the mode of operation of each of the two timers.
Using this SFR your program may configure each timer to be a 16-bit timer, an 8-bit autoreload
timer, a 13-bit timer, or two separate timers. Additionally, you may configure the timers to only
count when an external pin is activated or to count "events" that are indicated on an external
pin.

137
TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Ch): These two SFRs, taken together, represent
timer 0. Their exact behavior depends on how the timer is configured in the TMOD SFR;
however, these timers always count up. What is configurable is how and when they increment in
value.
138
TL1/TH1 (Timer 1 Low/High, Addresses 8Bh/8Dh): These two SFRs, taken together, represent
timer 1. Their exact behavior depends on how the timer is configured in the TMOD SFR;
however, these timers always count up. What is configurable is how and when they increment in
value.

SCON (Serial Control, Addresses 98h, Bit-Addressable):

139
The Serial Control SFR is used to configure the behavior of the 8051's on-board serial port. This
SFR controls the baud rate of the serial port, whether the serial port is activated to receive data,
and also contains flags that are set when a byte is successfully sent or received..

140
SBUF (Serial Control, Addresses 99h):
The Serial Buffer SFR is used to send and receive data via the on-board serial port. Any value
written to SBUF will be sent out the serial port's TXD pin. Likewise, any value which the 8051
receives via the serial port's RXD pin will be delivered to the user program via SBUF. In other
words, SBUF serves as the output port when written to and as an input port when read from.
IE (Interrupt Enable, Addresses A8h):
The Interrupt Enable SFR is used to enable and disable specific interrupts. The low 7
bits of the

141
SFR are used to enable/disable the specific interrupts, where as the highest bit is used to
enable or disable ALL interrupts. Thus, if the high bit of IE is 0 all interrupts are disabled
regardless of whether an individual interrupt is enabled by setting a lower bit.

142
IP (Interrupt Priority, Addresses B8h, Bit-Addressable):
The Interrupt Priority SFR is used to specify the relative priority of each interrupt. On the 8051,
an interrupt may either be of low (0) priority or high (1) priority. An interrupt may only interrupt
interrupts of lower priority. For example, if we configure the 8051 so that all interrupts are of low
priority except the serial interrupt, the serial interrupt will always be able to interrupt the system,
even if another interrupt is currently executing. However, if a serial interrupt is executing no
other interrupt will be able to interrupt the serial interrupt routine since the serial interrupt routine
has the highest priority.

143
PSW (Program Status Word, Addresses D0h, Bit-Addressable):-

The Program Status Word is used to store a number of important bits that are set and cleared
by 8051 instructions. The PSW SFR contains the carry flag, the auxiliary carry flag, the overflow

144
flag, and the parity flag. Additionally, the PSW register contains the register bank select flags
which are used to select which of the "R" register banks are currently selected.

145
146
147
TYPES OF MEMORY :-

The 8051 has three very general types of memory. To effectively program the 8051
it is
necessary to have a basic understanding of these memory types.
The memory types are illustrated in the following graphic. They are: On-Chip
Memory,
External Code Memory, and External RAM.

148
On-Chip Memory refers to any memory (Code, RAM, or other) that physically exists on
the
microcontroller itself. On-chip memory can be of several types, but we'll get into
that shortly.
External Code Memory is code (or program) memory that resides off-chip. This is often
in
the form of an external EPROM.
External RAM is RAM memory that resides off-chip. This is often in the form of standard
static RAM or flash RAM

149
TIMERS
The 8051 comes equipped with two timers, both of which may be controlled, set, read, and
configured individually. The 8051 timers have three general functions: 1) Keeping time and/or
calculating the amount of time between events, 2) Counting the events themselves, or 3)
Generating baud rates for the serial port.
As mentioned before, the 8051 has two timers which each function essentially the same way.
One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and
TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself
(TH0/TL0 and TH1/TL1).
150
151
152
13 bit timer mode:-
Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain
compatability with its predecesor, the 8048. Generally the 13-bit timer mode is not used in new
development.When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is
incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the
two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in

153
essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will overflow
back to zero 8192 machine cycles later.
16-bit Time Mode (mode 1)
Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions
just like 13-
bit mode except that all 16 bits are used.
TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes
THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536

154
distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine
cycles.
8-bit Time Mode (mode 2)
Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a timer
is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting
up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the
case of modes 0 and 1), it will be reset to the value stored in THx.
For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were to
watch the values of TH0 and TL0 for a few machine cycles this is what wed see:As you can see,
155
the value of TH0 never changed. In fact, when you use mode 2 you almost always set THx to a
known value and TLx is the SFR that is constantly incremented.
Split Timer Mode (mode 3)
Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes
two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count
from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to
TH0.
While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or
2 normally--however, you may not start or stop the real timer 1 since the bits that do that are
156
now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no
matter what.
INTERRUPTS:-

As the name implies, an interrupt is some event which interrupts normal program
execution.
As stated earlier, program flow is always sequential, being altered only by those instructions
which expressly cause program flow to deviate in some way. However, interrupts give us a
mechanism to "put on hold" the normal program flow, execute a subroutine, and then resume
157
normal program flow as if we had never left it. This subroutine, called an interrupt handler, is
only executed when a certain event (interrupt) occurs. The event may be one of the timers
"overflowing," receiving a character via the serial port, transmitting a character via the serial
port, or one of two "external events." The 8051 may be configured so that when any of these
events occur the main program is temporarily suspended and control passed to a special
section of code which presumably would execute some function related to the event that
occured. Once complete, control would be returned to the original program. The main program
never even knows it was interrupted.

158
The ability to interrupt normal program execution when certain events occur makes it much
easier and much more efficient to handle certain conditions. If it were not for interrupts we would
have to manually check in our main program whether the timers had overflown, whether we had
received another character via the serial port, or if some external event had occured. Besides
making the main program ugly and hard to read, such a situation would make our program
inefficient since wed be burning precious "instruction cycles" checking for events that usually
dont happen.
We can configure the 8051 so that any of the following events will cause an
interrupt:
y

159
Timer 0 Overflow.
y

Timer 1 Overflow.
y

Reception/Transmission of Serial Character.


y

External Event 0.
y

External Event 1.
In other words, we can configure the 8051 so that when Timer 0 Overflows or when
a character
is sent/received, the appropriate interrupt handler routines are called.
Polling Sequence
160
The 8051 automatically evaluates whether an interrupt should occur after every
instruction.
When checking for interrupt conditions, it checks them in the following order:
y

External 0 Interrupt
y

Timer 0 Interrupt
y

External 1 Interrupt
y

Timer 1 Interrupt
y

Serial Interrupt

161
This means that if a Serial Interrupt occurs at the exact same instant that an External 0 Interrupt
occurs, the External 0 Interrupt will be executed first and the Serial Interrupt will be executed
once the External 0 Interrupt has completed.
SERIAL PORT COMMUNICATION
One of the 8051s many powerful features is its integrated UART, otherwise known as a serial
port. The fact that the 8051 has an integrated serial port means that you may very easily read
and write values to the serial port. If it were not for the integrated serial port, writing a byte to a
serial line would be a rather tedious process requring turning on and off one of the I/O lines in

162
rapid succession to properly "clock out" each individual bit, including start bits, stop bits, and
parity bits.
However, we do not have to do this. Instead, we simply need to configure the serial ports
operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a
value to the serial port or read the same SFR to read a value from the serial port. The 8051 will
automatically let us know when it has finished sending the character we wrote and will also let
us know whenever it has received a byte so that we can process it. We do not have to worry
about transmission at the bit level--which saves us quite a bit of coding and processing time

163
The first thing we must do when using the 8051s integrated serial port is, obviously, configure it.
This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how
the baud rate will be determined.
First, lets present the "Serial Control" (SCON) SFR and define what each bit of the
SFR
represents:

164
165
PROJECT DESCRIPTION:-

166

You might also like