0% found this document useful (0 votes)
4 views

Lite

Uploaded by

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

Lite

Uploaded by

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

Embedded Primitive Level

EMBEDDED PRIMITIVE LEVEL

IWIZ Learners Institute of Technical education Pvt Ltd 1


Embedded Primitive Level

All rights reserved.

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


in any form, or by any means, electronic, mechanical, photocopying, recording or
otherwise, without the prior written permission of the publisher. No patent liability is
assumed with respect to the use of the information contained therein. Although every
precaution has been taken in the preparation of this book, the publisher and authors
assume no responsibility for errors or omissions.

All references to software are the registered trademarks of their respective


organizations. All software is used for education purpose only.

LITE/JA1/08
LITE/J21/08
LITE/DN1/08

IWIZ LITE (p) ltd


#78, 3rd floor, Usman Road,
(Hotel Saravana Bhavan upstairs )
T.Nagar.
Chennai – 600 017.

IWIZ Learners Institute of Technical education Pvt Ltd 2


Embedded Primitive Level

Basics of Embedded

BASIC ELECTRONICS LEVEL 1

1.1 INTRODUCTION
1.2. RESISTOR
1.2.1 Introduction
1.2.2 Types of Resistors
1.3 CAPACITOR
1.3.1 Introduction
1.3.2 Types of capacitors
1.4 DIODES
1.4.1 Introduction
1.4.2 Types of Diodes
1.5. TRANSISTOR
1.5.1 Introduction
1.5.2 Commercial Type of Transistors
1.6. INTEGRATED CIRCUITS
1.6.1 Introduction
1.6.2 Types of IC’s
1.7 RELAY
1.7.1 Introduction
1.7.2 Application
1.7.3 Operation
1.8 RF-TRANSCEIVER
1.8.1 RF-TRANSMITTER
1.8.2 RF Receiver
FUNDAMENTAL CONCEPT OF C LEVEL 2

2.1 INTRODUCTION
2.2 C KEYWORDS
2.3 DATA TYPE
2.4 VARIABLE
2.4.1 Extern
.4.2 Static
2.4.3 Auto
2.4.4 Register
2.5 Constant
2.6 Operators
2.6.1 Arithmetic:
2.6.2 Assignment
2.6.3 Logical/Relational
2.6.4 Bitwise
2.7 Statements
2.7.1. If Statement
2.7.2. IF Else Statement
2.8 MULTI WAY STATEMENTS
2.8.1. Switch
2.9 Loop Control Structure

IWIZ Learners Institute of Technical education Pvt Ltd 3


Embedded Primitive Level

2.9.1. While Statement


2.9.2. for Statement
2.9.3 .Do Statement
2.10 Unconditional Statements
2.10.1. Goto
2.10.2. Continue
2.10.3. Break
2.10.4. Return
2.11 Memory Function
2.11.1 Calloc
2.11.2. Free
2.11.3. Malloc
2.11.4 .Realloc
2.12 String
2.12.1. Strlen ()
2.12.2 Strncpy ()
2.12.3 Strcmp ()
2.12.4 Strcat ()
2.13 Arrays
2.13.1 Array declaration
2.13.2 Accessing elements
2.13.3 Dynamic arrays
2.13.4 Multidimensional arrays
2.14 Function
2.14.1 Call by value
2.14.2 Call-by-reference parameters
2.14.3 Recursive Functions
2.15 Pointer
2.15.1 Pointers to Functions
2.15.2 Pointers and Strings
2.15.3 Pointers to Arrays:
2.16 linked list
2.16.1 Single Linked List
2.16.2 Doubly-Linked List
2.16.3 Circular Linked List
ADVANCED C LEVEL 3

3.1 C-style strings


3.1.1 Using String
3.1.2 Manupulating C String using String.h
3.1.3 Safe Programming
3.2 File I/O
3.2.1 C File I/O and Binary File I/O
3.2.2 Binary I/O
3.3 COMMAND-LINE ARGUMENTS IN C
3.3.1 ACCESSING COMMAND-LINE ARGUMENTS
3.3.1.1 COMMAND-LINE ARGUMENTS
3.4 Variable Argument List
3.5 BINARY TREES

IWIZ Learners Institute of Technical education Pvt Ltd 4


Embedded Primitive Level

3.6 USING LIBRARY


3.6.1 HEADER FILES
3.6.2 ANSI C Library Header Files
3.6.3 macro definition of function
3.7 TYPE CASTING
3.7.1 Implicit conversion
3.7.2 Explicit conversion
3.7.3 TYPE-CAST CONVERSIONS
3.8 STORAGE CLASSES
FOUNDATION OF EMBEDDED SYSTEM LEVEL 4

4.1 What is Embedded System


4.1.1 Characteristics
4.1.2 Real Time Issues
4.1.3 Reliability
4.1.4 Cost Effectiveness
4.1.5 Low Power Consumption
4.1.6 Efficient Use of Processing Power
4.1.7 Efficient Use of Memory
4.1.8 Appropriate Execution Time
4.1.9 Embedded Systems Design
4.1.10. Applications
4.2 Which programming language should you use

4.3 Cognitive Process in Embedded Systems


4.3.1 Stand-Alone Embedded Systems
4.3.2 Real Time Systems
4.3.3 Networked Information Appliances
4.3.4 Mobile Devices
4. 4 8051 Instruction set
4.4.1 Arithmetic Instructions: -
4.4.2 Logical Instructions: -
4.4.3 Data Moving / Handling Instructions: -
4.4.4 Branching Instructions: -
4.5 Programming embedded system in C
4.5.1 Introduction:
4.5.2 Embedded System Applications
4.5.3 Which Processor Should You Use?
4.6 Which operating system Should You Use
4.7 Assembler
4.7.1 Definition
4.7.2 Compiler:
4.8 Diversify MicroControllers
4.9 Architecture
4.9.1 Vann Neumann
4.9.2 Harvard
4.9.3 Roll of Outstanding Firm of Microcontrollers

IWIZ Learners Institute of Technical education Pvt Ltd 5


Embedded Primitive Level

ATMEL MICROCONTROLLER (89C51&89S51&89S52) LEVEL 5

5.1 Comparison Between RISC and CISC

5.1.1 RISC VERSUS CISC


5.2 Difference Between MICROCONTROLLER and Microprocessor
5.2.1 MICROCONTROLLER
5.2.2 Microprocessor
5.3 Pin Diagram
5.4 Difference between 8031,8052,8051
5.5 Pin Description
5.5.1 PORT 0
5.5.2 PORT 1
5.5.3 PORT 2
5.5.4 PORT 3
5.5.5 PORT PIN ALTERNATE FUNCTIONS
5.5.6 RST
5.5.7 ALE/PROG
5.5.8 PSEN
5.5.9 EA/VPP
5.6.1 XTAL2
5.6.0 XTAL1

5.7 ADDRESSING MODES


5.7.1 IMMEDIATE ADDRESSING
5.7.2 DIRECT ADDRESSING
5.7.3 INDIRECT ADDRESSING
5.7.4 EXTERNAL DIRECT
5.7.5 EXTERNAL INDIRECT
5.8 Types of instructions
5.8.1 DATA TRANSFER
5.8.2 ARITHMETIC

5.8.3 HARDWARE DESCRIPTION


5.9 Timers / Count
5.9.1 HOW DOES A TIMER COUNT?
5.9.2 TIMER SFRS
5.9.3 INITIALIZING A TIMER
5.9.4 READING THE TIMER
5.9.5 READING THE VALUE OF A TIMER
5.9.6 DETECTING TIMER OVERFLOW
5.9.7 TIMING THE LENGTH OF EVENTS
5.9.8 USING TIMERS AS EVENT COUNTERS

HANDLING REGISTER TYPES OF MNEMONICS LEVEL 6

6.1 Binary manipulation instruction


6.2 Bitwise Boolean Logic instructions
6.2.1 Note on word and byte bitwise calculations
6.2.2 Single Bit Manipulation Instructions

IWIZ Learners Institute of Technical education Pvt Ltd 6


Embedded Primitive Level

6.3 Shifts
6.3.1 Relation of Shifts and Division and Multiplication
6.3.2 Arithmetic Shifts
6.4 Rotates
6.4.1 Synthesizing Multiplication Using Shifts and Additions
6.5 data transfer
6.5.1 data transfer instructions- Internal
6.5.2 data transfer instructions-External
6.6 Ram
6.6.1 EXTERNAL CODE MEMORY
6.6.2 EXTERNAL RAM DATA MEMORY
6.6.3 INTERNAL MEMORY
6.7 Port register SFR
6.8 PSW, Program Status Word
6.9 Stack Pointer
6.10 Data Pointer
6.11 accumulator
6.12 Program Counter
6.13 SFR register for the Internal Timer
6.14 Power Control register
6.15 serial register port
6.16 Interrupts registers
6.17 ROM
6.18 Hybrid Memory
6.19 Summary

IWIZ Learners Institute of Technical education Pvt Ltd 7


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 8


Embedded Primitive Level

CHAPTER -1

BASIC ELECTRONICS

About this Chapter

 This chapter gives information about Active and Passive components.


 This chapter gives brief idea about Wireless technologies.

After this Chapter

 You can able to know different types of electronic components and its
functions.
 You can able to handle the circuit components effectively.

1.1 INTRODUCTION

Electronic circuits are composed of various electronic devices such as transistors,


resistors and capacitors. Circuits are built using discrete components, the components are
typically soldered together on a fiberglass board known as a printed circuit board. One or
more surfaces of the printed circuit board are layered on conductive material which has been
patterned to form interconnections between the different components in the circuit. In some
cases, the circuits necessary for a particular application are far too complex to build from
individual discrete components, and integrated-circuit technology must be employed.
Integrated circuits are fabricated entirely from a single piece of semiconductor substrate. It is
possible in some cases to put several million electronic devices inside the same integrated
circuit. Many integrated circuits can be fabricated on a single wafer of silicon at one time,
and at the end of the fabrication process, the wafer is sawed into individual integrated
circuits. These small pieces or chips, as they are popularly known, are then packaged
appropriately for their intended application. Very often electronic components are
mechanically stabilized, improved in insulation properties and protected from environmental
influence by being enclosed in synthetic resin.

Components may be Passive or Active

 Passive components are those that do not have gain or directionality. In the Electric
industry they are called Electrical elements or electrical components.
 Active components are those that have gain or directionality, in contrast to passive
components, which have neither.

1.2. RESISTOR

1.2.1 Introduction

The resistors function is to reduce the flow of electric current.


This symbol is used to indicate a resistor in a circuit diagram, known as a schematic.

IWIZ Learners Institute of Technical education Pvt Ltd 9


Embedded Primitive Level

Resistance value is designated in units called the "Ohm." A 1000 Ohm resistor is typically
shown as 1K-Ohm (kilo Ohm) and 1000 K-Ohms is written as 1M-Ohm (megohm).

There are two classes of resistors: Fixed resistors and variable resistors. They are
also classified according to the material from which they are made. The typical resistor is
made of either carbon film or metal film. There are other types as well, but these are the most
common.

1.2.2 Types of Resistors

a) Fixed Resistors

A fixed resistor is one in which the value of its resistance cannot change.

Carbon film resistors

The physical size of the different resistors is as follows.

ROUGH SIZE
Rating power Thickness Length
From the top of the photograph (W) (mm) (mm)
1/8 2 3
1/8W
1/4W 1/4 2 6
1/2W
1/2 3 9

This is the most general purpose, cheap resistor. Usually the tolerance of the
resistance value is ±5%. Power ratings of 1/8W, 1/4W and 1/2W are frequently used.
Carbon film resistors have a disadvantage; they tend to be electrically noisy. Metal film
resistors are recommended for use in analog circuits
.

This resistor is called a Single-In-Line (SIL) resistor network. It is made with many
resistors of the same value, all in one package. One side of each resistor is connected with
one side of all the other resistors inside.

IWIZ Learners Institute of Technical education Pvt Ltd 10


Embedded Primitive Level

b) Variable Resistors

There are two general ways in which variable resistors are used. One is the variable
resistor which value is easily changed, like the volume adjustment of Radio. The other is
semi-fixed resistor that is not meant to be adjusted by anyone but a technician. It is used to
adjust the operating condition of the circuit by the technician. Semi-fixed resistors are used to
compensate for the inaccuracies of the resistors, and to fine-tune a circuit. The rotation angle
of the variable resistor is usually about 300 degrees. Some variable resistors must be turned
many times to use the whole range of resistance they offer. This allows for very precise
adjustments of their value. These are called "Potentiometers" or "Trimmer Potentiometers."

The variable resistor typically used for volume controls can be seen on the far right. Its
value is very easy to adjust. The four resistors at the center of the photograph are the semi-
fixed type. These ones are mounted on the printed circuit board.

The two resistors on the left are the trimmer potentiometers.

This symbol is used to indicate a variable resistor in a circuit diagram.

1.3 CAPACITOR

1.3.1 Introduction

Definition: Capacitor is a component ,having an electrolyte between the two plates. A


thin layer of oxide is deposited only on the positive plate. The oxide acts as the dielectric for
the capacitor. Electrolytic capacitors are polarized and must be connected in correct polarity
to prevent breakdown.

The capacitor's function is to store electricity, or electrical energy. The capacitor also
functions as a filter, passing alternating current (AC) and blocking direct current (DC).
This symbol is used to indicate a capacitor in a circuit diagram.

The capacitor is constructed with two electrode plates facing each other, but separated
by an insulator. When DC voltage is applied to the capacitor an electric charge is stored on
each electrode. While the capacitor is charging up current flows. The current will stop
flowing when the capacitor has fully charged. The value of a capacitor (the capacitance) is
designated in units called the Farad (F).

IWIZ Learners Institute of Technical education Pvt Ltd 11


Embedded Primitive Level

1.3.2 Types of capacitors

a) Electrolytic Capacitors

Aluminum is used for the electrodes by using a thin oxidization membrane. Large
values of capacitance can obtained in comparison with the size of the capacitor, because the
dielectric used is very thin. The most important characteristic of electrolytic capacitors is that
they have polarity. They have a positive and a negative electrode [Polarized]. This means that
it is very important in which way round they are connected. If the capacitor is subject to
voltage exceeding its working voltage, or if it has connected with incorrect polarity, it may
burst. It is extremely dangerous, because it can quite literally explode. Make absolutely no
mistakes. Generally, in the circuit diagram, the positive side is indicated by a "+" (plus)
symbol. Electrolytic capacitors range in value from about 1µF to thousands of µF. These
types of capacitors are use as a ripple filter in a power supply circuit, or as a filter to bypass
low frequency signals, etc. Because this type of capacitor is comparatively similar to the
nature of a coil in construction, it is not possible to use for high-frequency circuits.

b) Ceramic Capacitors

Ceramic capacitors are constructed with materials such as titanium


acid, barium which are used as the dielectric. Internally, these capacitors are
not constructed as a coil, so they can be used in high frequency applications.
Typically, they are used in circuits, which bypass high frequency signals to
ground. These capacitors have the shape of a disk. Their capacitance is
comparatively small. The capacitor on the left of the photograph is a 100pF
capacitor with a diameter of about 3 mm. The capacitor on the right side is
printed with 103, so 10 x 103pF becomes 0.01 µF. The diameter of the disk is about six mm.
Ceramic capacitors have no polarity. Ceramic capacitors should not be use for analog
circuits, because they can distort the signal.

c) Variable Capacitors

Variable capacitors are used for adjustment etc. of frequency


mainly. On the left in the photograph is a "trimmer," which uses
ceramic as the dielectric. Next to it on the right is one that uses
polyester film for the dielectric. The pictured components are meant
to be mounted on a printed circuit board.

IWIZ Learners Institute of Technical education Pvt Ltd 12


Embedded Primitive Level

When adjusting the value of a variable capacitor, it is advisable to be careful.

One of the component's lead is connected to the adjustment screw of the capacitor.
This means that the value of the capacitor can be affected by the capacitance of the
screwdriver in your hand. It is better to use a special screwdriver to adjust these components.

1.4 DIODES

1.4.1 Introduction

In electronics, a diode is a two-terminal device (except that harmonic diodes may also
have one or two ancillary terminals for a heater). Diodes have two active electrodes between
which the signal of interest may flow, and most of them are used for their unidirectional
current property. The varicap diode is used as an electrically adjustable capacitor.

The directionality of current flow which most diodes exhibit is sometimes generically
called the rectifying property. The most common function of a diode is to allow an electric
current to pass in one direction (called the forward biased condition) and to block it in the
opposite direction (the reverse biased condition). Thus the diode can be thought of as an
electronic version of a check valve. Real diodes do not display such a perfect on-off
directionality but have a more complex non-linear electrical characteristic, which depends on
the particular type of diode technology. Diodes also have many other functions in which they
are not designed to operate in this on-off manner.
This symbol is used to indicate a diode in a circuit diagram. The meaning of the
symbol is (Anode) (Cathode).Current flows from the anode side to the cathode side.

1.4.2 Types of Diodes

a) Light Emitting Diode (Led)

Light emitting diodes must be chosen according to how they will be used, because
there are various kinds. The diodes are available in several colors. The most common colors
are red and green, but there are even blue ones. The device on the far right in the photograph
combines a red LED and green LED in one package. The component lead in the middle is
common to both LEDs. As for the remaining two leads, one side is for the green, the other for
the red LED. When both are turned on simultaneously, it becomes orange.

When an LED is new out of the package, the polarity of the device can be determined
by looking at the leads. The longer lead is the Anode side, and the short one is the Cathode

IWIZ Learners Institute of Technical education Pvt Ltd 13


Embedded Primitive Level

side. The polarity of an LED can also be determined using a resistance meter, or even a 1.5 V
battery.

When using a test meter to determine polarity, set the meter to a low resistance
measurement range. Connect the probes of the meter to the LED. If the polarity is correct, the
LED will glow. If the LED does not glow, switch the meter probes to the opposite leads on
the LED.

1.5. TRANSISTOR

1.5.1 Introduction

The transistor's function is to amplify an electric current. Many different kinds of


transistors are used in analog circuits, for different reasons. This is not the case for digital
circuits. In a digital circuit, only two values matter; on or off. The amplification ability of a
transistor is not relevant in a digital circuit. In many cases, a circuit is built with integrated
circuits(ICs).
Transistors are often used in digital circuits as buffers to protect ICs. For
example, when powering an electromagnetic switch (called a 'relay'), or when controlling a
light emitting diode.

Two different symbols are used for the transistor.

PNP Type NPN Type

1.5.2 Commercial Type of Transistors

a) SL100

Bipolar transistors are composed of three segments called "Collector," "Base," and
"Emitter," and there is a thin insulating layer between Base and Emitter. If a voltage of the
correct polarity is applied to the Base and Emitter terminals, the insulating layer becomes so
thin that it behaves as a conductor. If this voltage polarity is reversed, the insulating layer
becomes wide. By changing the thickness of this insulating layer, the BJT behaves as a
voltage-controlled valve or switch. Whenever the Base-Emitter voltage is causing the
insulator layer to become thinner, there occurs a leakage current in the base terminal. This
tiny current is proportional to any larger current passing through the entire transistor.
Although the BJT is controlled by the voltage between Base and Emitter, designers usually
ignore the base-emitter voltage, and the BJT is treated as a current-controlled valve or switch.

IWIZ Learners Institute of Technical education Pvt Ltd 14


Embedded Primitive Level

All transistors are made of a "doped" semiconductor, typically silicon. Pure silicon
contains few movable charges, so it behaves as an insulator. In the silicon crystal impurities
are deliberately introduced during manufacturing process. Each impurity atom will produce a
movable charged particle in the silicon, which changes the silicon into a conductor. Doped
silicon is very different than metal conductors. The charges within metals behave like a dense
liquid, while the charges in doped silicon behave as a highly compressible gas. Doped
semiconductor is a special kind of conductor where an applied voltage can easily "compress"
or sweep the charges away. By sweeping the charges away, the semiconductor is changed
from a conductor to an insulator. Semiconductors are like electric switches, but with no
moving parts.

1.6. INTEGRATED CIRCUITS

1.6.1 Introduction

An integrated circuit contains transistors, capacitors, resistors and other parts packed
with high density on one chip. Although the function is similar to a circuit made with
separate components.The internal structure of the components are different in an integrated
circuit. The transistors, resistors, and capacitors are formed very small, and in high density on
a foundation of silicon. They are formed by a variation of printing technology. There are
different kind of ICs, including special use ICs.

There are lot of IC packages. They are DIP (Dual In - line Package), SOP (Smart
Outline Package) etc. The most commonly used package is DIP. The following figure shows
the typical value of IC, Pin diagram, Operating voltage and Operating temperature and
Operating Current.

1.6.2 Types of IC’s

Specifications
Name Function Vcc Pin Assign(Top View)

NE555 Timer +4.5 Max frequency:


to 500kHz
+16V Temperature drift:
0.005%/°C.
Max output current:
200mA.
Delay time setting
:several micro sec to
several hours
LM386N- Low +4 to Max output: 660mW
1 frequency 12V Load: 8 to 32-ohm
electric Waiting current: 4mA
power
amplifier

IWIZ Learners Institute of Technical education Pvt Ltd 15


Embedded Primitive Level

LM386N- Low +5 to Max output: 1.25W


4 frequency 18V Load: 8 to 32-ohm
electric Waiting current: 4mA
power
amplifier

IC 78L05 & IC 7805

Three Terminal Voltage Regulators


On the left of photograph is a 78L05. The size and form is similar to a 2SC1815 transistor.
The output voltage is +5V, and the maximum output current is about 100mA.
The maximum input voltage is +35V. (Differs by manufacturer.)

On the right is a 7805. The output voltage is +5V, and maximum output current is 500mA to
1A. (It depends on the heat sink used)
The maximum input voltage is also +35V.

ADC 0809

IWIZ Learners Institute of Technical education Pvt Ltd 16


Embedded Primitive Level

Pin Number Description


1 IN3 - Analog Input 3
2 IN4 - Analog Input 4
3 IN5 - Analog Input 5
4 IN6 - Analog Input 6
5 IN7 - Analog Input 7
6 START - Start Conversion
7 EOC - End Of Conversion
8 2(-5) - Tri-State Output Bit 5
9 OUT EN - Output Enable
10 CLK - Clock
11 Vcc - Positive Supply
12 Vref+ - Positive Voltage Reference Input
13 GND - Ground
14 2(-7) - Tri-State Output Bit 7
15 2(-6) - Tri-State Output Bit 6
16 Vref- - Voltage Reference Negative Input
17 2(-8) - Tri-State Output Bit 8
18 2(-4) - Tri-State Output Bit 4
19 2(-3) - Tri-State Output Bit 3
20 2(-2) - Tri-State Output Bit 2
21 2(-1) - Tri-State Output Bit 1
22 ALE - Address Latch Enable
23 ADD C - Address Input C
24 ADD B - Address Input B
25 ADD A - Address Input A
26 IN0 - Analog Input 0
27 IN1 - Analog Input 1
28 IN2 - Analog Input 2

1.7 RELAY

1.7.1 Introduction

A relay is an electrical switch that opens and closes under the control of another electrical
circuit. In the original form, the switch is operated by an electromagnet to open or close one
or many sets of contacts. It was invented by Joseph Henry in 1835. Because a relay is able to

IWIZ Learners Institute of Technical education Pvt Ltd 17


Embedded Primitive Level

control an output circuit of higher power than the input circuit, it can be considered to be, in a
broad sense, a form of an electrical amplifier.

• DPDT - Double Pole Double Throw. These have two rows of change-over terminals.
Equivalent to two SPDT switches or relays actuated by a single coil. Such a relay has
eight terminals, including the coil.

1.7.2 Application

Relays are used:

• to control a high-voltage circuit with a low-voltage signal, as in some types of


modems
• to control a high-current circuit with a low-current signal, as in the starter solenoid
of an automobile
• to detect and isolate faults on transmission and distribution lines by opening and
closing circuit breakers (protection relays)

A DPDT AC coil relay with "ice cube" packaging.


1.7.3 Operation
A) Driving relays using NPN transistor

NPN Relay Driver Circuit

The above figure shows the relay controlling method using NPN transistor. Here we
are applying 12V supply at one end of the relay coil. Other end of the relay coil is connected
with transistor collector. When input of the transistor base is low, the collector output is high.
During that period the relay will be in OFF condition. If transistor base is high, the collector
output is low. The relay is energized and then the relay will be in ON condition.

IWIZ Learners Institute of Technical education Pvt Ltd 18


Embedded Primitive Level

B) Driving relays using PNP transistor

PNP Relay Driver Circuit

The relay controlling method using PNP transistor is shown in above figure. The free
wheeling diode is connected across the relay coil. It is used to protect the circuit from return
voltage in relay coil.

C) Driving relays using ULN 2003

The above figure shows the relay driver using ULN 2003. The input pins from 1 to 7
are connected with microcontroller. Output pins are connected with relay coil. If input is high
the output will be low. Therefore the relay is energized. If input pins are low the output will
be high.

IWIZ Learners Institute of Technical education Pvt Ltd 19


Embedded Primitive Level

1.8 RF-TRANSCEIVER

1.8.1 RF-TRANSMITTER

Introduction

TWS-434 and RWS-434 are extremely small, and are excellent for applications
requiring short-range RF remote controls. The transmitter module is only 1/3 the size of a
standard postage stamp, and can easily be placed inside a small plastic enclosure.

Types of Transmitter

a) TWS-434

The transmitter output is up to 8mW at 433.92MHz with a range of approximately


400 foot (open area) outdoors.In Indoors, the range is approximately 200 foot, and will go
through most walls.

b) TWS-434A

The TWS-434 transmitter accepts both linear and digital inputs can operate from 1.5
to 12 Volts-DC, and makes building a miniature hand-held RF transmitter very easy. The
TWS-434 is approximately the size of a standard postage stamp.

IWIZ Learners Institute of Technical education Pvt Ltd 20


Embedded Primitive Level

Sample Transmitter Circuit

Sample Transmitter circuit:

The sample transmitter circuit is shown in above. We can choose any one from 00 to
FF as the address line. The TE pin must be low while transmitting the RF signal. HT 12E has
4 bit data line.

1.8.2 RF Receiver

Rws-434

The receiver also operates at 433.92MHz, and has a sensitivity of 3uV. The RWS-
434 receiver operates from 4.5 to 5.5 volts-DC, and has both linear and digital outputs.

RWS-434 Receiver

IWIZ Learners Institute of Technical education Pvt Ltd 21


Embedded Primitive Level

RWS-434 Pin Diagram

Note: For maximum range, the recommended antenna should be approximately 35cm long.
To convert from centimeters to inches -- multiply by 0.3937. For 35cm, the length in inches
will be approximately 35cm x 0.3937 = 13.7795 inches long. We tested these modules using
a 14", solid, 24 gauge hobby type wire, and reached a range of over 400 foot.

Your results may vary depending on your surroundings.

Sample Receiver Circuit

IWIZ Learners Institute of Technical education Pvt Ltd 22


Embedded Primitive Level

Description

Here we are using HT12 D decoder. It has 8 bit address line and 4 bit data line. The
data line is connected with the microcontroller. The VT (Valid Transmission) will be set
when transmitting the RF signal. The 8 bit address line must be same as the address line on
the encoder.

Summary

 The electronic elements can be classified into active and passive elements.

 A fixed resistor is one in which the value of its resistance cannot change.

 A variable resistor is one in which the value of its resistance can change.

 Rectifier and clipper are the application of diode.

 Relay is an automatic switch. The transistor switching circuit is used to

control the relay.

 HT12E and HT12D have 8 bit address line and 4 bit data line.

 The address line of the encoder and decoder must be same.

 The TE pin on the encoder should be low when transmitting the signal.

Technical Questions

1. Give some example for active and passive elements?

2. What are the materials used in diodes?

3. What is the cut in voltage of silicon diode?

4. What is the cut in voltage of germanium diode?

5. Describe the function of relay?

6. What is the use of encoder and decoder?

IWIZ Learners Institute of Technical education Pvt Ltd 23


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 24


Embedded Primitive Level

CHAPTER 2
FUNDAMENTAL CONCEPT OF C

About this chapter

 We have to briefly discuss about the Basic Essential Concepts in C Language such
as some important concepts of this language.
 There are Data Types, Variables, Operators, Statements, Arrays, Strings, Pointers
and Linked List.

After this chapter

 You have to work with some Sample Examples of the above events.
 We have to work with all the events in separate example.

2.1 INTRODUCTION

C Programming/Why learns C?

C is the most commonly used programming language for writing operating systems.
UNIX was the first operating system written in C. Later Microsoft Windows, Mac OS X, and
GNU/Linux were all written in C. Operating systems run directly on top of the hardware --
there is no lower layer to mediate their requests with the except of the C compiler, which is
assembly language.

Not only is C the language of operating systems, it is the precursor and inspiration for
almost all of the most popular high-level languages available today. In fact, Perl, PHP,
Python, and Ruby are all written in C!

By way of analogy, let's say that you were going to be learning Spanish, Italian,
French, or English. Do you think knowing Latin would be helpful? In the same way, knowing
C will enable you to understand and appreciate an entire family of programming languages
built upon the traditions of C. Knowledge of C enables freedom.

Why C, and not assembly language?

Because Assembly language, while extremely powerful, is simply too difficult to


program large applications, and hard to read or interpret in a logical way. Assembly language
can be directly converted into binary with no compilation, assembly is instead 'linked'
together, meaning the individual source files are all put into one file and converted to binary.
C also gives the programmer the ability to program in assembly right inside the C-code,
giving programmers the option to optimize a very important or heavily used piece of code in
Assembly.

IWIZ Learners Institute of Technical education Pvt Ltd 25


Embedded Primitive Level

2.2 C KEYWORDS

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

2.3 DATA TYPE

The definition of a variable will assign storage for the variable and define the type of
data that will be held in the location.

int float double char void enum

Int - data type


Int is used to define integer numbers.

{
int Count;
Count = 5;
}

Float - data type


Float is used to define floating point numbers.

{
float Miles;
Miles = 5.6;
}

IWIZ Learners Institute of Technical education Pvt Ltd 26


Embedded Primitive Level

Double - data type


Double is used to define BIG floating point numbers. It reserves twice the storage for the

{
double Atoms;
Atoms = 2500000;
}

Char - data type


Char defines characters.

{
char Letter;
Letter = 'x';
}

Type Bytes Bits Range

short int 2 16 -32,768 -> +32,767 (32kb)


unsigned short int 2 16 0 -> +65,535 (64Kb)
unsigned int 4 32 0 -> +4,294,967,295 ( 4Gb)
int 4 32 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
long int 4 32 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
signed char 1 8 -128 -> +127
unsigned char 1 8 0 -> +255
float 4 32
double 8 64
long double 12 96

2.4 VARIABLES

A variable may be defined using any uppercase or lowercase character, a numerical


digit (0 through 9), and the underscore character (_). The first character of the variable may
not be a numerical digit or underscore. Variable names are case sensitive.

The scope of the variable (where it can be used), is determined by where it is defined.
If it is defined outside any block or list of parameters, then it has file scope. This means it
may be accessed anywhere in the current source code file. This is normally called a global
variable and is normally defined at the top of the source code. All other types of variables are
local variables. If a variable is defined in a block (encapsulated with {and}), then its scope
begins when the variable is defined and ends when it hits the terminating}. This is called

IWIZ Learners Institute of Technical education Pvt Ltd 27


Embedded Primitive Level

block scope. If the variable is defined in a function prototype, then the variable may only be
accessed in that function. This is called function prototype scope.

Access to variables outside of their file scope can be made by using linkage. Linkage
is done by placing the keyword extern prior to a variable declaration. This allows a variable
that is defined in another source code file to be accessed.

Variables defined within a function scope have automatic storage duration. The life of
the variable is determined by the life of the function. Space is allocated at the beginning of
the function and terminated at the end of the function. Static storage duration can be obtained
by placing the keyword static in front of the variable declaration. This causes the variable's
space to be allocated when the program starts up and is kept during the life of the program.
The value of the variable is preserved during subsequent calls to the function that defines it.
Variables with file scope are automatically static variables.

A variable is defined by the following:

2.4.1 Extern

Indicates that the variable is defined outside of the current file. This brings the
variables scope into the current scope. No variable is actually created by this.

2.4.2 Static

Causes a variable that is defined within a function to be preserved in subsequent calls


to the function.

2.4.3 Auto

Causes a local variable to have a local lifetime (default).

2.4.4 Register

Requests that the variable be accessed as quickly as possible. This request is not
guaranteed. Normally, the variable's value is kept within a CPU register for maximum speed.

2.5 CONSTANT

The const keyword is used to create a read only variable. Once initialized, the value
of the variable cannot be changed but can be used just like any other variable.

Const syntax

main()
{ const float pi = 3.14;
}

IWIZ Learners Institute of Technical education Pvt Ltd 28


Embedded Primitive Level

The const keyword is used as a qualifier to the following data types - int float char double
struct.

const int degrees = 360;


const float pi = 3.14;
const char quit = 'q';

2.6 OPERATORS

Operators are used with operands to build expressions. For example the following
is an expression containing two operands and one operator.

4+5

C contains the following operator groups.

 Arithmetic - Assignment - Logical/relational - Bitwise - Odds and ends! - Operator


and precedence table.

The order (precedence) that operators are evaluated can be seen here.

2.6.1 Arithmetic:
+
-
/
*
% Modulo
-- Decrement (post and pre)
++ Increment (post and pre)

2.6.2 Assignment
These all perform an arithmetic operation on the lvalue and assign the result to the
lvalue. So what does this mean in English? Here is an example:
Counter = counter + 1;
Can be reduced to
Counter += 1;
Here is the full set.
=
*= Multiply
/= Divide.
%= Modulus.
+= add.
-= Subtract.
<<= left shift.
>>= Right shift.
&= Bitwise AND.
^= bitwise exclusive OR (XOR).
|= bitwise inclusive OR.

IWIZ Learners Institute of Technical education Pvt Ltd 29


Embedded Primitive Level

2.6.3 Logical/Relational

== Equal to
!= Not equal to
>
<
>=
<=
&& Logical AND
|| Logical OR
! Logical NOT

2.6.4 Bitwise
& AND (Binary operator)
| Inclusive OR
^ Exclusive OR
<< Shift left. C ++ use of <<
>> shift right. C ++ use of >>
~ one's complement
Sizeof () size of objects and data types.
Strlen may also be of interest.
& Address of (Unary operator)

2.7 STATEMENTS

Control Structures

There are two types of Control Structure statements used in the C Language.
 Conditional Statements
• Decision Control Structures
• Loop Control Structures
 Unconditional Statements

Control Statements

This type of Control Statements is used to execute the set of statements by


the particular condition it will be performed.

Decision Control Structure

Decision Control Structure is used to execute the set of conditions. If the condition will
be true the first statement is executed otherwise the else block statement will be executed.
There are two styles of Control Statements are used in this Decision Structure.
Single Way Statement
Multi Way Statement

IWIZ Learners Institute of Technical education Pvt Ltd 30


Embedded Primitive Level

Single Way Statement

2.7.1. If Statement

If statement evaluates an expression. If that expression is true, then a statement is


executed. If an else clause is given and if the expression is false, then the else's statement is
executed.
Syntax:
If (expression) statement1;

Or

If (expression) statement1;
Else statement2;

2.7.2. IF Else Statement

If (loop<3) counter++;

If(x==y)
X++;
Else
Y++;

If (z>x)
{
z=5;
x=3;
}
Else
{
z=3;
x=5;
}

IWIZ Learners Institute of Technical education Pvt Ltd 31


Embedded Primitive Level

2.8 MULTI WAY STATEMENTS

2.8.1. Switch

A switch statement allows a single variable to be compared with several possible


constants. If the variable matches one of the constants, then an execution jump is made to that
point. A constant can not appear more than once and there can only be one default
expression.

Syntax:
Switch (variable)
{
Case const:
Statements...;
Default:
Statements...;
}

Examples
Switch (Betty)
{
Case 1:
Printf ("Betty=1\n");
Case 2:
Printf ("Betty=2\n");
Break;
Case 3:
Printf ("Betty=3\n");
Break;
Default:
Printf ("Not sure.\n");

2.9 LOOP CONTROL STRUCTURE

2.9.1. While Statement


The while statement provides an iterative loop.
Syntax:
While (expression) statement...
Statement is executed repeatedly as long as expression is true. The test on expression takes
place before each execution of statement.

Examples

While (*pointer! ='j') pointer++;

While (counter<5)
{
Printf ("counter=%I”, counter);
Counter++;
}

IWIZ Learners Institute of Technical education Pvt Ltd 32


Embedded Primitive Level

2.9.2. for Statement

For statement allows for a controlled loop.

Syntax:
For (expression1; expression2; expression3) statement...
Expression1 is evaluated before the first iteration. After each iteration, expression 3 is
evaluated. Both expression1 and expression3 may be omitted. If expression2 is omitted, it is
assumed to be 1. Statement is executed repeatedly until the value of expression2 is 0. The test
on expression2 occurs before each execution of statement.

Examples
For (loop=0; loop<1000; loop++)
Printf ("%i\n", loop);
Prints numbers 0 through 999.
For(x=3, y=5; x<100+y; x++, y--)
{
Printf ("%i\n", x);
Some function ();
}
Prints numbers 3 through 53. Some function is called 51 times.

2.9.3 .Do Statement

The do...while construct provides an iterative loop.

Syntax

Do statements... while (expression?)


Statement is executed repeatedly as long as expression is true. The test on expression takes
place after each execution of statement.

Examples
do {
betty++;
printf ("%i", betty);
} while (betty<100);

2.10 UNCONDITIONAL STATEMENT

This Unconditional Statements refers to executes the

2.10.1. Goto

The goto statement transfers program execution to some label within the program.

Syntax
Goto label;
....
Label:

IWIZ Learners Institute of Technical education Pvt Ltd 33


Embedded Primitive Level

Examples
goto skip_point;
printf ("This part was skipped.\n");
skip_point:
printf ("Hi there! \n");
Only the text "Hi there!" is printed.

2.10.2. Continue

The continue statement can only appear in a loop body. It causes the rest of the
statement body in the loop to be skipped.

Syntax

Continue;
Examples:
For (loop=0; loop<100; loop++)
{
if (loop==50)
Continue;
Printf ("%i\n", loop);
}
The numbers 0 through 99 are printed except for 50.
Joe=0;
While (Joe<1000)
{
For (zip=0; zip<100; zip++)
{
If (Joe==500)
Continue;
Printf ("%i\n", joe);
}
Joe++;
}
Each number from 0 to 999 is printed 100 times except for the number 500 which is not
printed at all.

2.10.3. Break

The break statement can only appear in a switch body or a loop body. It causes the
execution of the current enclosing switch or loop body to terminate.

Syntax
Break;

Examples
Switch (Henry)
{
Case 1: print ("Hi! \n");
Break;

IWIZ Learners Institute of Technical education Pvt Ltd 34


Embedded Primitive Level

Case 2: break;
}
If Henry is equal to 2, nothing happens.
For (loop=0; loop<50; loop++)
{
If (loops==10)
Break;
Printf ("%i\n", loop);
}
Only numbers 0 through 9 are printed.

2.10.4. Return

The return statement causes the current function to terminate. It can return a value to
the calling function. A return statement can not appear in a function whose return type is
void. If the value returned has a type different from that of the function's return type, then the
value is converted. Using the return statement without an expression creates an undefined
result. Reaching at the end of the function is the same as returning without an expression.

Syntax
Return expression;

Examples

int alike (int x, int y)


{
If(x<y)
Return (1);
Else
Return (0);
}

2.11 MEMORY FUNCTIONS

2.11.1 Calloc

Declaration:
Void *calloc (size_t nitems, size_t size);
Allocates the requested memory and returns a pointer to it. The requested size is
nitems each size bytes long (total memory requested is nitems*size). The space is initialized
to all zero bits. On success a pointer to the requested space is returned. On failure a null
pointer is returned.

IWIZ Learners Institute of Technical education Pvt Ltd 35


Embedded Primitive Level

2.11.2. Free

Declaration

Void free (void *ptr);

Deallocates the memory previously allocated by a call to calloc, malloc, or realloc.


The argument ptr points to the space that was previously allocated. If ptr points to a memory
block that was not allocated with calloc, malloc, or realloc, or is a space that has been
deallocated, then the result is undefined.

2.11.3. Malloc

Declaration

Void *malloc (size_t size);


Allocates the requested memory and returns a pointer to it. The requested size is size
bytes. The value of the space is indeterminate.
On success a pointer to the requested space is returned. On failure a null pointer is returned.

2.11.4 .Realloc

Declaration

Void *realloc (void *ptr, size_t size);

Attempts to resize the memory block pointed to by ptr that was previously allocated
with a call to malloc or calloc. The contents pointed to by ptr are unchanged. If the value of
size is greater than the previous size of the block, then the additional bytes have an
indeterminate value. If the value of size is less than the previous size of the block, then the
difference of bytes at the end of the block are freed. If ptr is null, then it behaves like malloc.
If ptr points to a memory block that was not allocated with calloc or malloc, or is a space that
has been deallocated, then the result is undefined. If the new space cannot be allocated, then
the contents pointed to by ptr are unchanged. If size is zero, then the memory block is
completely freed. On success a pointer to the memory block is returned (which may be in a
different location as before). On failure or if size is zero, a null pointer is returned.

2.12 STRING

2.12.1. Strlen ()

Declaration
Size_t strlen (const char *STR);
Computes the length of the string STR up to but not including the terminating null
character.
Returns the number of characters in the string.

2.12.2 Strncpy ()

IWIZ Learners Institute of Technical education Pvt Ltd 36


Embedded Primitive Level

Declaration
Char *strcpy (char *str1, const char *str2);
Copies the string pointed to by str2 to str1. Copies up to and including the null
character of str2. If str1 and str2 overlap the behavior is undefined.
Returns the argument str1.

2.12.3 Strcmp ()

Declaration
Int strcmp (const char *str1, const char *str2);
Compares the string pointed to by str1 to the string pointed to by str2.
Returns zero if str1 and str2 are equal. Returns less than zero or greater than zero if
str1 is less than or greater than str2 respectively.

2.12.4 Strcat ()

Declaration
Char *strncat (char *str1, const char *str2, size_t n);
Appends the string pointed to by str2 to the end of the string pointed to by str1 up to n
characters long. The terminating null character of str1 is overwritten. Copying stops once n
characters are copied or the terminating null character of str2 is copied. A terminating null
character is always appended to str1. If overlapping occurs, the result is undefined.
The argument str1 is returned.

2.13 ARRAYS

2.13.1 Array declaration


Arrays are used in C to represent structures of consecutive elements of the same type.
The declaration of a (fixed-size) array has the following syntax:

Int array [100];

2.13.2 Accessing elements


The primary facility for accessing the values of the elements of an array is the array
subscript operator. To access the i-indexed element of array, the syntax would be array[i],
which refers to the value stored in that array element.

Array subscript numbering begins at 0. The largest allowed array subscript is


therefore equal to the number of elements in the array minus 1. To illustrate this, consider an
array a declared as having 10 elements; the first element would be a [0] and the last element
would be a [9].

C provides no facility for automatic bounds checking for array usage. Though
logically the last subscript in an array of 10 elements would be 9, subscripts 10, 11, and so
forth could accidentally be specified, with undefined results.

IWIZ Learners Institute of Technical education Pvt Ltd 37


Embedded Primitive Level

Due to array↔pointer interchangeability, the addresses of each of the array elements


can be expressed in equivalent pointer arithmetic. The following table illustrates both
methods for the existing array:

Array subscripts vs. pointer arithmetic


Element
0 1 2 n
index
Array
array[0] array[1] array[2] array[n]
subscript
Dereference
*array *(array + 1) *(array + 2) *(array + n)
pointer

2.13.3 Dynamic arrays


Recall that a constant is required for the dimension in a declaration of a static array.
Often we would prefer to determine the array length as a run-time variable:

Int a[n];
A [3] = 10;

This behavior can be imitated with the help of the C standard library. The malloc
function provides a simple method for allocating memory. It takes one parameter: the amount
of memory to allocate in bytes. Upon successful allocation, malloc returns a generic (void *)
pointer value, pointing to the beginning of the allocated space. The pointer value returned is
converted to an appropriate type implicitly by assignment. If the allocation could not be
completed, malloc returns a null pointer. The following segment is therefore similar in
function to the above desired declaration:

#include <stdlib.h> /* declares malloc */



Int *a;
a = malloc (n * sizeof (int));
a [3] = 10;

The result is a "pointer to int" variable (a) that points to the first of n contiguous int
objects; due to array↔pointer equivalence this can be used in place of an actual array name,
as shown in the last line. The advantage in using this dynamic allocation is that the amount of
memory that is allocated to it can be limited to what is actually needed at run time, and this
can be changed as needed (using the standard library function realloc).

When the dynamically-allocated memory is no longer needed, it should be released


back to the run-time system. This is done with a call to the free function. It takes a single
parameter: a pointer to previously allocated memory. This is the value that was returned by
the call to malloc. It is considered good practice to then set the pointer variable to NULL so that
further attempts to access the memory to which it points will fail. If this is not done, errors in
the code (or manipulations by an attacker) might be very hard to detect and lead to obscure
and potentially dangerous malfunction caused by memory corruption.

IWIZ Learners Institute of Technical education Pvt Ltd 38


Embedded Primitive Level

Free (a);
a = NULL;

Standard C also supports variable-length arrays with block scope. Such arrays
variables are allocated based on the value of an integer value at runtime upon entry to a
block, and are deallocated at the end of the block.

Float read_and_process (int sz)


{
Float Vals [sz]; // VLA, size determined at runtime

For (int i = 0; i < so; i++)


Vals[i] = read value ();
Return process (vales, so);
}

2.13.4 Multidimensional arrays


In addition, C supports arrays of multiple dimensions, which are stored in row-major
order. Technically, C multidimensional arrays are just one-dimensional arrays whose
elements are arrays. The syntax for declaring multidimensional arrays is as follows:

Int array2d [ROWS] [COLUMNS];

(Where ROWS and COLUMNS are constants); this defines a two-dimensional array.
Reading the subscripts from left to right, array2d is an array of length ROWS, each element of
which is an array of COLUMNS nits.

To access an integer element in this multidimensional array, one would use

array2d [4] [3]

2.14 FUNCTION

2.14.1 Call by value


#include <stdio.h>
Int main (void)
{
Int i = 1, j = 2;
Void exchange (int, int);

Printf ("main : i = %d j = %d\n", i, j);


Exchange (i, j);
Printf ("main : i = %d j = %d\n", i, j);
Return 0;
}
Void exchange (int i, int j)
{
Int t;

IWIZ Learners Institute of Technical education Pvt Ltd 39


Embedded Primitive Level

t = i, i = j, j = t;
Printf ("exchange: i = %d j = %d\n", i, j);
}
The following output is produced
Main : i = 1 j = 2
Exchange: i = 2 j = 1
Main : i = 1 j = 2

2.14.2 Call-by-reference parameters

Values cannot be returned to the calling program via call-by-value parameters


because the function only operates on a copy of the value of the parameters, not on the actual
parameter itself. If it is required to return a value by a parameter then the address of the actual
parameter used in the function call must be passed to the function. The function can then use
this address to access the actual parameter in its own space in the calling program and change
it if required. Thus what we are passing is a reference to the parameter. Hence call-by-
reference parameters.

C programming this is the key difference between passing by reference and passing
by value. If we pass the variables normally, they will be passed by value: a copy of the
variable's assigned content will be passed to the function as a constant. This means that it can
not be changed.

However, if we pass the variables by reference, then only a reference to the memory
where the variable is stored is passed to the function. Using this reference, the function is able
to modify the contents of the variable.

Void Swap Integers (int & a, int & b)

2.14.3 Recursive Functions

A recursive function is one which calls itself. This is another complicated idea which
you are unlikely to meet frequently. We shall provide some examples to illustrate recursive
functions.

Recursive functions are useful in evaluating certain types of mathematical function.


You may also encounter certain dynamic data structures such as linked lists or binary trees.
Recursion is a very useful way of creating and accessing these structures.

Int fib (int num)

/* Fibonacci value of a number */


{ Switch (num) {
Case 0:
Return (0);
Break;
Case 1:
Return (1);
Break;
Default: /* including recursive calls */

IWIZ Learners Institute of Technical education Pvt Ltd 40


Embedded Primitive Level

Return (fib (num - 1) + fib (num - 2));


Break;
}
}

2.15 POINTER

A pointer is a variable which contains the address in memory of another variable.


We can have a pointer to any variable type.

2.15.1 Pointers to Functions

#include <stdio.h>
int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
Void bubble (int a [], int N);
Int main (void)
{
Int i;
Put char ('\n');
For (i = 0; i < 10; i++)
{
Printf ("%d ", arr[i]);
}
Bubble (arr, 10);
Put char ('\n');

For (i = 0; i < 10; i++)


{
Printf ("%d ", arr[i]);
}
Return 0;
}

Void bubble (int a [], int N)


{
Int i, j, t;
For (i = N-1; i >= 0; i--)
{
For (j = 1; j <= i; j++)
{
If (a [j-1] > a[j])
{
t = a [j-1];
A [j-1] = a[j];
A[j] = t;
}
}
}
}

IWIZ Learners Institute of Technical education Pvt Ltd 41


Embedded Primitive Level

2.15.2 Pointers and Strings

Strings are arrays of characters. This is not necessarily true in other languages. In
BASIC, Pascal, FORTRAN and various other languages, a string has its own data type. But
in C it does not. In C a string is an array of characters terminated with a binary zero character
(written as '\0'). To start off our discussion we will write some code which, while preferred
for illustrative purposes, you would probably never write in an actual program. Consider, for
example:

#include <stdio.h>

Char strA [80] = "A string to be used for demonstration purposes";


Char strB [80];

Int main (void)


{

Char *pA; /* a pointer to type character */


Char *Pb; /* another pointer to type character */
Puts (strA); /* show string A */
PA = strA; /* point pA at string A */
Puts (pA); /* show what pA is pointing to */
PB = strB; /* point Pb at string B */
Put char ('\n'); /* move down one line on the screen */
While (*pA! = '\0') /* line A (see text) */
{
*pB++ = *pA++; /* line B (see text) */
}
*Pb = '\0'; /* line C (see text) */
Puts (strB); /* show strB on screen */
Return 0;
}

IWIZ Learners Institute of Technical education Pvt Ltd 42


Embedded Primitive Level

2.15.3 Pointers to Arrays:

We stated that given an array of integers we could point an integer pointer at that array using:

Int *ptr;
Ptr = &my array [0]; /* point our pointer at the first
Integer in our array */

2.16 LINKED LISTS

A linked list is a complex data structure, especially useful in systems or applications


programming. A linked list is comprised of a series of nodes, each node containing a data
element, and a pointer to the next node

A structure which contains a data element and a pointer to the next node is created by,

Struct list {
Int value;
Struct list *next;
};

This defines a new data structure called list (actually the definition of a node), which
contains two members. The first is an integer called value. The second is called next, which is
a pointer to another list structure (or node). Suppose that we declare two structures to be of
the same type as list, e.g.

2.16.1 Single Linked List

The advantage of a single linked list is that it is simple to create, and add/remove
'nodes'. However, its main disadvantage is that it can take a while to add/remove nodes due to
a pointer only able to go one way.

E very linked list needs to have one node that has no value, but just points to the start
of the list we call this the 'Head Node'. The end of the list must always point to NULL this is
good programming behavior and ensures that the program using the list in that method will
be more stable.

2.16.2 Doubly-Linked List

The doubly linked list has one major advantage; it is possible to move a pointer that
reads the list back and forth which saves on time a great deal. However, there is more pointer
bookkeeping involved Instead of changing two pointers in a single linked list, you now have
to change four. The speed in how data is found/added/removed however is still a large step.

IWIZ Learners Institute of Technical education Pvt Ltd 43


Embedded Primitive Level

A visual example of a doubly linked list. Notice there're two nulls, one head, and each node
has two pointers. There's usually a second head pointer called the rear (tail) pointer which
keeps up the other end of the list.

A visual example of adding a node to a doubly linked list. Notice how four pointers
need to be changed. A common mistake in adding an element is changing the pointers in the
wrong order, you want to have the pointers of the node you are adding pointing to its
neighbors first, and then you want its neighbors to point to it.

2.16.3 Circular Linked List

There are two types of circular linked list, single and double. Like its name, the end of
the list points at the beginning so there is no need for null. The advantage about this is that
there is no real end of the list, and you don't have to reset pointers much. However, you have
to keep track of the beginning and end of the list or problems are going to arise in the
program.

Summary:

 From this chapter we learned basic concepts,


 Brief knowledge gathered from structures, functions, linked list, pointers and array.

Technical Question:
1. Write a program for calculating Armstrong Number
2. To write the program for to tests whether a number is prime or not.
3. Performs XOR encryption

Exercise:
1. Reverses a series of numbers by using pointer version
2. Finds the largest and smallest elements in an array
3. Sorts an array of integers using Quick sort algorithm
4. Write a program Recursive Function

IWIZ Learners Institute of Technical education Pvt Ltd 44


Embedded Primitive Level

CHAPTER 3

ADVANCED C

About this Chapter:


 In this chapter we are going to discuss about Command Line Arguments, Type
Casting, File I/O and Variable Argument List.
 And we are also going to discuss about the Header files and Macro Substitutions.

After this Chapter:


 You will have a basic idea about templates and name space standard concepts in c.
 You will have knowledge about advanced File Techniques.

3.1 C-STYLE STRINGS


C-style strings, which are arrays, there are also string literals, such as "this". In reality,
both of these string types are merely just collections of characters sitting next to each other in
memory. The only difference is that you cannot modify string literals, whereas you can
modify arrays. Functions that take a C-style string will be just as happy to accept string
literals unless they modify the string (in which case your program will crash). Some things
that might look like strings are not strings; in particular, a character enclosed in single quotes,
like this, 'a', is not a string. It's a single character, which can be assigned to a specific location
in a string, but which cannot be treated as a string.

To recap: strings are arrays of chars. String literals are words surrounded by double quotation
marks.

"This is a static string"

Remember that special sauce mentioned above? Well, it turns out that C-style strings
are always terminated with a null character, literally a '\0' character (with the value of 0), so
to declare a string of 49 letters, you need to account for it by adding an extra character, so
you would want to say:

char string [50];

This would declare a string with a length of 50 characters. Do not forget that arrays
begin at zero, not 1 for the index number. In addition, we've accounted for the extra with
a null character, literally a '\0' character. It's important to remember that there will be
an extra character on the end on a string, just like there is always a period
at the end of a sentence. Since this string terminator is unprintable, it is not counted as a
letter, but it still takes up a space. Technically, in a fifty char array you could only hold 49
letters and one null character at the end to terminate the string.

Note that something like

IWIZ Learners Institute of Technical education Pvt Ltd 45


Embedded Primitive Level

char *my string;

can also be used as a string. If you have read the tutorial on pointers, you can do something
such as:

array = new char [256];

which allows you to access array just as if it were an array? Keep in mind that to use delete
you must put [] between delete and array to tell it to free all 256 bytes of memory allocated.

For example:

delete [] array.

3.1.1 Using Strings


Strings are useful for holding all types of long input. If you want the user to input his
or her name, you must use a string. Using scanf() to input a string works, but it will terminate
the string after it reads the first space, and moreover, because scanf doesn't know how big the
array is, it can lead to "buffer overflows" when the user inputs a string that is longer than the
size of the string (which acts as an input "buffer").

There are several approaches to handling this problem, but probably the simplest and
safest is to use the fgets function, which is declared in stdio.h.

The prototype for the fgets function is:

char *fgets (char *str, int size, FILE* file);

There are a few new things here. First of all, let's clear up the questions about that
funky FILE* pointer. The reason this exists is because fgets is supposed to be able to read
from any file on disk, not just from the user's keyboard (or other "standard input" device). For
the time being, whenever we call fgets, we'll just pass in a variable called stdin, defined in
stdio.h, which refers to "standard input". This effectively tells the program to read from the
keyboard. The other two arguments to fgets, str and size, are simply the place to store the data
read from the input and the size of the char*, str. Finally, fgets returns str whenever it
successfully read from the input.

For an example

#include <stdio.h>

int main ()
{
/* A nice long string */
char string [256];

IWIZ Learners Institute of Technical education Pvt Ltd 46


Embedded Primitive Level

printf (“Please enter a long string: " );

/* notice stdin being passed in */


Fgets (string, 256, stdin);

Printf (“You entered a very long string, %s", string);

Getchar ();
}
Remember that you are actually passing the address of the array when you pass string
because arrays do not require an address operator (&) to be used to pass their addresses, so
the values in the array string are modified.

The one thing to watch out for ,when using fgets is that it will include the new line
character ('\n') when it reads input unless there isn't room in the string to store it. This means
that you may need to manually remove the input. One way to do this would be to search the
string for a new line and then replace it with the null terminator. What would this look like?
See if you can figure out a way to do it before looking below:

char input [256];


int i;

fgets (input, 256, stdin);

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


{
if (input[i] == '\n’)
{
input[i] = '\0';
break;
}
}

Here, we just loop through the input until we come to a new line, and when we do, we
replace it with the null terminator. Notice that if the input is less than 256 characters long, the
user must have hit enter, which would have included the new line character in the string! (By
the way, aside from this example, there are other approaches to solving this problem that use
functions from String.h.)

3.1.2 Manipulating C strings using String.h

String.h is a header file that contains many functions for manipulating strings. One of
these is the string comparison function.

IWIZ Learners Institute of Technical education Pvt Ltd 47


Embedded Primitive Level

int strcmp (const char *s1, const char *s2);

strcmp will accept two strings. It will return an integer. This integer will either be:

Negative if s1 is less than s2.


Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.

Strcmp performs a case sensitive comparison; if the strings are the same except for a
difference in case, then they're countered as being different. Strcmp also passes the address of
the character array to the function to allow it to be accessed.

char *strcat (char *dest, const char *src);

strcat is short for "string concatenate"; concatenate is a fancy word that means to add
to the end, or append. It adds the second string to the first string. It returns a pointer to the
concatenated string. Beware this function; it assumes that dest is large enough to hold the
entire contents of src as well as its own contents.

char *strcpy (char *dest, const char *src);

strcpy is short for string copy, which means it copies the entire contents of src into
dest. The contents of dest after strcpy will be exactly the same as src such that strcmp (dest,
src) will return 0.

size_t strlen (const char *s);

strlen will return the length of a string, minus the treating character ('\0'). The size_t is
nothing to worry about. Just treat it as an integer that cannot be negative, When fgets actually
reads input from the user, it will read up to size - 1 characters and then place the null
terminator after the last character it read. fgets will read input until it either has no more room
to store the data or until the user hits enter. Notice that fgets may fill up the entire space
allocated for str, but it will never return a non-null terminated string to you.

3.1.3 Safe Programming


The above string functions all rely on the existence of a null terminator at the end of a
string. This isn't always a safe bet. Moreover, some of them, noticeably strcat, rely on the fact
that the destination string can hold the entire string being appended onto the end. Although it
might seem like you'll never make that sort of mistake, historically, problems based on
accidentally writing off the end of an array in a function like strcat, have been a major
problem.

Fortunately, in their infinite wisdom, the designers of C have included functions


designed to help you avoid these issues. Similar to the way that fgets takes the maximum

IWIZ Learners Institute of Technical education Pvt Ltd 48


Embedded Primitive Level

number of characters that fit into the buffer; there are string functions that take an additional
argument to indicate the length of the destination buffer. For instance, the strcpy function has
an analogous strncpy function

char *strncpy (char *dest, const char *src, size_t Len);

which will only copy Len bytes from src to dest (Len should be less than the size of
dest or the write could still go beyond the bounds of the array)? Unfortunately, strncpy can
lead to one niggling issue: it doesn't guarantee that dest will have a null terminator attached to
it (this might happen if the string src is longer than dest). You can avoid this problem by
using strlen to get the length of src and make sure it will fit in dest. Of course, if you were
going to do that, then you probably don't need strncpy in the first place, right? Wrong. Now it
forces you to pay attention to this issue, which is a big part of the battle

3.2 FILE I/O

3.2.1 C File I/O and Binary File I/O

When accessing files through C, the first necessity is to have a way to access the files.
For C File I/O you need to use a FILE pointer, which will let the program keep track of the
file being accessed. (You can think of it as the memory address of the file or the location of
file).
For Example:

FILE *fp;

To open a file you need to use the fopen function, which returns a FILE pointer. Once you've
opened a file, you can use the FILE pointer to let the compiler perform input and output
functions on the file.

FILE *fopen (const char *filename, const char *mode);

In the filename, if you use a string literal as the argument, you need to remember to
use double backslashes rather than a single backslash as you otherwise risk an escape
character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is
expected. Your users, of course, do not need to do this! It's just the way quoted strings are
handled in C and++.
The modes are as follows:

r - open for reading


w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)

IWIZ Learners Institute of Technical education Pvt Ltd 49


Embedded Primitive Level

Note that it's possible for fopen to fail even if your program is perfectly correct: you might try
to open a file specified by the user, and that file might not exist (or it might be write-
protected). In those cases, fopen will return 0, the NULL pointer.

Here's a simple example of using fopen:

FILE *fp;
fp=fopen ("c:\\test.txt", "r");

This code will open test.txt for reading in text mode. To open a file in a binary mode
you must add a b to the end of the mode string; for example, "rb" (for the reading and writing
modes, you can add the b either after the plus sign - "r+b" - or before - "rb+")

To close a function you can use the function

int fclose (FILE *a file);

fclose returns zero if the file is closed successfully.


An example of fclose is

fclose (fp);

To work with text input and output, you use fprintf and fscanf, both of which are
similar to their friend’s printf and scanf except that you must pass the FILE pointer as first
argument. For example:

FILE *fp;
fp=fopen ("c:\\test.txt", "w");
fprintf (fp, "Testing...\n");

It is also possible to read (or write) a single character at a time--this can be useful if
you wish to perform character-by-character input (for instance, if you need to keep track of
every piece of punctuation in a file it would make more sense to read in a single character
than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns
an int, will let you read a single character from a file:

int fgetc (FILE *fp);

Notice that fgetc returns an int. What this actually means is that when it reads a
normal character in the file, it will return a value suitable for storing in an unsigned char
(basically, a number in the range 0 to 255). On the other hand, when you're at the very end of
the file, you can't get a character value--in this case, fgetc will return "EOF", which is a

IWIZ Learners Institute of Technical education Pvt Ltd 50


Embedded Primitive Level

constant that indicates that you've reached the end of the file. To see a full example using
fgetc in practice, take a look at the example here.

The fputc function allows you to write a character at a time--you might find this
useful if you wanted to copy a file character by character. It looks like this:

int fputc (int c, FILE *fp);

Note that the first argument should be in the range of an unsigned char so that it is a
valid character. The second argument is the file to write to. On success, fputc will return the
value c, and on failure, it will return EOF.

3.2.2 Binary I/O


For binary File I/O you use fread and fwrite.
The declarations for each are similar:

size_t fread (void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a file);

size_t fwrite (const void *ptr, size_t size_of_elements, size_t number_of_elements,


FILE *a file);

Both of these functions deal with blocks of memories - usually arrays. Because they
accept pointers, you can also use these functions with other data structures; you can even
write struts to a file or a read struct into memory.
Let's look at one function to see how the notation works.fread takes four arguments.
Don't by confused by the declaration of a void *ptr; void means that it is a pointer that can be
used for any type variable. The first argument is the name of the array or the address of the
structure you want to write to the file. The second argument is the size of each element of the
array; it is in bytes. For example, if you have an array of characters, you would want to read it
in one byte chunks, so size_of_elements is one. You can use the sizeof operator to get the
size of the various data types; for example, if you have a variable int x; you can get the size
of x with sizeof(x); This usage works even for struts or arrays. E.g., if you have a variable of
a struct type with the name abstract, you can use sizeof (abstract) to find out how much
memory it is taking up.
e.g.

sizeof (int);

The third argument is simply how many elements you want to read or write; for
example, if you pass a 100 element array, you want to read no more than 100 elements, so
you pass in 100.

The final argument is simply the file pointer we've been using. When fread is used,
after being passed an array, fread will read from the file until it has filled the array, and it will
return the number of elements actually read. If the file, for example, is only 30 bytes, but you
try to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was

IWIZ Learners Institute of Technical education Pvt Ltd 51


Embedded Primitive Level

reached, use the feof function, which accepts a FILE pointer and returns true if the end of the
file has been reached. fwrite is similar in usage, except instead of reading into the memory
you write from memory into a file.

For example,

FILE *fp;
fp=fopen ("c:\\test.bin", "web");
char x [10] ="ABCDEFGHIJ";
fwrite(x, sizeof(x [0]), sizeof(x)/sizeof(x [0]), fp);

3.3 COMMAND-LINE ARGUMENTS IN C


Depending on the operating system and programming environment, a C program can
be executed either by selecting an icon inform a graphical user interface desktop or by
entering a command in a command window (DOS or UNIX command window). It is usually
easier to write programs that are run by entering a command in a command window.

A C program is executed by calling its main () function. The function is called with
one argument that indicates how many words are in the command and another argument that
is an array containing the command words.

3.3.1 ACCESSING COMMAND-LINE ARGUMENTS

In order to access the command words, the main () function must have a prototype
similar to the following.

int main (int argc, char * argv [])

The names argc and argv are usually used for the parameters, but a programmer could
use different names.

The command words can be accessed as arg [0] through argv [argc - 1]. The program
name is the first word on the command line,

3.3.1.1 COMMAND LINE ARGUMENTS


It is possible to pass arguments to C programs when they are executed. The brackets which
follow main are used for this purpose. argc refers to the number of arguments passed, and
argv [] is a pointer array, which points to each argument which is passed to main. A simple
example follows, which checks to see if a single argument is supplied on the command line
when the program is invoked.

#include <stdio.h>
main (int argc, char *argv [])
{
if (argc == 2)
printf ("The argument supplied is %s\n", argv [1]);
else if (argc > 2)
printf ("Too many arguments supplied.\n");
else
printf ("One argument expected.\n");
}

IWIZ Learners Institute of Technical education Pvt Ltd 52


Embedded Primitive Level

3.4 VARAIBALE ARGUMENT LIST


One way you could make the function would be to accept a pointer to an array.
Another way would be to write a function that can take any number of arguments. So you
could write avg (4, 12.2, 23.3, 33.3, 12.1); or you could write avg (2, 2.3, 34.4); The
advantage of this approach is that it's much easier to change the code if you want to change
the number of arguments. Indeed, some library functions can accept a variable list of
arguments (such as printf--I bet you've been wondering how that works!).

Whenever a function is declared to have an indeterminate number of arguments, in


place of the last argument you should place an ellipsis (which looks like '...'), so, int a
function ( int x, ... ); would tell the compiler the function should accept however many
arguments that the programmer uses, as long as it is equal to at least one, the one being the
first, x.

We'll need to use some macros (which work much like functions, and you can treat
them as such) from the stdarg.h header file to extract the values stored in the variable
argument list--va_start, which initializes the list, va_arg, which returns the next argument in
the list, and va_end, which cleans up the variable argument list.

To use these functions, need a variable capable of storing a variable-length argument


list--this variable will be of type va_list. va_list is like any other type. For example, the
following code declares a list that can be used to store a variable number of arguments.

va_list a_list;

va_start is a macro which accepts two arguments, a va_list and the name of the
variable that directly precedes the ellipsis ("..."). So in the function a function, to initialize
a_list with va_start, you would write va_start (a_list, x);

Int a function (int x,)


{
va_list a_list;
va_start (a_list, x);
}

Va_arg takes a va_list and a variable type, and returns the next argument in the list in the
form of whatever variable type it is told. It then moves down the list to the next argument.
For example, va_arg (a_list, double) will return the next argument, assuming it exists, in the
form of a double. The next time it is called, it will return the argument following the last
returned number, if one exists. Note that you need to know the type of each argument--that's
part of why printf requires a format string! Once you're done, use va_end to clean up the list:
va_end (a_list); It isn't necessarily a good idea to use a variable argument list at all times; the
potential exists for assuming a value is of one type, while it is in fact another, such as a null
pointer being assumed to be an integer. Consequently, variable argument lists should be used
sparingly.

IWIZ Learners Institute of Technical education Pvt Ltd 53


Embedded Primitive Level

3.5 BINARY TREES

The binary tree is a fundamental data structure used in computer science. The binary
tree is a useful data structure for rapidly storing sorted data and rapidly retrieving stored data.
A binary tree is composed of parent nodes, or leaves, each of which stores data and also links
to up to two other child nodes (leaves) which can be visualized spatially as below the first
node with one placed to the left and with one placed to the right. It is the relationship between
the leaves linked to and the linking leaf, also known as the parent node, which makes the
binary tree such an efficient data structure. It is the leaf on the left which has a lesser key
value (i.e., the value used to search for a leaf in the tree), and it is the leaf on the right which
has an equal or greater key value. As a result, the leaves on the farthest left of the tree have
the lowest values, whereas the leaves on the right of the tree have the greatest values. More
importantly, as each leaf connects to two other leaves, it is the beginning of a new, smaller,
binary tree. Due to this nature, it is possible to easily access and insert data in a binary tree
using search and insert functions recursively called on successive leaves.

The typical graphical representation of a binary tree is essentially that of an upside


down tree. It begins with a root node, which contains the original key value. The root node
has two child nodes; each child node might have its own child nodes. Ideally, the tree would
be structured so that it is a perfectly balanced tree, with each node having the same number of
child nodes to its left and to its right. A perfectly balanced tree allows for the fastest average
insertion of data or retrieval of data. The worst case scenario is a tree in which each node
only has one child node, so it becomes as if it were a linked list in terms of speed. The typical
representation of a binary tree looks like the following:

10
/ \
6 14
/\ / \
5 8 11 18

The node storing the 10, represented here merely as 10, is the root node, linking to the
left and right child nodes, with the left node storing a lower value than the parent node, and
the node on the right storing a greater value than the parent node. Notice that if one removed
the root node and the right child nodes, that the node storing the value 6 would be the
equivalent a new, smaller, binary tree.
The structure of a binary tree makes the insertion and search functions simple to
implement using recursion. In fact, the two insertions and search functions are also both very
similar. To insert data into a binary tree involves a function searching for an unused node in
the proper position in the tree in which to insert the key value. The insert function is generally
a recursive function that continues moving down the levels of a binary tree until there is an
unused leaf in a position which follows the rules of placing nodes. The rules are that a lower
value should be to the left of the node, and a greater or equal value should be to the right.
Following the rules, an insert function should check each node to see if it is empty, if so, it
would insert the data to be stored along with the key value (in most implementations, an
empty node will simply be a NULL pointer from a parent node, so the function would also
have to create the node). If the node is filled already, the insert function should check to see if

IWIZ Learners Institute of Technical education Pvt Ltd 54


Embedded Primitive Level

the key value to be inserted is less than the key value of the current node, and if so, the insert
function should be recursively called on the left child node, or if the key value to be inserted
is greater than or equal to the key value of the current node the insert function should be
recursively called on the right child node. The search function works along a similar fashion.
It should check to see if the key value of the current node is the value to be searched. If not, it
should check to see if the value to be searched for is less than the value of the node, in which
case it should be recursively called on the left child node, or if it is greater than the value of
the node, it should be recursively called on the right child node. Of course, it is also necessary
to check to ensure that the left or right child node actually exists before calling the function
on the node.
Because binary trees have log (base 2) n layers, the average search time for a binary
tree is log (base 2) n. To fill an entire binary tree, sorted, takes roughly log (base 2) n * n.
Lets take a look at the necessary code for a simple implementation of a binary tree. First, it is
necessary to have a struct, or class, defined as a node.

struct node
{
int key value;
struct node *left;
struct node *right;
};

The struct has the ability to store the key value and contains the two child nodes
which define the node as part of a tree. In fact, the node itself is very similar to the node in a
linked list. A basic knowledge of the code for a linked list will be very helpful in
understanding the techniques of binary trees. Essentially, pointers are necessary to allow the
arbitrary creation of new nodes in the tree.
There are several important operations on binary trees, including inserting elements,
searching for elements, removing elements, and deleting the tree. We'll look at three of those
four operations in this tutorial, leaving removing elements for later.
We'll also need to keep track of the root node of the binary tree, which will give us
access to the rest of the data:

struct node *root = 0;

It is necessary to initialize root to 0 for the other functions to be able to recognize that the tree
does not yet exist. The destroy tree shown below which will actually free all of the nodes of
in the tree stored under the node leaf: tree.

IWIZ Learners Institute of Technical education Pvt Ltd 55


Embedded Primitive Level

void destroy tree (struct node *leaf)


{
if (leaf! = 0)
{
destroy tree (leaf->left);
destroy tree (leaf->right);
free (leaf);
}
}

The function destroy tree goes to the bottom of each part of the tree, that is, searching
while there is a non-null node, deletes that leaf, and then it works its way back up. The
function deletes the leftmost node, then the right child node from the leftmost node's parent
node, then it deletes the parent node, then works its way back to deleting the other child node
of the parent of the node it just deleted, and it continues this deletion working its way up to
the node of the tree upon which delete tree was originally called. In the example tree above,
the order of deletion of nodes would be 5 8 6 11 18 14 10. Note that it is necessary to delete
all the child nodes to avoid wasting memory.

3.6 USING LIBRARY

The C standard library is a now-standardized collection of header files and library


routines used to implement common operations, such as input/output and string handling, in
the C programming language. Unlike other languages such as COBOL, FORTRAN, and
PL/I, C does not include built-in keywords for these tasks, so nearly all C programs rely on
the standard library to function

3.6.1 HEADER FILES

Libraries for use by C programs really consist of two parts: header files that define
types and macros and declare variables and functions; and the actual library or archive that
contains the definitions of the variables and functions.

(Recall that in C, a declaration merely provides information that a function or


variable exists and gives its type. For a function declaration, information about the types of
its arguments might be provided as well. The purpose of declarations is to allow the compiler
to correctly process references to the declared variables and functions. A definition, on the
other hand, actually allocates storage for a variable or says what a function does.)

In order to use the facilities in the GNU C library, you should be sure that your
program source files include the appropriate header files. This is so that the compiler has
declarations of these facilities available and can correctly process references to them. Once
your program has been compiled, the linker resolves these references to the actual definitions
provided in the archive file.

Header files are included into a program source file by the `#include' preprocessor
directive. The C language supports two forms of this directive; the first,

IWIZ Learners Institute of Technical education Pvt Ltd 56


Embedded Primitive Level

#include "header"

Is typically used to include a header file header that you write yourself; this would
contain definitions and declarations describing the interfaces between the different parts of
your particular application. By contrast,

#include <file.h>

File.h is typically used to include a header file `file.h' that contains definitions and
declarations for a standard library. This file would normally be installed in a standard place
by your system administrator. You should use this second form for the C library header files.

3.6.2 ANSI C Library Header Files

Contains the assert macro, used to assist with detecting logical errors and other
<assert.h>
types of bug in debugging versions of a program.

<complex.h> A set of functions for manipulating complex numbers. (New with C99)

Contains functions used to classify characters by their types or to convert


between upper and lower case in a way that is independent of the used
<ctype.h>
character set (typically ASCII or one of its extensions, although
implementations utilizing EBCDIC are also known).

<errno.h> For testing error codes reported by library functions.

<fenv.h> For controlling floating-point environment. (New with C99)

Contains defined constants specifying the implementation-specific properties


of the floating-point library, such as the minimum difference between two
<float.h> different floating-point numbers (_EPSILON), the maximum number of digits
of accuracy (_DIG) and the range of numbers which can be represented
(_MIN, _MAX).

<inttypes.h> For precise conversion between integer types. (New with C99)

<iso646.h> For programming in ISO 646 variant character sets. (New with NA1)

IWIZ Learners Institute of Technical education Pvt Ltd 57


Embedded Primitive Level

Contains defined constants specifying the implementation-specific properties


<limits.h> of the integer types, such as the range of numbers which can be represented
(_MIN, _MAX).

For set locale () and related constants. This is used to choose an appropriate
<locale.h>
locale.

<math.h> For computing common mathematical functions

<setjmp.h> Declares the macros set Jmp and long Jmp, which are used for non-local exits

<signal.h> For controlling various exceptional conditions

<stdarg.h> For accessing a varying number of arguments passed to functions.

<stdbool.h> For a Boolean data type. (New with C99)

<String.h> For defining various integer types. (New with C99)

<stdio.h> For defining several useful types and macros.

Provides the core input and output capabilities of the C language. This file
<stdio.h>
includes the venerable printf function.

For performing a variety of operations, including conversion, pseudo-random


<stdlib.h> numbers, memory allocation, process control, environment, signaling,
searching, and sorting.

<String.h> For manipulating several kinds of strings.

<tgmath.h> For type-generic mathematical functions. (New with C99)

IWIZ Learners Institute of Technical education Pvt Ltd 58


Embedded Primitive Level

<time.h> For converting between various time and date formats.

For manipulating wide streams and several kinds of strings using wide
<wchar.h>
characters - key to supporting a range of languages. (New with NA1)

<wctype.h> For classifying wide characters. (New with NA1)

3.6.3 MACRO DEFINITIONS OF FUNCTIONS

If we describe something as a function in this manual, it may have a macro definition


as well. This normally has no effect on how your program runs--the macro definition does the
same thing as the function would. In particular, macro equivalents for library functions
evaluate arguments exactly once, in the same way that a function call would. The main
reason for these macro definitions is that sometimes they can produce an inline expansion
that is considerably faster than an actual function call.

Taking the address of a library function works even if it is also defined as a macro.
This is because, in this context, the name of the function isn't followed by the left parenthesis
that is syntactically necessary to recognize a macro call.

You might occasionally want to avoid using the macro definition of a function--
perhaps to make your program easier to debug. There are two ways you can do this:

• You can avoid a macro definition in a specific use by enclosing the name of the
function in parentheses. This works because the name of the function doesn't appear
in a syntactic context where it is recognizable as a macro call.
• You can suppress any macro definition for a whole source file by using the `#undef'
preprocessor directive, unless otherwise stated explicitly in the description of that
facility.

For example, suppose the header file `stdlib.h' declares a function named abs with

extern int abs (int);

and also provides a macro definition for abs. Then, in:

#include <stdlib.h>
int f (int *i) {return (abs (++*i)) ;}

The reference to abs might refer to either a macro or a function. On the other hand, in
each of the following examples the reference is to a function and not a macro.

#include <stdlib.h>
int g (int *i) {return ((abs) (++*i)) ;}

IWIZ Learners Institute of Technical education Pvt Ltd 59


Embedded Primitive Level

#undef abs
int h (int *i) {return (abs (++*i)) ;}

Since macro definitions that double for a function behave in exactly the same way as
the actual function version, there is usually no need for any of these methods. In fact,
removing macro definitions usually just makes your program slower.

3.7 TYPE CASTING

Converting an expression of a given type into another type is known as type-casting.

3.7.1 Implicit conversion


Implicit conversions do not require any operator. They are automatically performed
when a value is copied to a compatible type. For example:

short a=2000;
int b;
b=a;

Implicit conversions also include constructor or operator conversions, which affect


classes that include specific constructors or operator functions to perform conversions. For
example:

class A {};
class B { public: B (A a) {} };

A a;
B b=a;

Here, an implicit conversion happened between objects of class A and class B, because
B has a constructor that takes an object of class A as parameter. Therefore, implicit
conversions from A to B are allowed.

3.7.2 Explicit conversion

Explicit conversion occurs when you are converting the value of the larger data type
to the value of the smaller data type.

When floating points are converted to integers, truncation occurs.


#include <stdio.h>
main ()
{
double f1 = 12.23456;
printf ("%d \n", (int) f1);
}

3.7.3 TYPE-CAST CONVERSIONS

IWIZ Learners Institute of Technical education Pvt Ltd 60


Embedded Primitive Level

Syntax
cast-expression:
unary expression
(type-name) cast-expression

type-name:
specified-qualifier-list abstract-decelerator

Legal Type Casts

Destination Types Potential Sources

Integral types Any integer type or floating-point type, or pointer to an


object
Floating-point Any arithmetic type
A pointer to an object, or Any integer type, (void *), a pointer to an object, or a
(void *) function pointer
Function pointer Any integral type, a pointer to an object, or a function
pointer
A structure, union, or array None
Void type Any type

Type conversions depend on the specified operator and the type of the operand or
operators. Type conversions are performed in the following cases:

• When a value of one type is assigned to a variable of a different type or an operator


converts the type of its operand or operands before performing an operation
• When a value of one type is explicitly cast to a different type
• When a value is passed as an argument to a function or when a type is returned from a
function

3.8 STORAGE CLASSES

C has a concept of 'Storage classes' which are used to define the scope (visibility) and
life time of variables and/or functions.

auto - storage class


auto is the default storage class for local variables.
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only
be used within functions, i.e. local variables.

IWIZ Learners Institute of Technical education Pvt Ltd 61


Embedded Primitive Level

Register - Storage Class


Register is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word)
and cant have the unary '&' operator applied to it (as it does not have a memory location).
{
Register int Miles;
}
Register should only be used for variables that require quick access - such as counters.
It should also be noted that defining 'register' goes not mean that the variable will be stored in
a register. It means that it MIGHT be stored in a register - depending on hardware and
implementation restrictions.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and
road) both have a static storage class.

static int Count;


int Road;

main()
{
printf("%d\n", Count);
printf("%d\n", Road);
}

'Static' can also be defined within a function. If this is done, the variable is initialized
at compilation time and retains its value between calls. Because it is initialed at compilation
time, the initialization value must be a constant. This is serious stuff - tread with care.

void Func(void)
{
static Count=1;
}

Here is an example

There is one very important use for 'static'. Consider this bit of code.

char *Func(void);

main()
{
char *Text1;

IWIZ Learners Institute of Technical education Pvt Ltd 62


Embedded Primitive Level

Text1 = Func();
}

char *Func(void)
{
char Text2[10]="martin";
return(Text2);
}

'Func' returns a pointer to the memory location where 'Text2' starts BUT Text2 has a
storage class of auto and will disappear when we exit the function and could be overwritten
by something else. The answer is to specify:

static char Text[10]="martin";

The storage assigned to 'Text2' will remain reserved for the duration if the program.

Extern - Storage Class


Extern defines a global variable that is visible to ALL object modules. When you use 'extern'
the variable cannot be initialized as all it does is point the variable name at a storage location
that has been previously defined.

Source 1 Source 2
-------- --------

extern int count; int count=5;

Write () main ()
{ {
printf ("count is %d\n", count); write ();
} }

Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source 2
will see the new value. Here are some example source files

Summary
 We learnt about the Advanced C Programming Techniques.
 We are familiar in concepts like C style Arguments, File I/O, and Type Casting and
command line arguments.
 We saw about the Variable Argument List and Macro Substitutions like how we can
store the Variables and Constants in C like Memory Management

Exercise
1. Write a Program for Reading the Command Line
2. Write a Program for Average Calculation Using Variable Argument List

IWIZ Learners Institute of Technical education Pvt Ltd 63


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 64


Embedded Primitive Level

CHAPTER 4

FOUNDATION OF EMBEDDED SYSTEM


About this Chapter
 Understand the basic building blocks of a microcontroller device in general and its
relevance.
 Know the history and developments in micro controllers and microprocessor.

After this Chapter


 You must be able to work in embedded system software.
 You must be able to handle all the instructions sets and addressing modes
4.1 WHAT IS AN EMBEDDED SYSTEM?

An embedded system is a special-purpose computer system designed to perform a


dedicated function. Ex: In a washing machine, mobile etc Unlike a general-purpose
computer, such as a personal computer, which can be used for different applications like
word processing, software development, accounting, web applications etc. an embedded
system performs one or a few pre-defined tasks, usually with very specific requirements, and
often includes task-specific hardware and mechanical parts not usually found in a general-
purpose computer.

It is a combination of Hardware and software that forms a component of some


larger system and is expected to function without human intervention. Typically, an
embedded system consists of a single-board microcomputer with software in ROM, which
starts running a dedicated application as soon as power is turned on and does not stop until
power is turned off.

The system is dedicated to specific tasks; design engineers can optimize it, reducing the
size and cost of the product.
Embedded systems are often mass-produced, benefiting from economies of scale.

4.1.1 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 reason such as safety and usability; others may have low or no performance
requirements, allowing the system hardware to be simplified to reduce costs.

2) An embedded system is not always a separate block very often it is physically


built-in to the device it is controlling

3) The software written for embedded systems is often called firmware, and is stored
in read-only memory or Flash memory chips rather than a disk drive. It often runs with
limited computer hardware resources: small or no keyboard, screen, and little memory.

IWIZ Learners Institute of Technical education Pvt Ltd 65


Embedded Primitive Level

4.1.2 Real Time Issues

Embedded systems frequently control hardware, and must be able to respond to them in
real time. Failure to do so could cause inaccuracy in measurements, or even damage hardware
such as motors. This is made even more difficult by the lack of resources available.

Almost all embedded systems need to be able to prioritize some tasks over others, and to
be able to put off/skip low priority tasks in favor of high priority tasks like hardware control.

Requirements of Embedded Systems:

4.1.3 Reliability

Embedded systems will work without the need of rebooting or resetting. Hence, the
hardware and software should be reliable. The system should be able to reset itself without
human intervention at the time of any hardware failure. In addition, embedded systems must
operate reliably under extreme environmental conditions.

4.1.4 Cost Effectiveness

If embedded system is designed for a very special purpose like in a nuclear plant,
space satellites cost may not be an issue. However, when it is used for the mass market, as in
CD players, toys or mobile devices cost is an important consideration. SIC are developed to
reduce the hardware components and cost.

4.1.5 Low Power Consumption

Most of embedded systems are powered by batteries. Hence, power consumption


must be de-minimized to avoid draining the batteries.

4.1.6 Efficient Use of Processing Power

The processing power requirement is specified in terms of Million Instructions per


second (MIPS).The MIPS required for the application has to be estimated first for choosing
the processor.

4.1.7 Efficient Use of Memory

Most Embedded systems do not have secondary storage such as hard disk. The
memory chips available on the embedded system are only ROM for storing program and
RAM for data. The developer may determine the program size and data size considering the
functionality, based on which memory requirements are important.

4.1.8 Appropriate Execution Time

In real time applications, certain tasks must be performed within a specified time.
Hence, analyzing the tasks to meet the performance constraints is of considerable importance.
The performance requirement also involves code optimization to maximum possible extent.

IWIZ Learners Institute of Technical education Pvt Ltd 66


Embedded Primitive Level

4.1.9 Embedded Systems Design


Embedded systems consist of hardware, software, and an environment. They have in
common with most computing systems. However, there is an essential difference between
embedded and other computing systems: since embedded systems involve computation that is
subject to physical constraints, the powerful separation of computation (software) from
physicality platform and environment), which has been one of the central ideas enabling the
science of computing, does not work for embedded systems. Instead, the design of embedded
systems requires a holistic approach that integrates essential paradigms from hardware
design, software design, and control theory in a consistent manner. We postulate that such a
holistic approach cannot be simply an extension of hardware design, nor of software design,
but must be based on a new foundation that subsumes techniques from both worlds. This is
because current design theories and practices for hardware, and for software, are tailored
towards the individual properties of these two domains; indeed, they often use abstractions
that are diametrically opposed. To see this, we now have a look at the abstractions that are
commonly used in hardware design, and those that are used in software design.

The embedded system design and development process is divided into four phases.
1. creating the architecture of the system
2. implementing the architecture
3. testing the system
4. maintaining the system

The embedded system design involves choosing the right processor, memory, devices
and bus.

4.1.10. Applications

Embedded systems are used in many diverse fields.Embedded systems play crucial
role in design and manufacture of devices and systems. Depending on their areas of usage,
the embedded systems fall into different categories.

Consumer Electronics: Microwave ovens, digital cameras, CD players, DVD players,


washing machines, set top box etc.

Telecommunications: Telephone switches cellular phones etc.

Medical: Biologically interfaced systems, Medical control systems, Pacemakers etc.

Automotive: Engine controllers, anti-lock brake controllers etc.

Plant control: Robots, plant monitors, industrial process systems, airplane control
systems, missile guidance systems etc.

IWIZ Learners Institute of Technical education Pvt Ltd 67


Embedded Primitive Level

4.2 WHICH PROGRAMMING LANGUAGE SHOULD YOU USE?

Having decided to use an 8051 processor as the basis of your embedded system,
the next key decision that needs to be made is the choice of programming language.
In order to identify a suitable language for embedded systems, we might begin by making the
following observations:

• Computers (such as microcontroller, microprocessor or DSP chips) only accept


instructions in ‘machine code’ (‘object codes’). Machine code is, by definition, in
the language of the computer, rather than that of the programmer. Interpretation of
the code by the programmer is difficult and error prone.
• There is no point in creating ‘perfect’ source code, if we then make use of a poor
translator program (such as an assembler or compiler) and thereby generate
executable code that does not operate as we intended.
• Embedded processors – like the 8051 – have limited processor power and very
limited memory available: the language used must be efficient.
• To program embedded systems, we need low-level access to the hardware: this
means, at least, being able to read from and write to particular memory locations
(using ‘pointers’ or an equivalent mechanism).

Of course, not all of the issues involved in language selection are purely technical:
• No software company remains in business for very long if it generates new code,
from scratch, for every project. The language used must support the creation of
flexible libraries, making it easy to re-use (well-tested) code components in a
range of projects. It must also be possible to adapt complete code systems to work
with a new or updated processor with minimal difficulty.
• Staff members change and existing personnel have limited memory spans. At the
same time, systems evolve and processors are updated. As concern over the ‘Year
2000’ problem in recent years has illustrated, many embedded systems have a
long lifespan. During this time, their code will often have to be maintained.
• The language chosen should be in common use. This will ensure that you can
continue to recruit experienced developers who have knowledge of the language.
It will also mean that your existing developers will have access to sources of
information Even this short list immediately raises the paradox of programming
language selection.
• From one point of view, only machine code is safe, since every other language
involves a translator, and any code you create is only as safe as the code written
by the manufacturers of the translator.
• On the other hand, real code needs to be maintained and re-used in new projects,
possibly on different hardware: few people would argue that machine code is easy
to understand, debug or to port. Inevitably, therefore, we need to make
compromises; there is no perfect solution.
• All we can really say is that we require a language that is efficient, high-level,
gives low-level access to hardware, and is well defined. In addition, – of course –
the language must be available for the platforms we wish to use. Against all of
these points, C scores well.

IWIZ Learners Institute of Technical education Pvt Ltd 68


Embedded Primitive Level

4.3 Cognitive Process in Embedded Systems


Based on functionality and feat requirements, embedded systems can be sort out as:
• Stand-alone embedded systems
• Real time systems
• Networked information appliances
• Mobile devices

4.3.1 Stand-Alone Embedded Systems


These systems work in stand-alone mode.i.e. They take inputs, process the inputs and
produce desired output. The inputs can be electrical signals from transducers or command
inputs like pressing a button. The out can be of electrical form, which is used to drive another
system or a LED/LCD display for displaying the information to the users.
Examples for stand-alone systems include those used in process control, automobiles,
consumer electronics etc.

4.3.2 Real Time Systems


Embedded systems in which some specific task has to be done in a specific time are
called real time systems. Time of completion of the task is an important criterion here.
These systems are further classified as:

• Hard real time systems


• Soft real time systems
In hard real time systems, there are strict deadlines for completing the task. If the
deadline is not met, some disaster may occur in the system.Ex: In process control, suppose
the objective is to open a valve within 30ms when a certain condition occurs in the process, if
not opened may lead to some serious damage in the process.
In soft real time systems, a delay of few milliseconds in completing the task will not lead to
serious implication. Ex: Considering a DVD player, if a command is given to the player from
a remote control, and there is a delay of few ms in executing the command will not lead to
any serious consequences.

4.3.3 Networked Information Appliances


Embedded systems that are provided with network interfaces and accessed by
networks such as LAN or the internet are called networked information appliances. Such
embedded
Systems are connected to a network like a network running TCP/IP protocol suite. This could
be the internet or a company’s Intranet. One example of such a system could be a door –lock
system with TCP/IP and HTTP server software running on it. When someone stands in front
of the door, the web cameras in the door lock will send an alert to a desktop over the internet
and the door can be opened through a click of a mouse.

4.3.4 Mobile Devices

Mobile devices like mobile phones; PDAs, smart phones etc are a special category of
embedded systems. Since the mobile devices have resource limitations like embedded
systems such as memory constraints, small size, lack of good user interfaces such as full-
fledged keyboard and display they are classified as embedded systems

IWIZ Learners Institute of Technical education Pvt Ltd 69


Embedded Primitive Level

Building a desktop PC from an 8051 would not be a practical proposition, but it is an excellent
device for building many embedded systems. One important factor is that the 8051 requires a
minimum number of external components in order to operate. For example, figure shows the
circuit diagram for a complete 8051- based application.

The different nature of the embedded and desktop markets is emphasized by the fact
that some of the more recent 8051 devices – far from being more powerful and having more
features than the 1980 original – actually have fewer features. The original 8051 had 32 I/O
pins and could – if necessary – be connected to up to 128 Kbytes of External memory. By
contrast, the more recent ‘Small 8051’ devices typically have only some 15 I/O pins, and do
not support external memory. These devices are finding their way into applications that
would have involved a small number of discrete components (transistors, diodes, resistors,
capacitors) a few years ago, but which may now be Implemented more cheaply using
microcontrollers ‘8051’

4.4 8051 Instruction Set:

The Instruction set is divided in to 5 categories. They are as follows:

1. Arithmetic instructions.
2. Logic instructions.
3. Data transfer instructions.
4. Boolean variable manipulation instruction.
5. Program and machine control instruction

IWIZ Learners Institute of Technical education Pvt Ltd 70


Embedded Primitive Level

4.4.1 Arithmetic Instructions: -

No. of No. of
Addressing
MNEMONICS OPERATIONAL bytes cycles
mode
DESCRIPTION occupied used
INC A Add 1 to acc Register 1 1
INC RR Add 1 to register Rr Register 1 1
INC ADD Add 1 to the content of add Direct 2 1
Add 1 to the content of the
INC @RP indirect 1 1
address in Rp
INC DPTR Add 1 to DPTR Register 1 2
DEC A Subtract 1 from acc Register 1 1
DEC RR Subtract 1 from Rr Register 1 1
DEC ADD Subtract 1 from content of add Direct 2 1
Subtract 1 from the content of
DEC @RP indirect 1 1
address
Add the immediate num with acc
ADD A, #NUM immediate 2 1
and stores result in acc
Add the data in Rx with acc and
ADD A, RX Register 1 1
stores result in acc
Add the data in add with acc and
ADD A, ADD Direct 2 1
stores result in acc
Add the data at the address in Rp
ADD A, @RP with acc and stores result in acc Indirect 1 1

ADDC Add the immediate num with acc


immediate 2 1
A,#NUM and carry, stores result in acc
Add the data in Rx with acc and
ADDC A, RX Register 1 1
carry, stores result in acc
Add the data in add with acc and
ADDC A, ADD Direct 2 1
carry, stores result in acc
Add the data at the address in Rp
ADDC A, @RP with acc and carry, stores result Indirect 1 1
in acc
Subtract immediate num and
SUBB A,
carry from acc; stores the result immediate 2 1
#NUM
in acc
Subtract the content of add and
SUBB A, ADD carry from acc; stores the result Register 1 1
in acc
Subtract the data in Rx and carry
SUBB A, RX Direct 2 1
from acc; stores the result in acc
Subtract the data at the address in
SUBB A, @RP Rp and carry from acc; stores the Indirect 1 1
result in acc
Multiply acc and register B. store
MUL AB the lower byte of result in acc --- 1 4
and higher byte in B
DIV AB divide acc by register B. store --- 1 4

IWIZ Learners Institute of Technical education Pvt Ltd 71


Embedded Primitive Level

quotient in acc and remainder in


B
After addition of two packed
DAA BCD numbers, adjust the sum to --- 1 1
decimal format

4.4.2 Logical Instructions: -

No. of
Addressing No. of bytes
Mnemonics cycles
mode occupied
Operational description used
AND each bit of acc with same
ANLA,
bit of immediate num, stores Immediate 2 1
#NUM
result in acc
AND each bit of acc with same
ANL A, ADD bit of content in add, stores result Direct 2 1
in acc
AND each bit of acc with same
ANL A, RX bit of content of Rx, stores result Register 1 1
in acc
AND each bit of acc with same
ANL A, @RP bit of content of add given by Indirect 1 1
Rp, stores result in acc
AND each bit of acc with same
ANL ADD, A bit of direct add num, stores Direct 2 1
result in add
AND each bit of direct add with
ANL ADD,
same bit of immediate num, direct 3 2
#NUM
stores result in add
OR each bit of acc with same bit
ORL A,
of immediate num, stores result Immediate 2 1
#NUM
in acc
OR each bit of acc with same bit
ORL A, ADD of content in add, stores result in Direct 2 1
acc
OR each bit of acc with same bit
ORL A, RX of content of Rx, stores result in Register 1 1
acc
OR each bit of acc with same bit
ORL A, @RP of content of add given by Rp, Indirect 1 1
stores result in acc
OR each bit of acc with same bit
ORL ADD,
of direct add num, stores result in Direct 2 1
A
add
OR each bit of direct add with
ORL ADD,
same bit of immediate num, direct 3 2
#NUM
stores result in add
XRL A, XOR each bit of acc with same
Immediate 2 1
#NUM bit of immediate num, stores

IWIZ Learners Institute of Technical education Pvt Ltd 72


Embedded Primitive Level

result in acc
XOR each bit of acc with same
XRL A, ADD bit of content in add, stores result Direct 2 1
in acc
XOR each bit of acc with same
XRL A, RX bit of content of Rx, stores result Register 1 1
in acc
XOR each bit of acc with same
XRL A,
bit of content of add given by Indirect 1 1
@RP
Rp, stores result in acc
XOR each bit of acc with same
XRL ADD, A bit of direct add num, stores Direct 2 1
result in add
XOR each bit of direct add with
XRL ADD,
same bit of immediate num, direct 3 2
#NUM
stores result in add
CLR A Clear each bit of acc Direct 1 1
CPL A Complement each bit of acc direct 1 1
AND carry with given bit b,
ANL C, B -- 2 2
stores result in carry
AND carry with complement of --
ANL C, /B 2 2
given bit b, stores result in carry
OR carry with given bit b, stores --
ORL C, B 2 2
result in carry
OR carry with complement of --
ORL C, /B 2 2
given bit b, stores result in carry
CPL C Complement carry flag -- 1 1
CPL B Complement bit b -- 2 1
CLR C Clear carry flag -- 1 1
CLR B Clear given bit b -- 2 1
MOV C, B Copy bit b to carry -- 2 1
MOV B, C Copy carry to bit b -- 2 2
SETB C Set carry flag -- 1 1
SETB B Set bit b -- 2 1
RL A Rotate acc one bit left -- 1 1
RR A Rotate acc one bit right -- 1 1
RLC A Rotate acc one bit left with carry -- 1 1
Rotate acc one bit right with
RRC A -- 1 1
carry
Exchange upper and lower nibble
SWAP A -- 1 1
of acc

4.4.3 Data Moving / Handling Instructions: -

OPERATIONAL NO. OF NO. OF


ADDRESSING
MNEMONICS DESCRIPTION MODE BYTES CYCLES
OCCUPIED USED
MOV A,#NUM Copy the immediate data num in to Immediate 2 1

IWIZ Learners Institute of Technical education Pvt Ltd 73


Embedded Primitive Level

acc
MOV RX,A Copy the data from acc to Rx Register 1 1
MOV A,RX Copy the data from Rx to acc Register 1 1
MOV Copy the immediate data num in to
Immediate 2 1
RX,#NUM Rx
Copy the data from direct address
MOV A,ADD Direct 2 1
add to acc
Copy the data from acc to direct
MOV ADD, A Direct 2 1
address add
MOV Copy the immediate data num in to
Direct 3 2
ADD,#NUM direct address
MOV Copy the data from add2 to add1
Direct 3 2
ADD1,ADD2
Copy the data from direct address
MOV RX,ADD Direct 2 2
add to Rx
Copy the data from Rx to direct
MOV ADD,RX Direct 2 2
address add
MOV @RP,A Copy the data in acc to address in Rp Indirect 1 1
Copy the data that is at address in Rp
MOV A,@RP Indirect 1 1
to acc
MOV Copy the data that is at address in Rp
Indirect 2 2
ADD,@RP to add
MOV Copy the data in add to address in
Indirect 2 2
@RP,ADD Rp
MOV Copy the immediate byte num to the
Indirect 2 1
@RP,#NUM address in Rp
Copy the content of external add in
MOVX A,@RP Indirect 1 2
Rp to acc
MOVX Copy the content of external add in
Indirect 1 2
A,@DPTR DPTR to acc
Copy the content of acc to the
MOVX @RP,A Indirect 1 2
external add in Rp
MOVX Copy the content of acc to the
Indirect 1 2
@DPTR,A external add in DPTR
The address is formed by adding acc
MOVC
and DPTR and its content is copied Indirect 1 2
A,@A+DPTR
to acc
The address is formed by adding acc
MOVC A,
and PC and its content is copied to Indirect 1 2
@A+PC
acc
Increment SP and copy the data from
PUSH ADD source add to internal RAM address Direct 2 2
contained in SP
copy the data from internal RAM
POP ADD address contained in SP to Direct 2 2
destination add and decrement SP
Exchange the data between acc and
XCH A, RX Register 1 1
Rx
XCH A, ADD Exchange the data between acc and Direct 2 1

IWIZ Learners Institute of Technical education Pvt Ltd 74


Embedded Primitive Level

given add
Exchange the data between acc and
XCH A,@RP Indirect 1 1
address in Rp
XCHD A, Exchange only lower nibble of acc
Indirect 1 1
@RP and address in Rp

4.4.4 Branching Instructions: -

Mnemonic Operational description No of No. of


bytes cycles
occupied used
JC LABEL Jump to label if carry is set to 1 2 2
JNC LABEL Jump to label if carry is cleared to 0 2 2
JB B,LABEL Jump to label if given bit is set to 1 3 2
JNB B,LABEL Jump to label if given bit is cleared to 0 3 2
JBC B,LABEL Jump to label if given bit is set. Clear the bit 3 2
CJNE A, ADD, Compare the content of accumulator with the
LABEL content of given address and if not equal 3 2
jump to label
CJNE A, #NUM, Compare the content of accumulator with
LABEL immediate number and if not equal jump to 3 2
label
CJNE RX, Compare the content of Rx with the
#NUM, LABEL immediate number and if not equal jump to 3 2
label
CJNE @RP, Compare the content of location in Rp with
#NUM, LABEL immediate number and if not equal jump to 3 2
label
DJNZ RX, Decrement the content of Rx and jump to the
2 2
LABEL label if it is not zero
DJNZ ADD, Decrement the content of address and jump to
3 2
LABEL the label if it is not zero
JZ LABEL Jump to the label if content of accumulator is
2 2
0
JNZ LABEL Jump to the label if content of accumulator is
2 2
not 0
JMP @A+DPTR Jump to the address created by adding the
1 2
contents on accumulator and dptr
AJMP SADD Take a jump to absolute short range address
2 2
sadd
LJMP LADD Take a jump to absolute long range address
3 2
sadd
SJMP RADD Take a jump to relative address radd 2 2
NOP Short form of no operation means do nothing
1 1
and go to next instruction
ACALL SADD Pushes the content of Acc on stack and load it
2 2
will absolute short range address sadd
LCALL LADD Pushes the content of Acc on stack and load it 3 2

IWIZ Learners Institute of Technical education Pvt Ltd 75


Embedded Primitive Level

will absolute long range address sadd


RET returns from subroutine by restoring the Acc
1 2
from stack using pop operation
RETI Returns from interrupt subroutine by restoring
1 2
Acc from stack using pop operation

4.5 PROGRAMMING EMBEDDED SYSTEMS IN C

4.5.1 Introduction:
In this introductory chapter, we consider some important decisions that must be made at
the start of any embedded project:
• The choice of processor.
• The choice of programming language.
• The choice of operating system.
• We begin by considering the meaning of the phrase ‘embedded system’.

4.5.2 Embedded System Applications


When we talk about ‘Embedded Systems’, what do we mean? Opinions vary.
An embedded system is an application that contains at least one programmable
computer (typically in the form of a microcontroller, a microprocessor or digital signal
processor chip) and which is used by individuals who are, in the main, unaware that the
system is computer-based. Typical examples of embedded applications that are constructed
using the techniques discussed.
• Mobile phone systems (including both customer handsets and base stations).
• Automotive applications (including braking systems, traction control, airbag
release systems, engine-management units, steer-by-wire systems and cruise
control applications).
• Domestic appliances (including dishwashers, televisions, washing machines,
microwave ovens, video recorders, security systems, garage door controllers).
• Aerospace applications (including flight control systems, engine controllers,
autopilots and passenger in-flight entertainment systems).
• Medical equipment (including anesthesia monitoring systems, ECG monitors,
drug delivery systems and MRI scanners).
• Defense systems (including radar systems, fighter aircraft flight control systems,
radio systems and missile guidance systems).
Please note that our definition of embedded systems excludes applications such as
‘personal digital assistants’ (PDAs) running versions of Windows or similar operating
Systems: from a developer’s perspective, these are best viewed as a cut-down version
of a desktop computer system. This type of application makes up a very small percentage
Of the overall ‘embedded’ market

4.5.3 Which Processor Should You Use?


When desktop developers first think about working with embedded systems, there is a
natural inclination to stick with what they know and look for a book which uses Pentium
processors or other devices from this family (such as the 80486, or the Intel 188). However, if
you open up the engine management unit or the airbag release system in your car, or take the

IWIZ Learners Institute of Technical education Pvt Ltd 76


Embedded Primitive Level

back off your dishwasher, you will not find any of these processors sitting inside, nor will
there be anywhere to plug in a keyboard, graphics display or mouse.

Typical desktop processors cost more than US $100.00 a piece (often much more).
This cost puts them out of reach of all but the most expensive embedded application. (Who
would pay more than US $100 for a TV remote-control unit?)

In addition, a desktop processor requires numerous external support chips in order to


function: this further increases the cost. The additional components also increase the physical
size of the system, and the power consumption: both of these factors are major problems for
battery-powered embedded devices. (Who would buy a portable music player that requires
ten large batteries to run, and needs a trolley to transport it?)

Overall, the state-of-the art technology used in desktop processors matches the needs
of the PC user very well: however, their key features – an ability to execute industry-standard
code at a rate of more than 1000 million instructions per second –come with a heavy price tag
and are simply not required in most embedded systems.

The 8051 device is very different. It is a well-tested design, introduced in its original
form by Intel in 1980 The development costs of this device have now been fully recovered,
and prices of modern 8051 devices now start at less than US $1.00. At this price, you get a
performance of around 1 million instructions per second, and 256 bytes (not megabytes!) of
on-chip RAM. You also get 32 port pins and a serial interface. The 8051’s profile (price,
performance, available memory, serial interface) match the needs of many embedded systems
very well. As a result, it is now produced in more than 400 different forms by a diverse range
of companies including PHILIPS, INFINEON, ATMEL and DALLAS. Sales of this vast
family are estimated to have the largest share (around 60%) of the microcontroller market as
a whole, and to make up more than 50% of the 8-bit microcontroller market. Versions of the
8051 are currently used in a long list of embedded products, from children’s toys to
automotive systems.

4.6. WHICH OPERATING SYSTEM SHOULD YOU USE?

Having opted to create our 8051-based applications using C, we can now begin to
consider how this language can be used. In doing so, we will begin to probe some of the
differences between software development for desktop and embedded systems. In the desktop
environment, the program the user requires (such as a word processor program) is usually
loaded from disk on demand, along with any required data (such as a word processor file). It
shows a typical operating environment for such a word processor. Here the system is well
insulated from the underlying hardware. For example, when the user wishes to save his or her
latest novel on disk, the word processor delegates most of the necessary work to the operating
system, which in turn may delegate many of the hardware-specific commands to the BIOS
(basic input/output system).
The desktop PC does not require an operating system (or BIOS). However, for most
users, the main advantage of a personal computer is its flexibility: that is, that the same piece
of equipment has the potential to run many thousands of different programs.

If the PC had no operating system, each of these programs would need to be able to
carry out all the low-level functions for itself. This would be very inefficient and would tend
to make systems more expensive. It would also be likely to lead to errors, as many simple

IWIZ Learners Institute of Technical education Pvt Ltd 77


Embedded Primitive Level

functions would have to be duplicated in even the smallest of programs. One way of viewing
this is that a desktop PC is used to run multiple programs, and the operating system provides
the ‘common code’ (for printing, file storage, graphics, and so forth) that is required by this
set of programs.

Void main (void)


{
// Prepare run function X
X_Init ();
While (1) // ‘for ever’ (Super Loop)
{
X (); // Run function X ()
}
}
It is important to appreciate that there is no operating system in use here. When Power
is applied to the system, the function main () will be called: having performed The
initializations, the function X () will be called, repeatedly, until the system is disconnected
from the power supply (or a serious error occurs).
For example, suppose we wish to develop a microcontroller-based control system to
be used as part of the central-heating system in a building. The simplest version of this
system might consist of a gas-fired boiler (which we wish to control), a sensor (measuring
room temperature), a temperature dial (through which the desired temperature is specified)
and the controller itself

We assume that the boiler, temperature sensor and temperature dial are connected
To the system via appropriate ports.

4.7 ASSEMBLER
Definition
An assembler is a program that acquires basic computer instructions and converts them
into a pattern of bits that the computer's processor can use to perform its basic operations.
Some people call these instructions assembler language and others use the term assembly
language.

• Most computers come with a specified set of very basic instructions that correspond
to the basic machine operations that the computer can perform. For example, a "Load"
instruction causes the processor to move a string of bits from a location in the
processor's memory to a special holding place called a register. Assuming the
processor has at least eight registers, each numbered, the following instruction would

IWIZ Learners Institute of Technical education Pvt Ltd 78


Embedded Primitive Level

move the value (string of bits of a certain length) at memory location 3000 into the
holding place called register 8:

L 8, 3000

• The programmer can write a program using a sequence of these assembler


instructions.
• This sequence of assembler instructions, known as the source code or source program,
is then specified to the assembler program when that program is started.
• The assembler program takes each program statement in the source program and
generates a corresponding bit stream or pattern (a series of 0's and 1's of a given
length).
• The output of the assembler program is called the object code or object program
relative to the input source program. The sequence of 0's and 1's that constitute the
object program is sometimes called machine code.
• The object program can then be run (or executed) whenever desired.

In the earliest computers, programmers actually wrote programs in machine code, but
assembler languages or instruction sets were soon developed to speed up programming.
Today, assembler programming is used only where very efficient control over processor
operations is needed. It requires knowledge of a particular computer's instruction set,
however. Historically, most programs have been written in "higher-level" languages such as
COBOL, FORTRAN, PL /C., and I these languages are easier to learn and faster to write
programs with than assembler language. The program that processes the source code written
in these languages is called a compiler. Like the assembler, a compiler takes higher-level
language statements and reduces them to machine code.

A newer idea in program preparation and portability is the concept of a virtual


machine. For example, using the Embedded C programming language, language statements
are compiled into a generic form of machine language known as byte code that can be run by
a virtual machine, a kind of theoretical machine that approximates most computer operations.
The byte code can then be sent to any computer platform that has previously downloaded or
built in the Java virtual machine. The virtual machine is aware of the specific instruction
lengths and other particularities of the platform and ensures that the Java byte code can run.

4.7.2 Compiler:
A compiler is a special program that progression statements written in a particular
programming language and turns them into machine language or "code" that a computer's
processor uses. Naturally, a programmer writes language statements in a language such as
Pascal or C one line at a time using an editor. The file that is created contains what are called
the source statements. The programmer then runs the appropriate language compiler,
specifying the name of the file that contains the source statements

When executing (running), the compiler first parses (or analyzes) all of the language
statements syntactically one after the other and then, in one or more successive stages or
"passes", builds the output code, making sure that statements that refer to other statements are
referred to correctly in the final code. Traditionally, the output of the compilation has been
called object code or sometimes an object module

IWIZ Learners Institute of Technical education Pvt Ltd 79


Embedded Primitive Level

4.8 DIVERSIFY MICROCONTROLLERS


MCS-51 FAMILY MEMBERS
Device On chip On chip No. of Interrupts Serial ADC Analog
data program timers/counters I/O channels comparators
memory memory

8051 128 bytes 4K ROM 2 5 1 None None


8052 256 bytes 8K ROM 3 6 1 None None
8751 128 bytes 4K EPROM 2 5 1 None None
8752 256 bytes 8K EPROM 3 6 1 None None
ATMEL Microcontrollers
AT89C51 128 bytes 4K flash 2 6 1 None None
AT89C52 256 bytes 8K flash 3 6 1 None None
AT898252 256 bytes 8K Flash 3 6 1 None None

4.9 ARCHITECTURE
Most microcontrollers have two vital architectures, each with two departures. One
architecture refers to the type of bus design used for the program and data memory: The other
cataloging describes the type of instruction set and the density of the CPU

4.9.1 Vann Neumann


The Von Neumann Architecture is a computer design model that uses a single storage
structure to hold both instructions and data. Single bus for address and data (multiplexed) and
program and data memory is not detached for microprocessor (CISC) complex instruction set
computer.

4.9.2 Harvard

Harvard architecture has separate program and data memory busses. The program
memory bus is up-and-down in width and optimized for a particular device. The data bus
width is usually a standard 8 or 16 bits. The special function registers (timer settings, port
configuration, etc.) are also mapped onto the data bus for the reason they are in essence
variable. This architecture allows the simultaneous access of both program memory and data
memory.

Harvard architecture has several benefits, mainly a long word instruction that
occupies only one location in program memory. A single word instruction increases the
execution speed because the operation code and associated data are all contained in a single
word. The single cycle instruction execution is also easily performed in the Harvard
architecture because the program and data memory can be accessed at the same time.

4.9.3 Roll of Outstanding Firm of Microcontrollers

• ATMEL maker of the AVR RISC controller and various 8051 clones.
• Intel which large line of microprocessor and microcontroller families (Pentium, i960,
8051, etc.), as well as the world leader in flash memory technologies.

IWIZ Learners Institute of Technical education Pvt Ltd 80


Embedded Primitive Level

• Texas Instruments maker of the TMS370 line of 8-bit controllers, as well as the
world-leader in DSP technologies.
• Hitachi, maker of the H8 and Super line of powerful microcontrollers.
• NEC Electronics. Ultra fast VR4xxx line of low power processors, as well as other 8,
16, and 32-bit controllers.
• Philips. 8051 clones and enhanced derivatives.
• Motorola. Very popular microprocessor and microcontroller manufacturer, plus many
cellular and wireless technologies.
• Siemens. Manufacturer of multiple microcontrollers including various 8051 clones.
• Microchip. Maker of the popular "PIC" line of controllers, as well as an extensive line
of serial access EPROM’s.
• National Semiconductor. Maker of the "COP8" controller series, as well as an
embedded version of the Intel 486.
• SGS Thomson. Maker of various 8 and 16-bit microcontrollers.
• Analog Devices. DSPs and many analog ICs.
• Digital Equipment (DEC). The Strong-Arm SA-110 and SA-1110.
• ARM. Licenses the ARM core used in many processors and ASIC’s.
• Advanced Micro Devices (AMD). Manufacturer of various RISC and Intel x86
clones, as well as a large line of embedded x86 derivatives.

• Dallas Semiconductor. Specializes in low power and nonvolatile memory


technologies, "smart card" devices, 8051 clones, microcontroller support chips, etc.
• Fujitsu. DSPs and various microcontrollers.
• Harris Semiconductor. Microcontrollers and MC6805 clones.
• Toshiba. Makes various microcontrollers including Z80 and Motorola microcontroller
clones.

Summary

• Covers key techniques required in all embedded systems in detail, including the
control of port pins and the reading of switches.
• Presents a complete embedded operating system, which uses less than 1% of the
available processor power of an embedded 8051 microcontroller.

• Covers the microcontroller serial interface, which is widely used for debugging
embedded systems, as well as for system maintenance and in data acquisition
applications.
• Includes a substantial and realistic case study.
• Uses 100% C code: no knowledge of assembly language is needed. An industry-
standard C compiler from Kiel Software is also included on the CD, along with
copies of the source code from the book. Programmers with experience of Java,
C++ or C on a desktop PC or workstation will therefore be able to get up and
running very quickly.
• The type of embedded systems that will be discussed
• The choice of programming language for embedded systems.
• The choice of operating system for embedded systems.
• The process of creating executable code for an embedded processor on a desktop
PC.
• The process of testing the embedded code.

IWIZ Learners Institute of Technical education Pvt Ltd 81


Embedded Primitive Level

Technical questions

Exchange the content of FFh and FF00h

1. Store the higher nibble of r7 in to both nibbles of r6

2. Treat r6-r7 and r4-r5 as two 16-bit registers. Perform subtraction between them. Store
the result in 20h (lower byte) and 21h (higher byte).

Exercise

1) Divide the content of r0 by r1. Store the result in r2 (Solution) and r3 (reminder).
Then restore the original content of r0.

2) Transfer the block of data from 20h to 30h to external location 1020h to 1030h.

IWIZ Learners Institute of Technical education Pvt Ltd 82


Embedded Primitive Level

CHAPTER 5

ATMEL MICROCONTROLLER (89C51&89S51&89S52)

About this Chapter


 This chapter will give basic ideas about CISC and RISC architecture.
 It details about addressing modes and instruction sets of 8051 microcontroller.

After this Chapter:


 You can be able to generate software interrupt using the timer.
 You can be able to handle all the instructions sets and addressing modes.

5.1 COMPARISION BETWEEN CISC AND RISC

RISC (Reduced Instruction Set Computer) and CISC (Complex Instruction Set
Computer) stands for two different competing philosophies in designing modern computer
architecture. The difference between RISC and CISC can lie on many levels, many plausible
arguments are put forward by both sides, such as code density, transistor counts, memory
bottlenecks, complier and decode complexity etc.

CISC computers are based on a complex instructions are executed by microcode.


Microcode allows developers to change hardware design and still maintain backward
compatibility with instructions for earlier computers by changing only microcode, thus makes
a complex instruction set possible and flexible. Although CISC designs allow a lot of
hardware flexibility, the supporting of microcode and slows the microprocessor performance
because of the number of operations that must be performed to execute each of CISC
instruction. A CISC instruction set typically includes many instructions with different sizes
and execution cycles, which makes CISC instructions harder to pipeline.

5.1.1 RISC VERSUS CISC


A CISC processor has most of the following properties:
 Richer instruction set, some simple, some very complex
 Instructions generally take more than 1 clock to execute
 Instructions with variable size
 Instructions interface memory in multiple mechanisms with complex addressing
modes.
 No pipelining is used.
 Upward compatibility within the family
 Microcode control
 Work well with simpler compiler

As time passed, one of the non-RISC architecture with large market is the Intel
x 86 families; it has some specific characteristics associated with CISC:
 Segmented memory model
 Few registers
 Crappy floating point performance

IWIZ Learners Institute of Technical education Pvt Ltd 83


Embedded Primitive Level

5.2 DIFFRENCE BETWEEN CONTROLLER AND PROCESSOR

5.2.1 MICROCONTROLLER
Microcontrollers are used in a wide number of electronic systems such as:
 Engine management systems in automobiles.
 Keyboard of a PC.
 Electronic measurement instruments (such as digital millimeters, frequency
oscilloscopes)
 Printers.
 Mobile phones.
 Televisions, radios, CD players, tape recording equipment.
 Hearing aids.
 Security alarm systems, fire alarm systems, and building services systems

5.2.2 Microprocessor
Microprocessor is the integration of a number of useful functions into a single IC
Package. These functions are:

 The ability to execute a stored set of instructions to carry out user defined tasks.
 The ability to be able to access external memory chips to both read and write
From the memory.

MICROCONTROLLER MICROPROCESSOR
In built memory External memory
Internal I/O Circuit External I/O Circuit
More bit handling Instructions Few bit handling instructions.
That we can interface a microcontroller Microprocessor we can't interface
Directly means, "for example we can directly...we
directly connect a Keyboard to require a circuit board since it requires
microcontroller to any of its ports". RAM, IC.....etc
Designed to perform a small set of Designed to perform a wider set of
specific functions general-purpose functions.
RISC architecture CISC architecture

5.3 Pin Diagram

IWIZ Learners Institute of Technical education Pvt Ltd 84


Embedded Primitive Level

5.4 Difference between 8031, 8051, 8052

Controller On-chip data On chip No of 16bit No of vectored


memory program Timers/counters interrupts
Memory

8031 128 None 2 5


8051 128 4k ROM 2 5
8052 256 8k ROM 3 6

5.5 PIN DESCRIPTION

VCC Supply voltage.


GND Ground.

5.5.1 PORT 0

Port 0 is an 8-bit open drain bidirectional I/O port. As an output port, each pin
can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high-
impedance inputs. Port 0 can also be configured to be the multiplexed low-order address/data
bus during accesses to external program and data memory. In this mode, P0 has internal pull-
ups. Port 0 also receives the code bytes during Flash programming and outputs the code bytes
during program verification. External pull-ups are required during program verification.

5.5.2 PORT 1

Port 1 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 1 output
buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins, they are pulled
high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pins that are
externally being pulled low will source current (IIL) because of the internal pull-ups.

5.5.3 PORT 2

Port 2 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 2 output
buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins, they are pulled
high by the internal pull-ups and can be used as inputs. As inputs, Port 2 pins that are
externally being pulled low will source current (IIL) because of the internal pull-ups. Port 2
emits the high-order address byte during fetches from external program memory and during
accesses to external data memory that uses 16-bit addresses (MOVX @ DPTR). In this
application, Port 2 uses strong internal pull-ups when emitting 1s. During accesses to external
data memory that uses 8-bit addresses (MOVX @ RI); Port 2 emits the contents of the P2
Special Function Register. Port 2 also receives the high-order address bits and some control
signals during Flash programming and verification.

5.5.4 PORT 3
Port 3 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 3 output
buffers can sink/source four TTL inputs. When 1s are written to Port 3 pins, they are pulled
high by the internal pull-ups and can be used as inputs. As inputs, Port 3 pins that are

IWIZ Learners Institute of Technical education Pvt Ltd 85


Embedded Primitive Level

externally being pulled low will source current (IIL) because of the pull-ups. Port 3 receives
some control signals for Flash programming and verification. Port 3 also serves the functions
of various special features of the 8051.

5.5.5 PORT PIN ALTERNATE FUNCTIONS

 P3.0 RXD (serial input port)


 P3.1 TXD (serial output port)
 P3.2 INT0 (external interrupt 0)
 P3.3 INT1 (external interrupt 1)
 P3.4 T0 (timer 0 external input)
 P3.5 T1 (timer 1 external input)
 P3.6 WR (external data memory write strobe)
 P3.7 RD (external data memory read strobe)

5.5.6 RST
Reset input. A high on this pin for two machine cycles while the oscillator is running
resets the device. This pin drives high for 98 oscillator periods after the Watchdog times out.
The DISRTO bit in SFR AUXR (address 8EH) can be used to disable this feature. In the
default state of bit DISRTO, the RESET HIGH out feature is enabled.

5.5.7 ALE/PROG

Address Latch Enable (ALE) is an output pulse for latching the low byte of the
address during accesses to external memory. This pin is also the program pulse input (PROG)
during Flash programming. In normal operation, ALE is emitted at a constant rate of 1/6 the
oscillator frequency and may be used for external timing or clocking purposes. Note,
however, that one ALE pulse is skipped during each access to external data memory. If
desired, ALE operation can be disabled by setting bit 0 of SFR location 8EH. With the bit set,
ALE is active only during a MOVX or MOVC instruction. Otherwise, the pin is weakly
pulled high. Setting the ALE-disable bit has no effect if the microcontroller is in external
execution mode.

5.5.8 PSEN
Program Store Enable (PSEN) is the read strobe to external program memory. When
the AT89S52 is executing code from external program memory, PSEN is activated twice
each machine cycle, except that two PSEN activations are skipped during each access to
external data memory.

5.5.9 EA/VPP

External Access Enable. (EA) must be strapped to GND in order to enable the device
to fetch code from external program memory locations starting at 0000H up to FFFFH. Note,
however, that if lock bit 1 is programmed, EA will be internally latched on reset. EA should
be strapped to VCC for internal program executions. This pin also receives the 12-volt
programming enable voltage (VPP) during Flash programming.

IWIZ Learners Institute of Technical education Pvt Ltd 86


Embedded Primitive Level

5.6.0 XTAL1

Input to the inverting oscillator amplifier and input to the internal clock operating
circuit.

5.6.1 XTAL2

Output from the inverting oscillator amplifier.

5.7 ADDRESSING MODES


An "addressing mode" refers to how addressing a given memory location. In
summary, the addressing modes are as follows, with an example of each:
Immediate Addressing MOV A,#20h
Direct Addressing MOV A,30h
Indirect Addressing MOV A,@R0
External Direct MOVX A,@DPTR
Code Indirect MOVC A,@A+DPTR

Each of these addressing modes provides important flexibility.

5.7.1 IMMEDIATE ADDRESSING

Immediate addressing is so-named because the value to be stored in memory


immediately follows the operation code in memory. That is to say, the instruction itself
dictates what value will be stored in memory.

For example, the instruction:

MOV A, #20h

This instruction uses Immediate Addressing because the Accumulator will be loaded
with the value that immediately follows; in this case 20 (hexadecimal).

Immediate addressing is very fast since the value to be loaded is included in the
instruction. However, since the value to be loaded is fixed at compile-time it is not very
flexible.

5.7.2 DIRECT ADDRESSING

Direct addressing is so-named because the value to be stored in memory is obtained


by directly retrieving it from another memory location. For example:

MOV A, 30h

This instruction will read the data out of Internal RAM address 30 (hexadecimal) and
store it in the Accumulator.

IWIZ Learners Institute of Technical education Pvt Ltd 87


Embedded Primitive Level

Direct addressing is generally fast since, although the value to be loaded isn’t
included in the instruction, it is quickly accessible since it is stored in the 8051s Internal
RAM. It is also much more flexible than Immediate Addressing since the value to be loaded
is whatever is found at the given address--which may be variable.

Also, it is important to note that when using direct addressing any instruction which
refers to an address between 00h and 7Fh is referring to Internal Memory. Any instruction
which refers to an address between 80h and FFh is referring to the SFR control registers that
control the 8051 microcontroller itself.

The obvious question that may arise is, "If direct addressing an address from 80h
through FFh refers to SFRs, how can I access the upper 128 bytes of Internal RAM that are
available on the 8052?" The answer is: You cant access them using direct addressing. As
stated, if you directly refer to an address of 80h through FFh you will be referring to an SFR.
However, you may access the 8052s upper 128 bytes of RAM by using the next addressing
mode, "indirect addressing".

5.7.3 INDIRECT ADDRESSING

Indirect addressing is a very powerful addressing mode which in many cases provides
an exceptional level of flexibility. Indirect addressing is also the only way to access the extra
128 bytes of Internal RAM found on an 8052.

Indirect addressing appears as follows:

MOV A,@R0

This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will
then load the accumulator with the value from Internal RAM which is found at the address
indicated by R0.

For example, let us say R0 holds the value 40h and Internal RAM address 40h holds
the value 67h. When the above instruction is executed, the 8051 will check the value of R0.
Since R0 holds 40h, the 8051 will get the value out of Internal RAM address 40h (which
holds 67h) and store it in the Accumulator. Thus, the Accumulator ends up holding 67h.

Indirect addressing always refers to Internal RAM; it never refers to an SFR. Thus, in
a prior example we mentioned that SFR 99h could be used to write a value to the serial port.
Thus, one may think that the following would be a valid solution to write the value 1 to the
serial port:

MOV R0,#99h ;Load the address of the serial port


MOV @R0,#01h ;Send 01 to the serial port -- wrong!!

This is not valid. Since indirect addressing always refers to Internal RAM these two
instructions would write the value 01h to Internal RAM address 99h on an 8052. On an 8051,
these two instructions would produce an undefined result since the 8051 only has 128 bytes
of Internal RAM.

IWIZ Learners Institute of Technical education Pvt Ltd 88


Embedded Primitive Level

5.7.4 EXTERNAL DIRECT

External Memory is accessed using a suite of instructions, which use what I call
"External Direct" addressing. I call it this because it appears to be direct addressing, but it is
used to access external memory rather than internal memory.

There are only two commands that use External Direct addressing mode:

MOVXA,@DPTR
MOVX @DPTR, A

As you can see, both commands utilize DPTR. In these instructions, DPTR must first
be loaded with the address of external memory that you wish to read or write. Once DPTR
holds the correct external memory address, the first command will move the contents of that
external memory address into the Accumulator. The second command will do the opposite: it
will allow you to write the value of the Accumulator to the external memory address pointed
to by DPTR.

5.7.5 EXTERNAL INDIRECT

External memory can also be accessed using a form of indirect addressing which I call
External Indirect addressing. This form of addressing is usually only used in relatively small
projects that have a very small amount of external RAM. An example of this addressing
mode is:

MOVX @R0, A

Once again, the value of R0 is first read and the value of the Accumulator is written to
that address in External RAM. Since the value of @R0 can only be 00h through FFh the
project would effectively be limited to 256 bytes of External RAM. There are relatively
simple hardware/software tricks that can be implemented to access more than 256 bytes of
memory using External Indirect addressing; however, it is usually easier to use External
Direct addressing if your project has more than 256 bytes of External RAM.

5.8 TYPES OF INSTRUCTIONS

The assembly level instructions include: data transfer instructions, arithmetic


instructions, logical instructions, program control instructions, and some special instructions
such as the rotate instructions.

5.8.1 DATA TRANSFER

Many computer operations are concerned with moving data from one location to
another. The 8051 uses five different types of instruction to move data:

MOV MOVX MOVC


PUSH and POP XCH

IWIZ Learners Institute of Technical education Pvt Ltd 89


Embedded Primitive Level

MOV
In the 8051 the MOV instruction is concerned with moving data internally, i.e.
between Internal RAM, SFR registers, general registers etc. MOVX and MOVC are used in
accessing external memory data. The MOV instruction has the following format:

MOV DESTINATION <- SOURCE


The instruction copies (copy is a more accurate word than move) data from a defined
source location to a destination location. Example MOV instructions are:

MOV R2, #80h ; Move immediate data value 80h to register R2


MOV R4, A ; Copy data from accumulator to register R4
MOV DPTR, #0F22Ch ; Move immediate value F22Ch to the DPTR register
MOV R2, 80h ; Copy data from 80h (Port 0 SFR) to R2
MOV 52h, #52h ; Copy immediate data value 52h to RAM location
52h
MOV 52h, 53h ; Copy data from RAM location 53h to RAM 52h
MOV A, @R0 ; Copy contents of location addressed in R0 to
A
(Indirect addressing)

MOVX
The 8051 the external memory can be addressed using indirect addressing only. The
DPTR register is used to hold the address of the external data (since DPTR is a 16-bit
register, it can address 64KByte locations: 216 = 64K). The 8 bit registers R0 or R1 can also
be used for indirect addressing of external memory but the address range is limited to the
lower 256 bytes of memory (28 = 256 bytes).
The MOVX instruction is used to access the external memory (X indicates external
memory access). All external moves must work through the A register (accumulator).
Examples of MOVX instructions are:

MOVX @DPTR, A ; Copy data from A to the address specified in DPTR


MOVX A, @DPTR ; Copy data from address specified in DPTR to A
MOVC
MOVX instructions operate on RAM, which is (normally) a volatile memory.
Program tables often need to be stored in ROM since ROM is non volatile memory. The
MOVC instruction is used to read data from the external code memory (ROM). Like the
MOVX instruction, the DPTR register is used as the indirect address register. The indirect
addressing is enhanced to realize an indexed addressing mode where register A can be used
to provide an offset in the address specification. Like the MOVX instruction, all moves must
be done through register A. The following sequence of instructions provides an example:

MOV DPTR, # 2000h ; Copy the data value 2000h to the DPTR register
MOV A, #80h ; Copy the data value 80h to register A
MOVC A, @A+DPTR ; Copy the contents of the address 2080h (2000h +
80h)
; To register A

IWIZ Learners Institute of Technical education Pvt Ltd 90


Embedded Primitive Level

Note, for the MOVC the program counter, PC, can also be used to form the address.

PUSH AND POP

PUSH and POP instructions are used with the stack only. The SFR register SP
contains the current stack address. Direct addressing is used as shown in the following

Examples

PUSH 4Ch ; Contents of RAM location 4Ch is saved to the stack. SP is


Incremented.
PUSH 00h ; The content of R0 (which is at 00h in RAM) is saved to the stack
and SP is incremented.

POP 80h; the data from current SP address is copied to 80h and SP is
Decremented.

XCH
The above move instructions copy data from a source location to a destination
location, leaving the source data unaffected. A special XCH (exchange) instruction will
actually swap the data between source and destination, effectively changing the source data.
Immediate addressing may not be used with XCH. XCH instructions must use register A.
XCHD is a special case of the exchange instruction where just the lower nibbles are
exchanged. Examples using the XCH instruction are:

XCH A, R3 ; Exchange bytes between A and R3


XCH A, @R0 ; Exchange bytes between A and RAM location whose address is in
R0
XCH A, A0h ; Exchange bytes between A and RAM location A0h (SFR port 2)

5.8.1 ARITHMETIC

Some key flags within the PSW, i.e. C, AC, OV, P, are utilised in many of the
arithmetic instructions. The arithmetic instructions can be grouped as follows:

A) Addition
B) Subtraction
C) Increment/decrement
D) Multiply/divide
E) Decimal adjust

EXPLANATION
A) ADDITION
Register A (the accumulator) is used to hold the result of any addition operation.
Some simple addition examples are:

ADD a, #25 h; Adds the number 25 h to A, putting sum in A


ADD a, R3; Adds the register R3 value to A, putting sum in A

IWIZ Learners Institute of Technical education Pvt Ltd 91


Embedded Primitive Level

The flags in the PSW register are affected by the various addition operations, as
follows:

The C (carry) flag is set to 1 if the addition resulted in a carry out of the accumulator’s
MSB bit, otherwise it is cleared.

The AC (auxiliary) flag is set to 1 if there is a carry out of bit position 3 of the
accumulator, otherwise it is cleared.

For signed numbers the OV flag is set to 1 if there is an arithmetic overflow (described
elsewhere in these notes)

Simple addition is done within the 8051 based on 8 bit numbers, but it is often
required to add 16 bit numbers, or 24 bit numbers etc. This leads to the use of multiple byte
(multi-precision) arithmetic. The least significant bytes are first added, and if a carry results,
this carry is carried over in the addition of the next significant byte etc. This addition process
is done at 8-bit precision steps to achieve multi-precision arithmetic. The ADDC instruction
is used to include the carry bit in the addition process. Example instructions using ADDC are:

ADDC A, #55h ; Add contents of A, the number 55h, the carry bit; and put
the Sum in A
ADDC a, R4; Add the contents of a, the register R4, the carry bit; and put
The sum in A.

B) SUBTRACTION
Computer subtraction can be achieved using 2’s complement arithmetic. Most
computers also provide instructions to directly subtract signed or unsigned numbers. The
accumulator, register A, will contain the result (difference) of the subtraction operation. The
C (carry) flag is treated as a borrow flag, which is always subtracted from the minuend during
a subtraction operation. Some examples of subtraction instructions are:

SUBB A, #55d ; Subtract the number 55 (decimal) and the C flag from and
Put the result in A.
SUBB A, R6 ; Subtract R6 the C flag from A; and put the result in A.
SUBB A, 58h ; Subtract the number in RAM location 58h and the C flag
From A; and put the result in A.

C) INCREMENT/DECREMENT
The increment (INC) instruction has the effect of simply adding a binary 1 to a
number while a decrement (DEC) instruction has the effect of subtracting a binary 1 from a
number. The increment and decrement instructions can use the addressing modes: direct,
indirect and register. The flags C, AC, and OV are not affected by the increment or
decrement instructions. If a value of FFh is increment it overflows to 00h. If a value of 00h is
decrement it underflows to FFh. The DPTR can overflow from FFFFh to 0000h. The DPTR
register cannot be decremented using a DEC instruction (unfortunately!). Some example INC
and DEC instructions are as follows:

IWIZ Learners Institute of Technical education Pvt Ltd 92


Embedded Primitive Level

INC R7 ; Increment register R7


INC A ; Increment A
INC @R1 ; Increment the number that is the content of the address in R1
DEC A ; Decrement register A
DEC 43h ; Decrement the number in RAM address 43h
INC DPTR ; Increment the DPTR register

D) MULTIPLY / DIVID
The 8051 supports 8-bit multiplication and division. This is low precision (8 bit)
arithmetic but is useful for many simple control applications. The arithmetic is relatively fast
since multiplication and division are implemented as single instructions. If better precision, or
indeed, if floating point arithmetic is required then special software routines need to be
written. For the MUL or DIV instructions the A and B registers must be used and only
unsigned numbers are supported.

(i) MULTIPLICATION
The MUL instruction is used as follows (note absence of a comma between the A and
B operands):
MUL AB ; Multiply A by B.

The resulting product resides in registers A and B, the low-order byte is in A and the
high order byte is in B.

(ii)DIVISION
The DIV instruction is used as follows:

DIV AB ; A is divided by B.
The remainder is put in register B and the integer part of the quotient is put in register A.

(E)DECIMAL ADJUST (SPECIAL)


The 8051 performs all arithmetic in binary numbers (i.e. it does not support BCD
arithmetic). If two BCD numbers are added then the result can be adjusted by using the DA,
decimal adjust, instruction:
DA A ; Decimal adjust A following the addition of two BCD numbers.

A simple burglar alarm project is described to demonstrate an 8051 based control


application. A four zone burglar system is realised. The design makes use of the input and
output ports of the 8051 processor

5.8.2 HARDWARE DESCRIPTION


Port3 (P3) is used as an input port. The four input pins, P3.0 to P3.3, are connected to
separate alarm zones. A single zone consists of a series of normally close switches. When any
one of these switches is opened the corresponding input pin transitions to a logic high level
and the processor becomes aware of an alarm situation for the corresponding zone. Pins P3.4
to P3.7 are not used and are tied to ground, logic low. This is a crude alarm system design

IWIZ Learners Institute of Technical education Pvt Ltd 93


Embedded Primitive Level

and the zone wiring could not operate over any long distances. However, the example will
suffice to demonstrate the concept.

The burglar alarm’s output consists of a seven-segment display device and an alarm bell.
The alarm bell is connected to Port 1, bit 7, and the bell is sounded when this output pin is set
to a logic high level by the software. The seven-segment display device is connected to Port
1, bits 0 to 6. Each output pin is fed to the relevant display segment via a non-inverting buffer
device. The seven-segment display device is a common-cathode device so writing a logic
high level to any segment will cause that segment to light.

5.9 TIMERS/COUNTERS

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.

The three timer uses are distinct so we will talk about each of them separately. The
first two uses will be discussed in this chapter while the use of timers for baud rate generation
will be discussed in the chapter relating to serial ports.

5.9.1 HOW DOES A TIMER COUNT?

How does a timer count? The answer to this question is very simple: A timer always
counts. It does not matter whether the timer is being used as a timer, a counter, or a baud rate
generator: A timer is always incremented by the microcontroller.

Programming Tip: Some derivative chips actually allow the program to configure
whether the timers count up or down. However, since this option only exists on some
derivatives it is beyond the scope of this tutorial, which is aimed at the standard 8051. It is
only mentioned here in the event that you absolutely need a timer to count backwards, you
will know that you may be able to find an 8051-compatible microcontroller that does it.

USING TIMERS TO MEASURE TIME

Obviously, one of the primary uses of timers is to measure time. We will discuss this
use of timers first and will subsequently discuss the use of timers to count events. When a
timer is used to measure time it is also called an "interval timer" since it is measuring the time
of the interval between two events.

HOW LONG DOES A TIMER TAKE TO COUNT?

First, it is worth mentioning that when a timer is in interval timer mode (as opposed to
event counter mode) and correctly configured, it will increment by one every machine cycle.
As you will recall from the previous chapter, a single machine cycle consists of 12 crystal
pulses. Thus, a running timer will be incremented:

11,059,000 / 12 = 921,583

IWIZ Learners Institute of Technical education Pvt Ltd 94


Embedded Primitive Level

921,583 times per second. Unlike instructions--some of which require 1 machine


cycle, others 2, and others 4--the timers are consistent: They will always be incremented once
per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate:
50,000 / 921,583 = .0542
.0542 seconds have passed. In plain English, about half of a tenth of a second, or one-
twentieth of a second.

Obviously, it is not very useful to know .0542 seconds have passed. If you want to
execute an event once per second you have to wait for the timer to count from 0 to 50,000
18.45 times. How can you wait "half of a time?" You cannot. Therefore, we come to another
important calculation.

Let us say we want to know how many times the timer will be incremented in .05
seconds. We can do simple multiplication:

.05 * 921,583 = 46,079.15.

This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to
46,079. Actually, it will take it .049999837 seconds--so were off by .000000163 seconds--
however, that’s close enough for government work. Consider that if you were building a
watch based on the 8051 and made the above assumption your watch would only gain about
one second every 2 months. Again, I think that is accurate enough for most applications--I
wish my watch only gained one second every two months!

Obviously, this is a little more useful. If you know it takes 1/20th of a second to count
from 0 to 46,079 and you want to execute some event every second you simply wait for the
timer to count from 0 to 46,079 twenty times; then you execute your event, reset the timers,
and wait for the timer to count up another 20 times. In this manner you will effectively
execute your event once per second, accurate to within thousandths of a second.

Thus, we now have a system with which to measure time. All we need to review is
how to control the timers and initialize them to provide us with the information we need.

5.9.2 TIMER SFRS


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).

We have given SFRs names to make it easier to refer to them, but in reality, an SFR
has a numeric address. It is often useful to know the numeric address that corresponds to an
SFR name. The SFRs relating to timers are:

SFR Name Description SFR Address


TH0 Timer 0 High Byte 8Ch
TL0 Timer 0 Low Byte 8Ah
TH1 Timer 1 High Byte 8Dh

IWIZ Learners Institute of Technical education Pvt Ltd 95


Embedded Primitive Level

TL1 Timer 1 Low Byte 8Bh


TCON Timer Control 88h
TMOD Timer Mode 89h

When you enter the name of an SFR into an assembler, it internally converts it to a
number. For example, the command:

MOV TH0, #25h


Moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR
address 8Ch this command is equivalent to?

MOV 8Ch, #25h


[
Now, back to the timers. First, let us talk about Timer 0.

Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making
things too complicated to start with, you may just think of this as the high and low byte of the
timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When
Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0
will contain the low byte of the value (232 decimal). Reviewing low/high byte notation, recall
that you must multiply the high byte by 256 and add the low byte to calculate the final value.
That is to say:

TH0 * 256 + TL0 = 1000


3 * 256 + 232 = 1000
Timer 1 works the exact same way, but its SFRs are TH1 and TL1.

Since there are, only two bytes devoted to the value of each timer it is apparent that
the maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is
subsequently incremented, it will reset--or overflow--back to 0.

THE TMOD SFR

Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is
used to control the mode of operation of both timers. Each bit of the SFR gives the
microcontroller specific information concerning how to run a timer. The high four bits (bits 4
through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact
same functions, but for timer 0.

The individual bits of TMOD have the following functions:

TMOD (89h) SFR


Bit Name Explanation of Function Timer
When this bit is set, the timer will only run when
7 GATE1 INT1 (P3.3) is high. When this bit is clear, the timer 1
will run regardless of the state of INT1.
6 C/T1 When this bit is set, the timer will count events on T1 1

IWIZ Learners Institute of Technical education Pvt Ltd 96


Embedded Primitive Level

(P3.5). When this bit is clear, the timer will be


incremented every machine cycle.
5 T1M1 Timer mode bit (see below) 1
4 T1M0 Timer mode bit (see below) 1
When this bit is set, the timer will only run when
3 GATE0 INT0 (P3.2) is high. When this bit is clear, the timer 0
will run regardless of the state of INT0.
When this bit is set, the timer will count events on T0
2 C/T0 (P3.4). When this bit is clear, the timer will be 0
incremented every machine cycle.
1 T0M1 Timer mode bit (see below) 0
0 T0M0 Timer mode bit (see below) 0

As you can see in the above chart, four bits (two for each timer) are used to specify a
mode of operation. The modes of operation are:

TxM1 TxM0 Timer Mode Description of Mode


0 0 0 13-bit Timer.
0 1 1 16-bit Timer
1 0 2 8-bit auto-reload
1 1 3 Split timer mode

13-BIT TIME MODE (MODE 0)

Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to
maintain compatibility with its predecessor, 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
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.

Again, there is very little reason to use this mode and it is only mentioned so you will
not be surprised if you ever end up analyzing archaic code, which has been passed down
through the generations (a generation in a programming shop is often about 3 or 4 months).

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

IWIZ Learners Institute of Technical education Pvt Ltd 97


Embedded Primitive Level

contain up to 65536 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, let us 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:

Machine Cycle TH0 Value TL0 Value


1 FDh FEh
2 FDh FFh
3 FDh FDh
4 FDh FEh
5 FDh FFh
6 FDh FDh
7 FDh FEh

As you can see, 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.

What is the benefit of auto-reload mode? Perhaps you want the timer to always have a
value from 200 to 255. If you use mode 0 or 1, you would have to check in code to see if the
timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of
execution time to check the value and/or to reload it. When you use mode 2 the
microcontroller takes care of this for you. Once you’ve configured a timer in mode 2 you
don’t have to worry about checking to see if the timer has overflowed nor do you have to
worry about resetting the value--the microcontroller hardware will do it all for you. The auto-
reload mode is very commonly used for establishing a baud rate, which we will talk more
about in the Serial Communications chapter.

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 now linked to TH0. The real timer 1, in this case, will be incremented every
machine cycle no matter what.

IWIZ Learners Institute of Technical education Pvt Ltd 98


Embedded Primitive Level

The only real use I can see of using split timer mode is if you need to have two
separate timers and, additionally, a baud rate generator. In such case, you can use the real
Timer 1 as a baud rate generator and use TH0/TL0 as two separate timers.

THE TCON SFR

Finally, there is one more SFR that controls the two timers and provides valuable
information about them. The TCON SFR has the following structure:

Bit
Bit Name Explanation of Function Timer
Address
Timer 1 Overflow. This bit is set by the
7 TF1 8Fh 1
microcontroller when Timer 1 overflows.
Timer 1 Run. When this bit is set Timer 1 is turned on.
6 TR1 8Eh 1
When this bit is clear, Timer 1 is off.
Timer 0 Overflow. This bit is set by the
5 TF0 8Dh 0
microcontroller when Timer 0 overflows.
Timer 0 Run. When this bit is set Timer 0 is turned on.
4 TR0 8Ch 0
When this bit is clear Timer, 0 is off.

As you may notice, we have only defined 4 of the 8 bits. That is because the other 4
bits of the SFR do not have anything to do with timers--they have to do with Interrupts and
they will be discussed in the chapter that addresses interrupts.

A new piece of information in this chart is the column "bit address." This is because
this SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1--
which is the highest bit of TCON--you could execute the command:

MOV TCON, #80h

Alternatively, since the SFR is bit-addressable, you could just execute the command:
SETB TF1
This has the benefit of setting the high bit of TCON without changing the value of any
of the other bits of the SFR. Usually when you start or stop a timer you do not want to modify
the other values in TCON, so you take advantage of the fact that the SFR is bit-addressable.

5.9.3 INITIALIZING A TIMER

Now that we have discussed the timer-related SFRs, we are ready to write code that
will initialize the timer and start it running.

As you will recall, we first must decide what mode we want the timer to be in. In this
case, we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any
external pins.

We must first initialize the TMOD SFR. Since we are working with timer 0, we will
be using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we
want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we

IWIZ Learners Institute of Technical education Pvt Ltd 99


Embedded Primitive Level

must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of
TMOD. Thus to initialize the timer we execute the instruction:

MOV TMOD, #01h


Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the
timer running we must set the TR0 bit we can do that by executing the instruction:

SETB TR0
Upon executing these two instructions timer 0 will immediately begin counting, being
incremented once every machine cycle (every 12 crystal pulses).

5.9.4 READING THE TIMER

There are two common ways of reading the value of a 16-bit timer; which you use
depends on your specific application. You may either read the actual value of the timer as a
16-bit number, or you may simply detect when the timer has overflowed.

5.9.5 READING THE VALUE OF A TIMER

If your timer is in an 8-bit mode--that is, either 8-bit Auto Reload mode or in split
timer mode--then reading the value of the timer is simple. You simply read the 1-byte value
of the timer.

However, if you are dealing with a 13-bit or 16-bit timer the chore is a little more
complicated. Consider what would happen if you read the low byte of the timer as 255, then
read the high byte of the timer as 15. In this case, what actually happened was that the timer
value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why? Because you read
the low byte as 255. Nevertheless, when you executed the next instruction a small amount of
time passed--but enough for the timer to increment again at which time the value rolled over
from 14/255 to 15/0. Nevertheless, in the process you have read the timer as being 15/255.
Obviously, there is a problem there.

The solution? It’s not too tricky, really. You read the high byte of the timer, then read
the low byte, then read the high byte again. If the high byte read the second time is not the
same as the high byte read the first time you repeat the cycle. In code, this would appear as:

REPEAT: MOV A,TH0


MOV R0,TL0
CJNE A,TH0,REPEAT
...

In this case, we load the accumulator with the high byte of Timer 0. We then load R0
with the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer
0--which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it
isn’t it means we’ve just "rolled over" and must reread the timer’s value--which we do by
going back to REPEAT. When the loop exits we will have the low byte of the timer in R0 and
the high byte in the Accumulator.

IWIZ Learners Institute of Technical education Pvt Ltd 100


Embedded Primitive Level

Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR
TR0), read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case,
the timer isn’t running so no special tricks are necessary. Of course, this implies that your
timer will be stopped for a few machine cycles. Whether or not this is tolerable depends on
your specific application.

5.9.6 DETECTING TIMER OVERFLOW

Often it is necessary to just know that the timer has reset to 0. That is to say, you are
not particularly interest in the value of the timer but rather you are interested in knowing
when the timer has overflowed back to 0.

Whenever a timer overflows from its highest value back to 0, the microcontroller
automatically sets the TFx bit in the TCON register. This is useful since rather than checking
the exact value of the timer you can just check if the TFx bit is set. If TF0 is set it means that
timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed.

We can use this approach to cause the program to execute a fixed delay. As you’ll
recall, we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to
46,079. However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to
use the TFx flag to indicate when 1/20th of a second has passed we must set the timer
initially to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later
the timer will overflow. Thus we come up with the following code to execute a pause of
1/20th of a second:

MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456)


MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457)
MOV TMOD,#01;Put Timer 0 in 16-bit mode
SETB TR0;Make Timer 0 start counting
JNB TF0,$;If TF0 is not set, jump back to this same instruction

In the above code the first two lines initialize the Timer 0 starting value to 19,457.
The next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB
TF0, $, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand means,
in most assemblers, the address of the current instruction. Thus as long as the timer has not
overflowed and the TF0 bit has not been set the program will keep executing this same
instruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit, and program
execution will then break out of the loop.

5.9.7 TIMING THE LENGTH OF EVENTS

The 8051 provides another cool toy that can be used to time the length of events.

For example, let's say we're trying to save electricity in the office and we're interested
in how long a light is turned on each day. When the light is turned on, we want to measure
time. When the light is turned off we don't. One option would be to connect the light switch
to one of the pins, constantly read the pin, and turn the timer on or off based on the state of
that pin. While this would work fine, the 8051 provides us with an easier method of
accomplishing this.

IWIZ Learners Institute of Technical education Pvt Ltd 101


Embedded Primitive Level

Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always
cleared this bit because we wanted the timer to run regardless of the state of the external pins.
However, now it would be nice if an external pin could control whether the timer was
running or not. All we need to do is connect the light switch to pin INT0 (P3.2) on the 8051
and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is high. When P3.2
is low (i.e., the light switch is off) the timer will automatically be stopped.

Thus, with no control code whatsoever, the external pin P3.2 can control whether or
not our timer is running or not.

5.9.8 USING TIMERS AS EVENT COUNTERS

We've discussed how a timer can be used for the obvious purpose of keeping track of
time. However, the 8051 also allows us to use the timers to count events.

How can this be useful? Let's say you had a sensor placed across a road that would
send a pulse every time a car passed over it. This could be used to determine the volume of
traffic on the road. We could attach this sensor to one of the 8051's I/O lines and constantly
monitor it, detecting when it pulsed high and then incrementing our counter when it went
back to a low state. This is not terribly difficult, but requires some code. Let's say we hooked
the sensor to P1.0; the code to count cars passing would look something like this:

JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting
JB P1.0,$ ;The line is high which means the car is on the sensor right now
INC COUNTER ;The car has passed completely, so we count it

As you can see, it's only three lines of code. However, what if you need to be doing
other processing at the same time? You can't be stuck in the JNB P1.0, $ loop waiting for a
car to pass if you need to be doing other things. Of course, there are ways to get around even
this limitation but the code quickly becomes big, complex, and ugly.

Since the 8051 provides us with a way to use the timers to count events we don't have
to bother with it. It is actually painfully easy. We only have to configure one additional bit.

Let's say we want to use Timer 0 to count the number of cars that pass. If you look
back to the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2
(TCON.2). Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will
be incremented every machine cycle. This is what we've already used to measure time.
However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented
every machine cycle, timer 0 will count events on the P3.4 line. Therefore, in our case we
simply connect our sensor to P3.4 and let the 8051 do the work. Then, when we want to know
how many cars have passed, we just read the value of timer 0--the value of timer 0 will be the
number of cars that have passed.

So what exactly is an event? What does timer 0 actually "count?" Speaking at the
electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a car
first runs over our sensor it will raise the input to a high ("1") condition. At that point the
8051 will not count anything since this is a 0-1 transition. However, when the car has passed

IWIZ Learners Institute of Technical education Pvt Ltd 102


Embedded Primitive Level

the sensor will fall back to a low ("0") state. This is a 1-0 transition and at that instant the
counter will be incremented by 1.

5.9.9 SUMMARY

In this chapter we learned about


 Difference between von Neumann and Harvard architecture, CISC, RISC, micro
processor, and micro controller.
 Pin description, I/O ports and memory organization of an 8051 microcontroller. Pin
functions have been elaborated so that it is possible to know the basic connections of
an 8051 microcontroller.
 In 8051 there are five addressing modes. Those are direct, register, indirect ,
immediate and base modes
 The instructions of 8051 and it is very important to know how the operands are
defined in every instruction.
 Port 0 is an 8-bit open drain bidirectional I/O port. As an output port, each pin can
sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as
high-impedance inputs. Port 0 can also be configured to be the multiplexed low-order
address/data bus during accesses to external program and data memory.
 Timers/counters, they can act independently once initialized.

5.10 Technical Question


(I). The 8052 is an upgraded version of the 8051 or not?
(2). The 8052 has s total of 256 bytes of on-chip ram in addition to the sfr’s?
(3). The extra 128 bytes of ram in the 8052 is physically the same ram as the sfr or not?
(4). Give the address for the upper ram of the 8052?
(5). Show how to put value 99h into ram location f6h of upper ram in the 8052?

5.11Exercise
1. Write a program to switch on a buzzer for every 14 seconds, using timer 0 modes 2.
2. Write a program to toggle a led after every 5 seconds using timer 0 modes 2.

IWIZ Learners Institute of Technical education Pvt Ltd 103


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 104


Embedded Primitive Level

CHAPTER 6

HANDLING REGISTER TYPES OF MNEMONICS


About this Chapter
 This chapter will give idea about bit wise and byte wise instruction.
 You can also learn about types of memory and data transfers.

After this Chapter


 You can understand bit wise and byte wise instruction used in programs.
 You can be able to handle data transfer between registers.

6.1 BINARY MANIPULATION INSTRUCTIONS

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data
shorter than a byte. Programming tasks that require bit manipulation include low-level device
control, error detection and correction algorithms, encryption algorithms, and optimization.
For most other tasks, modern programming languages allow the programmer to work directly
with abstractions instead of bits that represent those abstractions.

Thus we have seen instructions that move data (from/to memory or registers),
calculate arithmetic functions (add, sub) or that change the control flow. There are other
classes of instructions in 68k that are also commonly found in most modern processors. The
first class of instructions we will discuss, implements bit-wise Boolean logic operations. The
second class operates on single bits. The third class performs shifts and rotates.

6.2 BITWISE BOOLEAN LOGIC INSTRUCTIONS

As an example let’s consider the AND.L instruction. All bitwise instructions treat
their arguments as a collection or 32 independent bits (or 16 bits or 8 bits) without assigning
an arithmetic value to the collection of all bits. For them, a register or a memory value is just
an ordered collection of 32 bits (or 16 or 8 – OK we will stop saying this from this point on,
but please do recall that the following discussion applies to words and bytes also). They then
operate on each of those 32 bits separately.

Therefore, AND.L D0, D1 performs 32 Boolean AND calculations in parallel. Each


of those 32 AND calculations is done using two bits one from the D0 register and one from
the D1 register. The bit 0 of D0 is used with bit 0 of D1; bit 1 of D0 is used with bit 1 of D1
and so on. Each of two 32 bit pairs produces a result, which is written into the corresponding
bit position in the destination register. That is, the result of (bit 0 of D0 AND bit0 of D1) is
written into bit 0 of D1.

As an example assume the following initial values of D0 and D1:


3 2 1
1 3 5 7 0
D0 = 00000101 11111111 11001100 00110011
D1 = 11111100 00000111 00111001 00010010
------------------------------------------------------
D1 00000100 00000111 00001000 00010010 <-- AND.L D0, D1

IWIZ Learners Institute of Technical education Pvt Ltd 105


Embedded Primitive Level

Note that this is equivalent to the “&” operation in C. Also note that “&” is the bitwise
operation in C. There “&&” operation in C operates on TRUE and FALSE values (non-zero
and zero respectively on most C dialects – some define <= 0 as false).

These operations are called bitwise because they treat their operands as a collection of
bits that are operated upon individually.

6.2.1 Note on word and byte bitwise calculations


We can operate on long words, words or just bytes. When operating using words, the
upper two bytes of the destination register are left untouched. Similarly, when operating on
bytes, the upper three bytes of the destination register are left unchanged.
For the AND instruction one of the two operands must be a D register.

AND with Immediate


There is a variation where the source operand can be an immediate. This is the ANDI
instruction. For example we can use AND.L #$0000ffff, D0 to set the upper two bytes of D0.

AND operations are useful among other things for masking out bits out of long
values. For example, say we are interested in whether an integer is even. In this case, the
lower bit of the integer must be 0. Accordingly we can use the following sequence:

 ANDI.L #1, D0
 BEQ ISEVEN

What we have done is use a constant that had a 1 only at the bit position that we were
interested in. By doing a logical AND with this constant we essentially zeroed out all bits
except the last one. As a result, the outcome of the AND operation would be zero if the least
significant bit was zero otherwise it will be non-zero.

Such operations are very handy when accessing data that uses long data types to
encapsulate a collection of different information pieces. We will see more concrete examples
when we talk about I/O devices.

Other bitwise logical operations include:


EOR and EORI = exclusive OR (XOR), result is 1 if the two input bits have different values.
In C xor is “^”.

e.g., EOR (A0), D0  [d0] = [d0] XOR MEM [[A0]]


OR and ORI = OR. In C or is “|”.
e.g., OR D1, D0  [d0] = [d0] OR [d1]
NOT: This in C is the “~” operation.
e.g., NOT D0  [d0] = reverse of [d0] (i.e., 1s changed to 0s and vice versa).

IWIZ Learners Institute of Technical education Pvt Ltd 106


Embedded Primitive Level

The following table summarizes these instructions:

Where EOR is the Exclusive OR, or also called XOR. So 0 EOR 0 = 1 EOR 1 = 0 and
1 EOR 0 = 0 EOR 1 = 0.

As a side note, here’s a quick way to swap the values of two registers:

eor.l d1, d0
eor.l d0, d1
eor.l d1, d0

Try a couple of examples, and then try to express the outcome of each instruction as a
function of the original values of d0 and d1 and XOR. Keep in mind that A XOR A = 0, A
XOR 0 = A and A XOR 1…1 = not (A). Some machines provide a swap instruction.
The C equivalents of the aforementioned bitwise operations are:

 a AND b  a & b
 a OR b  a | b
 a EOR b  a ^ b
 NOT a  ~a

6.2.2 Single Bit Manipulation Instructions


These instructions change the value of a single bit. Before doing so they copy the
value of this bit into the Z condition code.
 BCLR.datatype bit no, destination
 BCHG.data type bit no, destination
 BSET.data type bit no, destination
 BTST.data type bit no, operand

The first three respectively clear, reverse and set the (bit no) bit of the destination.
Before changing the bit value, the bit is copied into the Z condition code. The last instruction
simply does that and does not affect the operand (tests for a bit value).

Examples:

 BCLR.L #0, D0  clears bit 0 (least significant of D0)


 BSET.B #7, D1  clears the 8th bit of register D1

IWIZ Learners Institute of Technical education Pvt Ltd 107


Embedded Primitive Level

Bits are numbered starting from 0 (leftmost – least significant). The data type can be either a
byte or a long word.

The following table summarizes these instructions where Z is the Z condition


code flag in register SR. “~” means NOT as it also does in C.

6.3 SHIFTS

The third class of bit manipulation instructions treats their operands as bits placed in
series one after the other. They displace these bits by a number of positions. Lets us look at
each one of these instructions. The shifts correspond to the “>>” and “<<” operations in C.
There are no C equivalents for the rotate instructions (although we can synthesize them using
shifts and bitwise logical operations).

First are logical shifts. For clarity we will restrict our attention to the 8 bit data type
however the discussion applies to all three data types.
Logical shifts can be performed either to the left or to the right. In shifts, the bits of the
operands being shifted are treated as 8 bits placed in order one after the other and on a
straight line. The instruction shifts those bits either to the left or to the right by a number of
bit positions. The positions that are left empty are filled with zeroes and the bits that are
shifted out of limits are simply discarded.

The two instructions are:


LSL.datatype n, operand  shift left the operand by n bits
LSR.datatype n, operand  shift right the operand by n bits
Consider for example a logical shift left:
lsl.b #1, d0

Assume that initially the value of the lower byte of d0 is 11001101. Shifting left by
one position gives 10011010. Note the 1 that was at the most significant bit position in the
source operand was discarded and the empty position that was created by shifting the bits to
the left was filled with a 0.

lsl.b #4, d0 will give 11010000.


lsl.b #6, d0 will give 0100000.
Similarly for logical shifts to the right we have:
lsr.b #1, d0 will give 01100110 (the last bit of the source operand was discarded)
lsr.b #5 d0 will give 00000110.

IWIZ Learners Institute of Technical education Pvt Ltd 108


Embedded Primitive Level

In summary, logical shifts move the bits by a specified number of bit positions to the
left or right. Bits positions that are emptied are filled with zeroes and bits that are moved out
of the bit positions that are available in the data type are discarded.

6.3.1 Relation of Shifts and Division and Multiplication


If the operand being shifted is interpreted as an unsigned integer then shifting left by 1
bit is equivalent to multiplying the operand by 2. Similarly shifting right by 1 bit is equivalent
to dividing by 2. It follows that:
Shifting left by n bits is equivalent to multiplying by 2^n
Shifting right by n bits is equivalent to dividing by 2^n

6.3.2 Arithmetic Shifts


The second class of shifts is meant to be used for quantities that are presumed to be
signed integers (2’s complement). The two instructions are:
ASL.datatype n, operand  Arithmetic shift left
ASR.datatype n, operand  Arithmetic shift right
Suffices to note that arithmetic and logical shifts to the left are equivalent. The
difference is between the two shifts to the right. While the logical fills in the emptied bits
with zeroes, the arithmetic shift fills them with the most significant bit of the source operand.
For example, assume D0 = 1101 0010 and D1 = 0101 0011 then:

 ASR.B #3, D0  will produce 1111 1010


 LSR.B #3, D0  will produce 0001 1010
 ASR.B #2, D1  produces 0001 0100
 LSR.B #2, D1  produces 0001 0100
Arithmetic shifts to the left and to the right by n bits are equivalent respectively to
multiplying or dividing by a power of 2 with one exception: if the operand is -1 then the
arithmetic shift right does not produce 0 as it should. It produces -1 (note -1 is represented as
all ones).

6.4 ROTATES
The last class of bit manipulation instructions treats their source/destination operand
as a sequence of bits that are placed on a circle. That is the bits are ordered (bit 1 is next to bit
2, which is next to bit 3 and so on) and bits 0 and 7 (for byte instructions) are also adjacent.

The two instructions are:


 ROR.data type n, operand  rotate the operand to the right by n bits. To the right means
towards bit 0.
 ROL.data type n, operand  rotate the operand to the left by n bits.
So, assuming that the least significant byte of D0 is 01101101 then we have:

ROR.B #1, D0  produces 10110110


ROR.B #2, D0  produces 01011011
ROR.B #3, D0  produces 10101101

IWIZ Learners Institute of Technical education Pvt Ltd 109


Embedded Primitive Level

Similarly,

ROL.L #1, D0  produces 11011010


ROL.L #2, D0  produces 10110101
ROL.L #3, D0  produces 01101011
There two variations in which the X condition code participates in the rotate as one of
the bits. In this case the X bit appears in between the first and the last bits (bits 0 and 7 for
bytes, bits 0 and 15 for words and bits 0 and 31 for long words).

The following tables summarized all shifts and rotate instructions:

6.4.1 Synthesizing Multiplication Using Shifts and Additions


Multiplication is a commonly needed calculation. Multipliers, however, are relatively
expensive circuits and/or slow. For this reason but also as means of getting familiar with
shifts we now explain how multiplication can be implemented using just left shift and
addition instructions. At a high level, the key idea is to convert multiplication into a sum of
multiplications with just powers of two. This is easier understood using an example. Assume
we want to multiply the value in register D0 by 5. One alternative would be to add the value
in D0 five consecutive times. This quickly becomes impractical (for example, to multiply by
1000 we would need 1000 additions). An alternative is to analyze the multiplier to a sum of
powers of 2. So, 5 becomes (4 + 1). In turn 5 X D0 become 4 X d0 + 1 X d0. Similarly, 11 x
d0 can be rewritten as 8 x d0 + 2 x d0 + 1 x d0. The nice thing about using powers of two is
that the corresponding multiplications can be implemented via simple left shift instructions.

IWIZ Learners Institute of Technical education Pvt Ltd 110


Embedded Primitive Level

Here’s the code for multiplying d0 by 11 with the result stored in d1:
move.l d0, d1 ; make a copy of d0 in d1, so now d1 = d0 x 1
lsl.l #1, d0 ; d0 = d0 x 2
add.l d0, d1; d1 = d0 + d0 x 2
lsl.l #2, d0 ; d0 = d0 x 4 but since we changed d0 to 2 times its original value, now d0 is 8
times its original value
add.l d0, d1 ; d1 = d0 + d0 x 2 + d0 x 8
Here’s the code for multiplying d0 by 17:
move.l d0, d1 ; d1 = d0
lsl.l #4, d0 ; d0 = 16 x d0
add.l d0, d1 ; d1 = d0 + 16 x d0
In general, if we need to calculate A x B then looks at the binary representation of B
focusing on the bits that are 1. If B’s binary representation has a 1 at bit i, then we need to
include A x 2^i into our sum. So, if B = 10101 the sum will include the following terms: A x
2^0, A x 2^2 and A x 2^4.

6.5 DATA TRANSFER


MOV: Most of the data transfer instructions involve the use of the MOV opcode. The
table below gives a list of data transfer instructions that access internal data memory
space along with the addressing modes involved.

The upper 128 bytes of RAM space can be accessed only by indirect addressing, and
SFR space can be accessed only by direct addressing. The stack space resides in on-chip
RAM in addition, grows upward. The PUSH instruction first increments the Stack Pointer
(SP), then copies the byte into the stack. PUSH and POP use only direct addressing to
identify the byte being saved or restored, but the stack itself is accessed by indirect
addressing using the SP register. Instructions with MOVX work on data transfer that access
external RAM memory. Instructions with MOVC work on moving constants for reading
look-up tables in program memory. The Data transfer instructions include a 16-bit MOV that
can be used to initialize the Data pointer for look-up tables in program memory or for 16-bit
data memory accesses.

IWIZ Learners Institute of Technical education Pvt Ltd 111


Embedded Primitive Level

6.5.1 DATA TRANSFER INSTRUCTIONS – INTERNAL


 destination>, <source>: allows data to be transferred between any two internal RAM or
SFR locations
 Stack operations (pushing and popping data) are also internal data transfer instructions
 Pushing increments SP before writing the data
 Popping from the stack reads the data and decrements the SP
 8051 stack is kept in the internal RAM
 Example: stack pointer contains 07H and A contains 55H and B Contains 4AH. What
internal RAM locations are altered and what are their new values after the following
instructions?
 PUSH ACC
 PUSH F0H
 Instruction XCH A, <source> causes the accumulator and the address byte to exchange
data
 Instruction XCHD A, @Ri causes the low-order nibbles to be exchanged.
 Example: if A contains F3H, R1 contains 40H, and internal RAM address 40H contains
5BH, instruction XCHD A, @R1 leaves A containing FBH and internal
RAM location 40H containing 53H.
6.5.2 DATA TRANSFER INSTRUCTIONS – EXTERNAL
 Data transfer instructions that move data between internal and external memory use
indirect addressing
 The address could be one byte (residing in R0 or R1) or two bytes (residing in DPTR)
 16-bit addresses uses all Port 2 for high-byte and this port cannot be used for I/O
 8-bit addresses allow access to a small external memory
 MOVX is used for external data transfer
6.6 RAM
The 8051 has a separate memory space for code (programs) and data. We will refer
here to on-chip memory and external memory as shown in figure 1.5. In an actual
implementation the external memory may, in fact, be contained within the microcomputer
chip. However, we will use the definitions of internal and external memory to be consistent
with 8051 instructions, which operate on memory. Note, the separation of the code and data
memory in the 8051 architecture is a little unusual. The separated memory architecture is
referred to as Harvard architecture whereas Von Neumann architecture defines a system
where code and data can share common memory.

8051 chip FFF External

DATA
Internal
Memory 000 Memory

Internal
SFRs FFF External

Internal CODE
RAM
000 Memory
Figure 1.5 8051 Memory representation

IWIZ Learners Institute of Technical education Pvt Ltd 112


Embedded Primitive Level

6.6.1 EXTERNAL CODE MEMORY


The executable program code is stored in this code memory. The code memory size is
limited to 64KBytes (in a standard 8051). The code memory is read-only in normal operation
and is programmed under special conditions e.g. it is a PROM or a Flash RAM type of
memory.

6.6.2 EXTERNAL RAM DATA MEMORY


This is read-write memory and is available for storage of data. Up to 64KBytes of
external RAM data memory is supported (in a standard 8051).

6.6.3 INTERNAL MEMORY

The 8051’s on-chip memory consists of 256 memory bytes organized as follows:

First 128 bytes: 00h to 1Fh Register Banks


20h to 2Fh Bit Addressable RAM
30 to 7Fh General Purpose RAM

Next 128 bytes: 80h to FFh Special Function Registers


The first 128 bytes of internal memory is organized as shown in figure 1.6, and is referred to
as Internal RAM, or IRAM.

Figure 1.6 Organization of Internal RAM (IRAM) memory

We will discuss a few specific SFR registers here to help explain the SFR concept.
Other specific SFR will be explained later.

IWIZ Learners Institute of Technical education Pvt Ltd 113


Embedded Primitive Level

6.7 PORT REGISTERS SFR


The standard 8051 has four 8 bit I/O ports: P0, P1, P2 and P3.
For example Port 0 is a physical 8 bit I/O port on the 8051. Read (input) and write
(output) access to this port is done in software by accessing the SFR P0 register, which is
located at address 80h. SFR P0 is also bit addressable. Each bit corresponds to a physical I/O
pin on the 8051. Example access to port 0:
SETB P0.7 ; sets the MSB bit of Port 0
CLR P0.7 ; clears the MSB bit of Port 0
The operand P0.7 uses the dot operator and refers to bit 7 of SFR P0. The same bit
could be addressed by accessing bit location 87h. Thus the following two instructions have
the same meaning:
CLR P0.7
CLR 87h

6.8 PSW PROGRAM STATUS WORD


PSW, the Program Status Word is at address D0h and is a bit-addressable register.
The status bits are listed in table 1.1.
TABLE 1. 1. PROGRAM STATUS WORD (PSW) FLAGS
Symbol Address Description
Bit
C (or CY) PSW.7 D7h Carry flag
AC PSW.6 D6h Auxiliary carry flag
F0 PSW.5 D5h Flag 0
RS1 PSW.4 D4h Register bank select 1
RS0 PSW.3 D3h Register bank select 0
0V PSW.2 D2h Overflow flag
PSW.1 D1h Reserved
P PSW.0 D0h Even Parity flag

CARRY FLAG. C
This is a conventional carry, or borrows, flag used in arithmetic operations. The carry
flag is also used as the ‘Boolean accumulator’ for Boolean instruction operating at the bit
level. This flag is sometimes referenced as the CY flag.

AUXILIARY CARRY FLA-. AC

This is a conventional auxiliary carry (half carry) for use in BCD arithmetic.
FLAG 0. F0
This is a general-purpose flag for user programming.
Register bank select 0 and register bank select 1. RS0 and RS1
These bits define the active register bank (bank 0 is the default register bank).

IWIZ Learners Institute of Technical education Pvt Ltd 114


Embedded Primitive Level

OVERFLOW FLAG. OV
This is a conventional overflow bit for signed arithmetic to determine if the result of a
signed arithmetic operation is out of range.
EVEN PARITY FLAG. P
The parity flag is the accumulator parity flag, set to a value, 1 or 0, such that the number of
‘1’ bits in the accumulator plus the parity bit add up to an even number.

6.9 STACK POINTER


The Stack Pointer, SP, is an 8-bit SFR register at address 81h. The small address field
(8 bits) and the limited space available in the Internal RAM confines the stack size and this is
sometimes a limitation for 8051 programmers. The SP contains the address of the data byte
currently on the top of the stack. The SP pointer in initialized to a defined address. A new
data item is ‘pushed’ on to the stack using a PUSH instruction, which will cause the data item
to be written to address SP + 1. Typical instructions, which cause modification to the stack
are: PUSH, POP, LCALL, RET, RETI etc. The SP SFR, on start-up, is initialized to 07h so
this means the stack will start at 08h and expand upwards in Internal RAM. If register banks
1 to 3 are to be used the SP SFR should be initialized to start higher up in Internal RAM. The
following instruction is often used to initialize the stack:

MOV SP, #2Fh


6.10 DATA POINTER
The Data Pointer, DPTR, is a special 16-bit register used to address the external code
or external data memory. Since the SFR registers are just 8-bits wide the DPTR is stored in
two SFR registers, where DPL (82h) holds the low byte of the DPTR and DPH (83h) holds
the high byte of the DPTR. For example, if you want to write the value 46h to external data
memory location 2500h, you might use the following instructions:
MOV A, #46h ; Move immediate 8 bit data 46h to A (accumulator)
MOV DPTR, #2504h ; Move immediate 16 bit address value 2504h to A.
Now DPL holds 04h and DPH holds25h.
MOVX @DPTR, A ; Move the value in A to external RAM location 2500h.
Uses indirect addressing.
Note the MOVX (Move X) instruction is used to access external memory.

6.11 ACCUMULATOR

This is the conventional accumulator that one expects to find in any computer, which
is used to the hold result of various arithmetic and logic operations. Since the 8051
microcontroller is just an 8-bit device, the accumulator is, as expected, an 8 bit register.
The accumulator, referred to as ACC or A, is usually accessed explicitly using
instructions such as:
INC A ; Increment the accumulator
However, the accumulator is defined as an SFR register at address E0h. Therefore, the
following two instructions have the same effect:
MOV A, #52h ; Move immediate the value 52h to the accumulator

IWIZ Learners Institute of Technical education Pvt Ltd 115


Embedded Primitive Level

MOV E0h, #52h ; Move immediate the value 52h to Internal RAM location E0h,
Which is, in fact, the accumulator SFR register?
Usually the first method, MOV A, #52h, is used as this is the most conventional (and happens
to use less space, 2 bytes as oppose to 3 bytes!)

B REGISTER
The B register is an SFR register at addresses F0h that is bit-addressable. The B
register is used in two instructions only: i.e. MUL (multiply) and DIV (divide). The B register
can also be used as a general-purpose register.

6.12 PROGRAM COUNTER

The PC (Program Counter) is a 2 byte (16 bit) register, which always contains the
memory address of the next instruction to be executed. When the 8051 is reset the PC is
always initialized to 0000h. If a 2 byte instruction is executed the PC is incremented by 2 and
if a 3 byte instruction is executed the PC is incremented by three so as to correctly point to
the next instruction to be executed. A jump instruction (e.g. LJMP) has the effect of causing
the program to branch to a newly specified location, so the jump instruction causes the PC
contents to change to the new address value. Jump instructions cause the program to flow in a
non-sequential fashion.

6.13 SFR REGISTERS FOR THE INTERNAL TIMER


The set up and operation of the on-chip hardware timers will be described later, but
the associated registers are briefly described here:

TCON, the Timer Control register is an SFR at address 88h, which is bit-addressable.
TCON is used to configure and monitor the 8051 timers. The TCON SFR also contains some
interrupt control bits.

TMOD, the Timer Mode register is an SFR at address 89h and is used to define the
operational modes for the timers.

TL0 (Timer 0 Low) and TH0 (Timer 0 High) are two SFR registers addressed at 8Ah
and 8Bh respectively. The two registers are associated with Timer 0.

TL1 (Timer 1 Low) and TH1 (Timer 1 High) are two SFR registers addressed at 8Ch
and 8Dh respectively. These two registers are associated with Timer 1.

6.14 POWER CONTROL REGISTER


PCON (Power Control) register is an SFR at address 87h. It contains various control
bits including a control bit, which allows the 8051 to go to ‘sleep’ so as to save power when
not in immediate use.

6.15 SERIAL PORT REGISTERS


Programming of the on-chip serial communications port will be described later in the
text. The associated SFR registers, SBUF and SCON, are briefly introduced here, as follows:

The SCON (Serial Control) is an SFR register located at addresses 98h, and it is bit-
addressable. SCON configures the behavior of the on-chip serial port, setting up parameters

IWIZ Learners Institute of Technical education Pvt Ltd 116


Embedded Primitive Level

such as the baud rate of the serial port, activating send and/or receive data, and setting up
some specific control flags.
The SBUF (Serial Buffer) is an SFR register located at address 99h. SBUF is just a
single byte deep buffer used for sending and receiving data via the on-chip serial port
6.16 INTERRUPT REGISTERS
Interrupts will be discussed in more detail later. The associated SFR registers are:
IE (Interrupt Enable) is an SFR register at addresses A8h and is used to enable and
disable specific interrupts. The MSB bit (bit 7) is used to disable all interrupts.
IP (Interrupt Priority) is an SFR register at addresses B8h and it is bit addressable.
The IP register specifies the relative priority (high or low priority) of each interrupt. On the
8051, an interrupt may either be of low (0) priority or high (1) priority. .
6.17 ROM
ROM is an acronym for Read-Only Memory. It refers to computer memory chips
containing permanent or semi-permanent data. Unlike RAM, ROM is non-volatile; even after
you turn off your computer, the contents of ROM will remain.

Almost every computer comes with a small amount of ROM containing the boot
firmware. This consists of a few kilobytes of code that tell the computer what to do when it
starts up, e.g., running hardware diagnostics and loading the operating system into RAM. On
a PC, the boot firmware is called the BIOS.

6.18 HYBRID MEMORY


A microcontroller comprising: a first memory operable to store instructions for
normal operational use of the microcontroller; a second memory operable to store patch code
instructions during debugging of the instructions within the first memory; and a central
processing unit (CPU) operable to fetch the instructions from the first memory and the patch
code instructions from the second memory, wherein the second memory is operable to store
the instructions for normal operational use of the microcontroller or data after the debugging
of the instructions within the first memory is completed. Wherein the first memory is a read-
only memory and the second memory is a bi-dimensional random access memory (RAM)
array. The bi-dimensional random access memory (RAM) array comprises a plurality of
random access memories (Rams) of a pre-determined size. The pre-determined size is one of
8-bits, 16-bits, 32-bits, 64-bits, or 128-bits. The second memory is configured according to
one of the following storage configurations after the debugging of the instructions within the
first memory is completed: to only store the data, to only store the instructions for normal
operational use of the microcontroller, or to store both the data and the instructions for
normal operational use of the microcontroller. Further comprising a boundary register
operable to designate an instruction portion of the second memory for storing instructions and
designate a data portion of the second memory for storing data. Further comprising a third
memory operable to store data required by the CPU to execute the instructions in the first
memory. The microcontroller is a Harvard 8-bit data, 16-bit instruction microcontroller. A
method for executing instructions within a microcontroller, the method comprising: storing
instructions for normal operational use of the microcontroller in a first memory of the
microcontroller; storing patch code instructions in a second memory of the microcontroller,
the patch code instructions to be used during debugging of the instructions stored in the first
memory; fetching instructions from the first memory or the patch code instructions from the
second memory during the debugging of the instructions within the first memory, and

IWIZ Learners Institute of Technical education Pvt Ltd 117


Embedded Primitive Level

configuring the second memory to store the instructions for normal operational use of the
microcontroller or data after the debugging of the instructions within the first memory is
completed. Storing instructions for normal operational use of the microcontroller in a first
memory includes storing the instructions for normal operational use of the microcontroller in
a read-only memory; and storing patch code instructions in a second memory includes storing
the patch code instructions in a bi-dimensional random access memory (RAM) array. The bi-
dimensional random access memory (RAM) array comprises a plurality of random access
memories (Rams) of a pre-determined size. The pre-determined size is one of 8-bits, 16-bits,
32-bits, 64-bits, or 128-bits. configuring the second memory includes configuring the second
memory according to one of the following storage configurations after the debugging of the
instructions within the first memory is completed: to only store the data, to only store the
instructions for normal operational use of the microcontroller, or to store both the data and
the instructions for normal operational use of the microcontroller. Comprising designating an
instruction portion of the second memory for storing instructions and designating a data
portion of the second memory for storing data. Further comprising storing, in a third memory,
data required by the CPU to execute the instructions stored in the first memory. The
microcontroller is a Harvard 8-bit data, 16-bit instruction microcontroller.A system for
performing a specific task, the system comprising: a microcontroller operable to execute
instructions associated with the task, the microcontroller including, a first memory operable
to store the instructions associated with the task; a second memory operable to store patch
code instructions during debugging of the instructions associated with the task; and a central
processing unit (CPU) operable to fetch the instructions from the first memory and the patch
code instructions from the second memory, wherein the second memory is operable to store
the instructions associated with the task or data for performing the task after the debugging of
the instructions within the first memory is completed. The first memory is a read-only
memory and the second memory is a bi-directional random access memory (RAM) array.
The microcontroller is a Harvard 8-bit data, 16-bit instruction microcontroller. The system is
associated with one of a data storage system, wireless system, or a computer system

6.19 Summary
In this chapter we learned about Microcontroller
 Types of memories .
 Electrically erasable(but unlike EEPROM memory) it does not have such a great
number of cycles of writing and erasing at memory locations.
 It does not hold back the contents as the previous when there is supply shortage.
 Thus, program is not stored in it, but it Serves for different variables and inter-results.
 Boolean logic, rotateand swap instructions are covered in this chapter.
 Byte-level operations involve each individual bit of a source byte operating on the
same bit position in the destination byte; the results are put in the destination, while
the source is not changed.
Technical Question
1. What is Bit and Byte?
2. What is Bit manipulation?
3. What is difference between ROM and RAM?
4. What is data transfer?
5. How many instructions available in 8051?
Exercise
1. Find a number that, at pc from microcontroller using TMOD, SCON registers.
2. Write program to Specifying the ISR Register Bank

IWIZ Learners Institute of Technical education Pvt Ltd 118


Embedded Primitive Level

CHAPTER -7

INTERRUPT

About this Chapter

 This chapter will give information about interrupts and its types.
 We can learn about how to debug an interrupt.

After this Chapter


 You can able to know the different types of interrupts.
 You can able to debug the interrupt and run the program.

7.1INTERRUPT

An interrupt is the occurrence of a condition--an event -- that causes a temporary


suspension of a program while the event is serviced by another program (Interrupt Service
Routine ISR or Interrupt Handler). Interrupt-Driven System-- gives the illusion of doing
many things simultaneously, quick response to events, suitable for real-time control
application.

 Base level - Interrupted program, foreground.


 Interrupt level --ISR, background.

7.1.1 What Events Can Trigger Interrupts:

We can configure the 8051 so that any of the following events will cause an interrupt:

 Timer 0 Overflow.
 Timer 1 Overflow.
 Reception/Transmission of Serial Character.
 External Event 0.
 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.

Obviously we need to be able to distinguish between various interrupts and executing


different code depending on what interrupt was triggered. This is accomplished by jumping to
a fixed address when a given interrupt occurs.

Interrupt Flag Interrupt Handler Address


External 0 IE0 0003h
Timer 0 TF0 000Bh
External 1 IE1 0013h
Timer 1 TF1 001Bh
Serial RI/TI 0023h

IWIZ Learners Institute of Technical education Pvt Ltd 119


Embedded Primitive Level

By consulting the above chart we see that whenever Timer 0 overflows (i.e., the TF0
bit is set), the main program will be temporarily suspended and control will jump to 000BH.
It is assumed that we have code at address 000BH that handles the situation of Timer 0
overflowing.

 Setting up Interrupts

By default at powerup, all interrupts are disabled. This means that even if, for
example, the TF0 bit is set, the 8051 will not execute the interrupt. Your program must
specifically tell the 8051 that it wishes to enable interrupts and specifically which interrupts it
wishes to enable.

Your program may enable and disable interrupts by modifying the IE SFR (A8h):

Bit Name BIT ADDRESS Explanation of Function


7 EA AFH Global Interrupt Enable/Disable
6 - AEH Undefined
5 - ADH Undefined
4 ES ACH Enable Serial Interrupt
3 ET1 ABH Enable Timer 1 Interrupt
2 EX1 AAH Enable External 1 Interrupt
1 ET0 A9H Enable Timer 0 Interrupt
0 EX0 A8H Enable External 0 Interrupt

As you can see, each of the 8051s interrupts has its own bit in the IE SFR. You enable
a given interrupt by setting the corresponding bit. For example, if you wish to enable Timer 1
Interrupt, you would execute either:

 MOV IE, #08h


[Or
 SETB ET1
Both of the above instructions set bit 3 of IE, thus enabling Timer 1 Interrupt. Once
Timer 1 Interrupt is enabled, whenever the TF1 bit is set, the 8051 will automatically put "on
hold" the main program and execute the Timer 1 Interrupt Handler at address 001Bh.

However, before Timer 1 Interrupt (or any other interrupt) is truly enabled, you must
also set bit 7 of IE. Bit 7, the Global Interrupt Enable/Disable, enables or disables all
interrupts simultaneously. That is to say, if bit 7 is cleared then no interrupts will occur, even
if all the other bits of IE are set. Setting bit 7 will enable all the interrupts that have been
selected by setting other bits in IE. This is useful in program execution if you have time-
critical code that needs to execute. In this case, you may need the code to execute from start
to finish without any interrupt getting in the way. To accomplish this you can simply clear bit
7 of IE (CLR EA) and then set it after your time-critical code is done.

So, to sum up what has been stated in this section, to enable the Timer 1 Interrupt the
most common approach is to execute the following two instructions?

IWIZ Learners Institute of Technical education Pvt Ltd 120


Embedded Primitive Level

 SETB ET1

 SETB EA

Thereafter, the Timer 1 Interrupt Handler at 01Bh will automatically be called


whenever the TF1 bit is set (upon Timer 1 overflow).

7.2 POLLING SEQUENCE

The 8051 automatically evaluates whether an interrupt should occur after every
instruction. When checking for interrupt conditions, it checks them in the following order:

• External 0 Interrupt
• Timer 0 Interrupt
• External 1 Interrupt
• Timer 1 Interrupt
• Serial Interrupt

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.

7.2.1 Interrupt Priorities

The 8051 offers two levels of interrupt priority: high and low. By using interrupt
priorities you may assign higher priority to certain interrupt conditions.

• Contrast edge-triggered with level-triggered interrupts


• Program the 8051 for interrupt-based serial communication
• Define the interrupt priority of the 8051

For example, you may have enabled Timer 1 Interrupt, which is automatically called
every time Timer 1 overflows. Additionally, you may have enabled the Serial Interrupt,
which is called every time a character is received via the serial port. However, you may
consider that receiving a character is much more important than the timer interrupt. In this
case, if Timer 1 Interrupt is already executing you may wish that the serial interrupt itself
interrupts the Timer 1 Interrupt. When the serial interrupt is complete, control passes back to
Timer 1 Interrupt and finally back to the main program. You may accomplish this by
assigning a high priority to the Serial Interrupt and a low priority to the Timer 1 Interrupt.

Interrupt priorities are controlled by the IP SFR (B8h). The IP SFR has the following
format:

IWIZ Learners Institute of Technical education Pvt Ltd 121


Embedded Primitive Level

Bit Name Bit Address Explanation of Function


7 - - Undefined
6 - - Undefined
5 - - Undefined
4 PS BCh Serial Interrupt Priority
3 PT1 BBh Timer 1 Interrupt Priority
2 PX1 BAh External 1 Interrupt Priority
1 PT0 B9h Timer 0 Interrupt Priority
0 PX0 B8h External 0 Interrupt Priority

When considering interrupt priorities, the following rules apply:

• Nothing can interrupt a high-priority interrupt--not even another high priority


interrupt.
• A high-priority interrupt may interrupt a low-priority interrupt.
• A low-priority interrupt may only occur if no other interrupt is already executing.
• If two interrupts occur at the same time, the interrupt with higher priority will execute
first. If both interrupts are of the same priority the interrupt, which is serviced first by
polling sequence, will be executed first.

7.2.2 What Happens When an Interrupt Occurs?

When an interrupt is triggered, the following actions are taken automatically by the
microcontroller:

• The current Program Counter is saved on the stack, low-byte first.


• Interrupts of the same and lower priority are blocked.
• In the case of Timer and External interrupts, the corresponding interrupt flag is
cleared.
• Program execution transfers to the corresponding interrupt handler vector address.
• The Interrupt Handler Routine executes.

Take special note of the third step: If the interrupt being handled is a Timer or
External interrupt, the microcontroller automatically clears the interrupt flag before passing
control to your interrupt handler routine. This means it is not necessary that you clear the bit
in your code.

7.3 SERIAL INTERRUPTS

Serial Interrupts are slightly different than the rest of the interrupts. This is due to the
fact that there are two interrupt flags: RI and TI. If either flag is set, a serial interrupt is
triggered. As you will recall from the section on the serial port, the RI bit is set when a byte is
received by the serial port and the TI bit is set when a byte has been sent.

This means that when your serial interrupt is executed, it may have been triggered
because the RI flag was set or because the TI flag was set--or because both flags were set.
Thus, your routine must check the status of these flags to determine what action is

IWIZ Learners Institute of Technical education Pvt Ltd 122


Embedded Primitive Level

appropriate. Also, since the 8051 does not automatically clear the RI and TI flags you must
clear these bits in your interrupt handler.

A brief code example is in order:

INT_SERIAL: JNB RI,CHECK_TI ;If the RI flag is not set, we jump to check TI
MOV A,SBUF ;If we got to this line, its because the RI bit *was* set
CLR RI ;Clear the RI bit after wave processed it
CHECK_TI: JNB TI,EXIT_INT ;If the TI flag is not set, we jump to the exit point
CLR TI ;Clear the TI bit before we send another character
MOV SBUF,#A ;Send another character to the serial port
EXIT_INT: RETI

As you can see, our code checks the status of both interrupts flags. If both flags were
set, both sections of code will be executed. Also note that each section of code clears its
corresponding interrupt flag. If you forget to clear the interrupt bits, the serial interrupt will
be executed over and over until you clear the bit. Thus it is very important that you always
clear the interrupt flags in a serial interrupt.

7.3.1 Important Interrupt Consideration: Register Protection

One very important rule applies to all interrupt handlers: Interrupts must leave the
processor in the same state as it was in when the interrupt initiated.

Remember, the idea behind interrupts is that the main program isn’t aware that they
are executing in the "background." However, consider the following code:

CLR C; Clear carry


MOV A,#25h ;Load the Accumulator with 25h
ADDC A,#10h ;Add 10h, with carry

After the above three instructions are executed, the accumulator will contain a value
of 35h.

But what would happen if right after the MOV instruction an interrupt occurred.
During this interrupt, the carry bit was set and the value of the accumulator was changed to
40h. When the interrupt finished and control was passed back to the main program, the
ADDC would add 10h to 40h, and additionally add an additional 1h because the carry bit is
set. In this case, the accumulator will contain the value 51h at the end of execution.

In this case, the main program has seemingly calculated the wrong answer. How can
25h + 10h yield 51h as a result? It doesn’t make sense. A programmer that was unfamiliar
with interrupts would be convinced that the microcontroller was damaged in some way,
provoking problems with mathematical calculations.

What has happened, in reality, is the interrupt did not protect the registers it used.
Restated: An interrupt must leave the processor in the same state as it was in when the
interrupt initiated.

IWIZ Learners Institute of Technical education Pvt Ltd 123


Embedded Primitive Level

What does this mean? It means if your interrupt uses the accumulator, it must insure
that the value of the accumulator is the same at the end of the interrupt as it was at the
beginning. This is generally accomplished with a PUSH and POP sequence. For example:

PUSHACC
PUSHPSW
MOVA,#0FFh
ADDA,#02h
POPPSW
POP ACC

The guts of the interrupt are the MOV instruction and the ADD instruction. However,
these two instructions modify the Accumulator (the MOV instruction) and also modify the
value of the carry bit (the ADD instruction will cause the carry bit to be set). Since an
interrupt routine must guarantee that the registers remain unchanged by the routine, the
routine pushes the original values onto the stack using the PUSH instruction. It is then free to
use the registers it protected to its hearts content. Once the interrupt has finished its task, it
pops the original values back into the registers. When the interrupt exits, the main program
will never know the difference because the registers are exactly the same as they were before
the interrupt executed.

In general, your interrupt routine must protect the following registers:

• PSW
• DPTR (DPH/DPL)
• PSW
• ACC
• B
• Registers R0-R7

Remember that PSW consists of many individual bits that are set by various 8051
instructions. Unless you are absolutely sure of what you are doing and have a complete
understanding of what instructions set what bits, it is generally a good idea to always protect
PSW by pushing and popping it off the stack at the beginning and end of your interrupts.

Note also that most assemblers (in fact, ALL assemblers that I know of) will not allow
you to execute the instruction:

PUSH R0
This is due to the fact that depending on which register bank is selected, R0 may refer
to either internal ram address 00h, 08h, 10h, or 18h. R0, in and of itself, is not a valid
memory address that the PUSH and POP instructions can use.

Thus, if you are using any "R" register in your interrupt routine, you will have to push
that registers absolute address onto the stack instead of just saying PUSH R0. For example,
instead of PUSH R0 you would execute:

IWIZ Learners Institute of Technical education Pvt Ltd 124


Embedded Primitive Level

PUSH 00h
Of course, this only works if you’ve selected the default register set. If you are using
an alternate register set, you must PUSH the address, which corresponds, to the register you
are using.

7.4 DEBUGGING ISRS

Few embedded systems are so simple they can work without at least a few interrupt
sources. Few designers manage to get their product to market without suffering metaphorical
scars from battling interrupt service routines (ISRs).

There's no science to debugging these beasts, which are often the most complex part
of any real time system. Too many of us become experts at ISRs the same way we picked up
the secrets of the birds and the bees - from quick conversations in the halls and on the streets
with our pals. There's got to be a better way!

7.4.1 Vector Overview


One common complaint against interrupts is that they are difficult to understand.
There is an element of truth to this, especially for first time users. However, just as we all
somehow shattered our parents' nerves and learned to drive a stick-shift, we can overcome
inexperience to be competent at interrupt-based design.

Fortunately there are only a few ways that interrupts are commonly handled. By far
the most prevalent is the Vectored scheme. A hardware device, either external to the chip or
an internal I/O port (as on a high integration CPU like the 188 or 68332) asserts the CPU's
interrupt input.

If interrupts are enabled (via an instruction like STI or EI), and if that particular
interrupt is not masked off (high integration processors almost always have some provision to
selectively enable interrupts from each device), then the processor responds to the interrupt
request with some sort of acknowledge cycle.

The requesting device then supplies a Vector, typically a single byte pointer to a table
maintained in memory. The table contains at the very least a pointer to the ISR.

The CPU pushes the program counter so at the conclusion of the interrupt the ISR can
return to where the program was running. Some CPUs push other data as well, like the flag
register. It then uses the vector to look up the ISR address and branches to the routine.

At first glance the vectoring seems unnecessarily complicated. Its great advantage is
support for many varied interrupt sources. Each device inserts a different vector; each vector
invokes a different ISR. Your UART Data Ready ISR called independently of the UART
Transmit_Buffer_Full interrupt.

7.4.2 C or Assembly?

If you've followed my suggestions you have a complete interrupt map with an


estimated maximum execution time for the ISR. You're ready to start coding... right?

IWIZ Learners Institute of Technical education Pvt Ltd 125


Embedded Primitive Level

If the routine will be in assembly language, convert the time to a rough number of
instructions. If an average instruction takes x microseconds (depending on clock rate, wait
states and the like), then it's easy to get this critical estimate of the code's allowable
complexity.

C is more problematic. In fact, there's no way to scientifically write an interrupt


handler in C! You have no idea how long a line of C will take. You can't even develop an
estimate as each line's time varies wildly. A string compare may result in a runtime library
call with totally unpredictable results. A FOR loop may require a few simple integer
comparisons or a vast amount of processing overhead.

Therefore,, we write our C functions in a fuzz of ignorance, having no concept of


execution times until we actually run the code. If it's too slow, well, just change something
and try again!

An old software adage recommends coding for functionality first, and speed second.
Since 80% of the speed problems are usually in 20% of the code, it makes sense to get the
system working and then determine where the bottlenecks are. Unfortunately, real time
systems by their nature usually don't work at all if things are slow. You've often got to code
for speed up front.

If the interrupts are coming fast - a term that is purposely vague and qualitative,
measured by experience and gut feel - then I usually just take the plunge and code the silly
thing in assembly. Why cripple the entire system due to little bit of interrupt code? If you
have broken the ISRs into small chunks, so the real time part is small, then little assembly
will be needed.

7.5 DEBUGGING INT/INTA CYCLES

Before you can debug your ISR, the processor must accept the interrupt and properly
vector to the handler. Most processors service an interrupt with the following steps:
Your hardware generates the interrupt pulse

• The interrupt controller (if any) prioritizes multiple simultaneous requests, and issues
a single interrupt to the processor
• The CPU responds with an interrupt acknowledge cycle
• The controller drops an interrupt vector on the data bus
• The CPU reads the vector, and computes the address of the user-stored vector in
memory. It then fetches this value.
• The CPU pushes the current context, disables interrupts, and jumps to the ISR

Interrupts from internal peripherals (those on the CPU itself) will generally not
generate an external interrupt acknowledge cycle. The vectoring is handled internally and
invisibly to the wary programmer, tools in hand, trying to discover his system's faults.

A generation of structured programming advocates has caused many of us to


completely design the system and write all of the code before debugging. Though this is
certainly a nice goal, it's a mistake for the low level drivers in embedded systems. I believe in
an early wrestling match with the system's hardware. Connect an emulator, and exercise the
I/O ports. They never behave quite how you expected. Bits might be inverted or transposed,

IWIZ Learners Institute of Technical education Pvt Ltd 126


Embedded Primitive Level

or maybe there's a dozen complex configuration registers needing setup. Work with your
system, understand its quirks, and develop notes about how to drive each I/O device. Use
these notes to write your code.

7.5.1 Debugging Speed Problems

If the ISR is not fast enough ;your system will fail. Unfortunately, few of the
developers I talk to have any idea what "fast enough" means. Unless you generate the
interrupt map I've discussed, only random luck will save you from speed problems.

Assume each ISR will be too slow, and plan accordingly. A performance analyzer
will instantly show the minimum, maximum, and average execution time required by your
code, including your ISRs.

Set a bit to a one when the ISR starts, and set it to zero when it completes. Connect a
scope and measure how long the bit says up. If the routine can run for varying lengths of
time, use a digital scope set to accumulate sweeps, and watch for the longest iteration.

It's important to look at total interrupt overhead in a system as well. If your ISR runs
in 100 microseconds, but gets invoked 10,000 times/second, there's serious trouble brewing.
Watch how long the bit stays asserted over long periods of time - a second or more - and
make sure it's not eating most of the CPU resources.

Set and reset this bit in all of the ISRs to see total interrupt overhead. It's sometimes
frightening to see just how close to the wire some systems run!

7.5.2 Debugging Reentrancy problems


Well designed interrupt handlers are largely re-entrant. Reentrant functions, AKA
"pure code", are often falsely thought to be any code that does not modify itself. Too many
programmers feel if they simply avoid self-modifying code, then their routines are guaranteed
to be reentrant, and thus interrupt-safe. Nothing could be further from the truth.

A function is reentrant if, while it is being executed, it can be re-invoked by itself, or


by any other routine.

Suppose your main line routine and the ISRs are all coded in C. The compiler will
certainly invoke runtime functions to support floating point math, I/O, string manipulations,
etc. If the runtime package is only partially reentrant, than your ISRs may very well corrupt
the execution of the main line code. This problem is common, but is virtually impossible to
troubleshoot since symptoms result only occasionally and erratically. Can you imagine the
difficulty of isolating a bug which manifests itself only occasionally and with totally different
characteristics each time?

If you’re ISR merely increments a global 32 bit value, say, to maintain time, it would
seem legal to produce code that does nothing more than a quick and dirty increment.
Especially when writing code on an 8 or 16 bit processor, remember that the C compiler will
surely generate several instructions to do the deed. On a 186, the construct ++j might
produce:

IWIZ Learners Institute of Technical education Pvt Ltd 127


Embedded Primitive Level

mov ax,[j]

add ax, 1 ; increment low part of j


mov [j], ax
mov ax,[j+1]
ADC ax,0 ; prop carry to high part of j
mov [j+1],ax

An interrupt in the middle of this code will leave j just partially changed; if the ISR is
reincarnated with j in transition, its value will surely be corrupt.

Watch out for noise on the NMI line. NMI is usually an edge-triggered signal. Any bit
of noise will cause perhaps hundreds of interrupts. Since it cannot be masked, you'll almost
certainly cause a reentrancy problem. This is yet another reason to avoid NMI for anything
other than a catastrophic failure.

Even the perfectly coded reentrant ISR leads to problems. If such a routine runs so
slowly that interrupts keep giving birth to additional copies of it, eventually the stack will fill.
Once the stack bangs into your variables the program is on its way to oblivion. You must
insure that the average interrupt rate is such that the routine will return more often than it is
invoked.

7.5.3Debugging Stack Problems


Any of a number of problems can cause the stack to grow to the point where the entire
system crashes. It's tough to go back and analyze the failure after the crash, as the program
will often write all over itself or the variables, removing all clues.

The best defense is a strong offense. Build a stack monitor into your code.

A stack monitor is just a few lines of assembly language that compares the stack
pointer to some limit you've set. Estimate the total stack use, and then double or triple the
size. Use this as the limit.

Put the stack monitor into one or more frequently called ISRs. Jump to a null routine,
where a breakpoint is set, when the stack grows too much.

Be sure that the compare is "fuzzy". The stack pointer will never exactly match the
limit.

7.6 Summary

 The wide use of C makes assembly-competent developers a scarce resource.


 Embedded systems are the last bastion of assembly, and will probably always require
some amount of it.
 Interrupt handling using C language/ Keil software.

IWIZ Learners Institute of Technical education Pvt Ltd 128


Embedded Primitive Level

Technical Question

1. What is interrupt?
2. What are types of interrupt?
3. What is Interrupt Priorities?
4. What is vector interrupt?
5. What Happens When an Interrupt Occurs?
6. What is the difference between the RET and RET1 instructions?

7.7 Exercise

1. Write a C program that continuously gets a single bit of data from P1.7 and sends it to
P1.0 in the main, while simultaneously
a. Creating a squire wave of 200 micro sec period on pin P2.5, and
b. Sending letter ‘A’ to the serial port. Use Timer 0 to create the square wave.
2. Write a C program using interrupts to do the following:
a. Receive data serially and send it to P0.
b. Read port P1, transmit data serially and give a copy to P2,
c. Make timer 0 generate a square wave of 8 kHz frequency on P0.1.

IWIZ Learners Institute of Technical education Pvt Ltd 129


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 130


Embedded Primitive Level

CHAPTER -8

PERIPHERAL DEVICE
About this Chapter

This chapter gives information about different types of display units.


 You will learn how to interface LED and LCD.

After this Chapter


 You can be able to display characters and numbers using an array and pointer.
 You will be well-versed in interfacing with Seven Segment Display.

8. SEVEN SEGMENT DISPLAY

8.1 Introduction

One common requirement for many different digital devices is a visual numeric
display. Individual LEDs can of course display the binary states of a set of latches or flip-
flops. However, we're far more used to thinking and dealing with decimal numbers. To this
end, we want a display of some kind that can clearly represent decimal numbers without any
requirement of translating binary to decimal or any other format.

One possibility is a matrix of 28 LEDs in a 7×4 array. We can then light up selected
LEDs in the pattern required for whatever character we want. Indeed, an expanded version of
this is used in many ways, for fancy displays. However, if all we want to display is numbers,
this becomes a bit expensive. A much better way is to arrange the minimum possible number
of LEDs in such a way as to represent only numbers in a simple fashion.

This requires just seven LEDs (plus an eighth one for the decimal point, if that is
needed). A common technique is to use a shaped piece of translucent plastic to operate as a
specialized optical fiber, to distribute the light from the LED evenly over a fixed bar shape.
The seven bars are laid out as a squared-off figure given blow. The result is known as a
seven-segment LED.

We've all seen seven-segment displays in a wide range of applications.


Clocks, watches, digital instruments, and many household appliances already have such
displays. In this experiment, we'll look at what they are and how they can display any of the
ten decimal digits 0-9 on demand.

Character display that is commonly used these days is called seven segment displays
because they are easy to read under low ambient light. Another type of display is called LCD
display, which is useful in low power, or battery operated system. Unlike LEDs, LCDs are
visible in bright ambient light. Since LCDs do not emit light, they are visible in low light
environment. These days, a combination of LCDs and LEDs are used to enable LCDs to be
visible even in low ambient light environment. LCDs are not efficient at low temperature
environment. The characters size available are in 0.3 inch, 0.6 inch and larger sizes

IWIZ Learners Institute of Technical education Pvt Ltd 131


Embedded Primitive Level

8.2 Seven-segment display layout:

The illustration to the above shows the basic layout of the segments in a seven-
segment display. The segments themselves are identified with lower-case letters "a" through
"g," with segment "a" at the top and then counting clockwise. Segment "g" is the center bar.

Most seven-segment digits also include a decimal point ("dp"), and some also include
an extra triangle to turn the decimal point into a comma. This improves readability of large
numbers on a calculator, for example. The decimal point is shown here on the right, but some
display units put it on the left, or have a decimal point on each side.

In addition, most displays are actually slanted a bit, making them look as if they were
in italics. This arrangement allows us to turn one digit upside down and place it next to
another, so that the two decimal points look like a colon between the two digits. The
technique is commonly used in LED clock displays.

Seven-segment displays can be packaged in a number of ways. Three


typical packages are shown above. On the left we see three small digits in a single 12-pin
DIP package. The individual digits are very small, so a clear plastic bubble is molded over
each digit to act as a magnifying lens. The sides of the end bubbles are flattened so that
additional packages of this type can be placed end-to-end to create a display of as many digits
as may be needed.

The second package is essentially a 14-pin DIP designed to be installed vertically.


Note that for this particular device, the decimal point is on the left. This is not true of all
seven-segment displays in this type of package.

One limitation of the DIP package is that it cannot support larger digits. To get larger
displays for easy reading at a distance, it is necessary to change the package size and shape.
The package on the right above is larger than the other two, and thus can display a digit that
is significantly larger than will fit on a standard DIP footprint. Even larger displays are also
available; some digital clocks sport digits that are two to five inches tall.

Seven-segment displays can be constructed using any of a number of different


technologies. The three most common methods are fluorescent displays (used in many line-
powered devices such as microwave ovens and some clocks and clock radios), liquid crystal
displays (used in many battery-powered devices such as watches and many digital
instruments), and LEDs (used in either line-powered or battery-powered devices). However,
fluorescent displays require a fairly high driving voltage to operate, and liquid crystal

IWIZ Learners Institute of Technical education Pvt Ltd 132


Embedded Primitive Level

displays require special treatment that we are not yet ready to discuss. Therefore, we will
work with a seven-segment LED display in this experiment.

8.3 Seven Segment Display Types

Seven segment displays can be divided into 2 types of connection. One is called
common anode of which all the anodes of the LEDs are connected together, leaving the
cathodes open for connection. The other one is called common cathode of which all the
cathodes of the LEDs are connected together, leaving the anodes open for connection.

8.4 Connection Diagram

IWIZ Learners Institute of Technical education Pvt Ltd 133


Embedded Primitive Level

8.5 Pin Connections of 4511 Decoder

8.5.1 Truth Table:

BCD Inputs Segment outputs Display


D C B A a b c d e f g

0 0 0 0 1 1 1 1 1 1 0

0 0 0 1 0 1 1 0 0 0 0

0 0 1 0 1 1 0 1 1 0 1

0 0 1 1 1 1 1 1 0 0 1

0 1 0 0 0 1 1 0 0 1 1

0 1 0 1 1 0 1 1 0 1 1

0 1 1 0 0 0 1 1 1 1 1

0 1 1 1 1 1 1 0 0 0 0

1 0 0 0 1 1 1 1 1 1 1

1 0 0 1 1 1 1 0 0 1 1

IWIZ Learners Institute of Technical education Pvt Ltd 134


Embedded Primitive Level

There are two important types of 7-segment LED display. In a common cathode
display, the cathodes of all the LEDs are joined together and the individual segments are
illuminated by HIGH voltages. In a common anode display, the anodes of all the LEDs are
joined together and the individual segments are illuminated by connecting to a LOW voltage.

The 4511 is designed to drive a common cathode display and won't work with a
common anode display. You need to check that you are using the right kind of display before
you start building.

8.5.2 Basic Operation:

In normal operation, the lamp test and ripple blanking inputs are connected HIGH,
and the enable (store) input is connected LOW. The circuit diagram shows the 4511 and a 7-
segment common cathode display connected to the outputs of a 4510 BCD counter:

When the lamp test input, pin 3, is made LOW, all the segment outputs go HIGH
regardless of all other input conditions.

With lamp test HIGH, if the ripple blanking input, pin 4, is made LOW, all the
segment outputs are forced LOW. This input can be used to blank leading zeros in a multi-
digit display.

The enable input controls the action of a 4-bit latch inside the 4511. With enable
LOW, the outputs of the latch follow the logic states of the BCD inputs and the 7-segment
outputs change accordingly. If enable is made HIGH, the logic states present on the BCD
inputs are stored. The 7-segment outputs remain unchanged until enable is made LOW once
more. This action allows the display to be updated at intervals.

When you need these inputs, you can work out how to use them by investigating the
behavior of the 4511 in a prototype circuit.

8.6 Pin connections of 4510 bcd converter

IWIZ Learners Institute of Technical education Pvt Ltd 135


Embedded Primitive Level

8..6.1 Truth Table

Pulses Output D Output C Output B Output A


0 0 0 0 0
1 0 0 0 1
2 0 0 1 0
3 0 0 1 1
4 0 1 0 0
5 0 1 0 1
6 0 1 1 0
7 0 1 1 1
8 1 0 0 0
9 1 0 0 1
10 0 0 0 0
11 0 0 0 1
: : : : :

BCD stands for Binary Coded Decimal. A BCD counter has four outputs usually
labeled A, B, C, and D. By convention A is the least significant bit, or LSB. The easiest way
to understand what a BCD counter does is to follow the counting sequence in truth table.

When pulses are delivered to the CLOCK input (and all the other connections needed
for basic operation are made), the outputs of the 4510 follow a sequence starting from 0 0 0 0
up to 1 0 0 1, the binary equivalent of the decimal number 9. The next pulse causes the 4510
to RESET and counting starts again from 0 0 0 0.

In other words, the counter outputs follow a binary sequence representing the decimal
numbers 0-9.... this is why the 4510 is called a binary coded decimal counter.

8.6.2 Basic Operation

To make the 4510 work, you need lots of connections. Every INPUT of a CMOS
integrated circuit must be connected to something. The CLOCK input, for example, will be
connected to the output of source of pulses such as an astable. You will also need to connect
all the load inputs, the carry in and the up/down input.

The 4093 Schmitt trigger NAND gate provides one of the easiest ways of making an
astable. When you have built this part of the circuit, the LED next to the 4093 should flash at
approximately 1 Hz, possibly a little faster

IWIZ Learners Institute of Technical education Pvt Ltd 136


Embedded Primitive Level

8.6.3 Applications

For industrial and consumer applications such as:


 Digital readout displays
 Instrument panels
 Point of sale equipment
 Digital clocks
 TV and radios

8.7. LIQUID. CRYSTAL DISPLAY

8.7.1 Introduction

Liquid Crystal Display (LCD) is the one of the important Display devices in
Embedded System. As we know already the Embedded System has the very limited input and
output devices. To know the stage of embedded system as well as to view the output we
require the one detailed output and/or display devices. One among the best is LCD display.

Other output display devices are LED and 7Segment LED. The comparison leads to
find out the merits and demerits of the LCD displays

8.7.2 Comparison between LCD and 7Segment LED Display

LCD Display LED Display


Can Display all Alpha Numerical Can Display Only Limited
Values Characters

It requires External Light to view It does not require external light


The Display generates the light.

Costly Cheaper

8.7.3 Type of LCD Display


 16x2 LCD display
 16x4 LCD display
 Graphical Display
 Mobile phone displays
 Color Displays……
8.7.4 Features
 5 ´ 8 and 5 ´ 10 dot matrix possible
 Low power operation support:
 Wide range of liquid crystal display driver power
 Correspond to high speed MPU bus interface
 4-bit or 8-bit MPU interface enabled
 64 ´ 8-bit character generator RAM
 Wide range of instruction functions:

IWIZ Learners Institute of Technical education Pvt Ltd 137


Embedded Primitive Level

 Display clear, cursor home, display on/off, cursor on/off, display character blink,
cursor shift, display shift
 Automatic reset circuit that initializes the controller/driver after power on
 Internal oscillator with external resistors
 Low power consumption

8.7.5 Working Principle


Liquid Crystal Display has two transparent layers. The gap between two transparent
layers is filled with liquid crystal. The molecules in liquid crystal are arranged in order. When
the voltage is passed through the Liquid crystal, they become to move randomly. That
random movement is visualized. Hence the Liquid Crystal Display requires external light to
visualize

8.7.6 Pin Details


1-Gnd
2-Vcc
3-Variable Contrast
4-RS
5-RW
6-EN
7 to 14 – Data Lines

8.7.7 Circuit Diagram

8.7.8 Circuit Description

Above is the quite simple schematic. The LCD panel's Enable and Register Select is
connected to the Control Port. The Control Port is an open collector / open drain output.
While most Parallel Ports have internal pull-up resistors, there are a few which don't.
Therefore by incorporating the two 10K external pull up resistors, the circuit is more portable
for a wider range of computers, some of which may have no internal pull up resistors.

IWIZ Learners Institute of Technical education Pvt Ltd 138


Embedded Primitive Level

We make no effort to place the Data bus into reverse direction. Therefore we hard
wire the R/W line of the LCD panel, into write mode. This will cause no bus conflicts on the
data lines. As a result we cannot read back the LCD's internal Busy Flag, which tells us if the
LCD has accepted and finished processing the last instruction. This problem is overcome by
inserting known delays into our program. The 10k Potentiometer controls the contrast of the
LCD panel.

8.7.9 Steps to display a character

 Initialize the LCD.


 Set the Address.
 Feed the corresponding ASCII value.

8.7.10 Applications

 Battery operated handheld devices


 Exercise equipment
 Heart rate monitors
 Cycling computers
 Glucose monitors
 Personal diagnostics
 Portable medical devices
 Security systems
 Low-end utility metering
 ZigBee nodes with display
 Multimeters
 Telephone displays
 Settings and memory info on digital cameras
 External caller ID on low end cellular phones

Summary

 Seven-segment displays are used in a wide range of applications like Clocks,


watches, digital instruments, and many household appliances.

 Character display is commonly used these days are called seven segment displays
because they are easy to read under low ambient light.

 Seven segment displays can be divided into 2 types of connection. One is called
common anode of which all the anodes of the LEDs are connected together, leaving
the cathodes open for connection.

 The other one is called common cathode of which all the cathodes of the LEDs are
connected together, leaving the anodes open for connection.
 Liquid Crystal Display has two transparent layers. The gap between two transparent
layers is filled with liquid crystal.

 The molecules in liquid crystal are arranged in order. When the voltage is passed
through the Liquid crystal, they become to move randomly.

IWIZ Learners Institute of Technical education Pvt Ltd 139


Embedded Primitive Level

Technical Question
1. Different type of seven segment display?
2. Different between LCD and 7 segment display.
3. Write the LCD pin details?
4. Explain function of LCD control pins?
5. Different type of command using in LCD?

Exercise
1. Write a program to get a data from a peripheral and display it using LCD.

IWIZ Learners Institute of Technical education Pvt Ltd 140


Embedded Primitive Level

CHAPTER 9

ANALYSING ANALOG TO DIGITAL SIGNAL

ABOUT THIS CHAPTER

 This chapter will give information about ADC, DAC and Keypad.
 You can learn how to interface the above mentioned peripherals to the
controller.

After this Chapter


 You can be able to fetch data from an ADC and handle DAC.
 You can be able to send data to the controller using keypad.
9.1 INTRODUCTION

ignals in the real world are analog: light, sound, etc.Therefore, real-world signals must
be converted into digital, using a circuit called ADC (Analog-to-Digital Converter), before
they can be manipulated by digital equipment. In this tutorial we will give an in-depth
explanation about analog-to-digital conversion yet keeping a very easy to follow language.

hen you scan a picture with a scanner what the scanner is doing is an analog-to-digital
conversion: it is taking the analog information provided by the picture (light) and converting
into digital.

hen you record your voice, you are using an analog-to-digital converter to convert
your voice, which is analog, into digital information.

igital information isn’t only restricted to computers. When you talk on the phone, for
example, your voice is converted into digital .since your voice is analog and the
communication between the phones switches is done digitally.

hen an audio CD is recorded at a studio, once again analog-to-digital is taking place,


converting sounds into digital numbers that will be stored on the disc.

evertheless, why digital? There are some basic reasons to use digital signals instead of
analog, noise being the number one.

IWIZ Learners Institute of Technical education Pvt Ltd 141


Embedded Primitive Level

9.2 WORKING PRINCIPLE

Analog to digital (A/D, ADC) converters are electrical circuit devices that convert
continuous signals, such as voltages or currents, from the analog domain to the digital domain
where the signals are represented by numbers. Most processing equipment today are digital in
nature, and they work with signals which are binary valued. In a digital or binary
representation, a signal is represented by a word, which is composed of a finite number of
bits. The processing of signals is preferably carried out in the digital domain because digital
processing is fast, accurate and reliable.

9.3 OPERATION

A successive approximation ADC works by using a digital to analog converter and a


comparator to perform a binary search to input voltage
A sample and hold circuit(S&H) is used to sample the analog input voltage and hold
the sampled value whilst the binary search is performed. The binary search starts with the
most significant bit(MSB) and works towards the least significant bit(LSB).For a 8-bit output
resolution,8 8 comparisons are needed in the binary search, taking a least 8 clock cycles.

The sample and hold circuit samples the analog input on a rising edge of the sample signal.
The comparator output is logic “1” if the sampled analog voltage is greater than the output of
the DAC,”0” otherwise. The circuit in this example has to control signals go and done. At
any point if go is 0”.Theircuit is reset. When go becomes a “1” the process of sampling and
converting takes place. When a conversion is finished valid is set to “1” and the result is
available

IWIZ Learners Institute of Technical education Pvt Ltd 142


Embedded Primitive Level

9.3.1 Sample/Hold Control Circuit

This circuit serves as an interface between the ADC’s input or the input analog signal
to be encoded and the rest of the ADC. The S/H (Sample/Hold) control circuit sustains a
certain point of an input analog signal for a certain amount of time (i.e. necessary for the rest
of the circuit to react on this value). The S/H circuit is typically a pair of voltage follower op-
amps in an open-loop or closed-loop configuration linked by a switch (CMOS or MOSFET,
etc) and a holding capacitor. It is regulated by its own specifications such as its acquisition
time, droop rate, sample-to-hold settling time, and slew rate, just to name a few.

9.3.2 Timing

The end of conversion is generally indicated by an end of convert (EOC), data –ready
(DRDY), or busy signal (actually, not busy indicates EOC).the polarities and name of the
signal maybe different for different SAR ADCs, but fund medal concepts is same. At the
beginning of the conversion interval , the signal goes high (or low) and remains in that states

IWIZ Learners Institute of Technical education Pvt Ltd 143


Embedded Primitive Level

until the conversion is completed, at which time it goes low(or high). The trailing edge is
generally an indication of valid output data.

9.3.3 Comparator

The comparator is essentially an operational amplifier or differential amplifier that


compares two signals. The first of these is the S/H (Sample/Hold) circuit output, or the
analog input after it has passed through the S/H control circuit. The second is the DAC
output, which is essentially the D/A conversion of the current digital output of the ADC (i.e.
a feedback loop of the current output). If the comparator output is too high, this means that
the current DAC output is too low. Vice versa, if the comparator output is too low, the
current DAC output is too high.

9.3.4 Successive Approximation Register (SAR)

The SAR has three inputs and two outputs. The first of these inputs is a clock signal
that will usually be an input pin to the ADC. This will determine the rate at which the ADC
encodes the input analog signal. The next input is a “start conversion” signal from the S/H
control circuit. This signal clears the SAR thus starting the encoding of a new signal. The
third input is the output from the comparator. If this output is high (the DAC output is too
low, as above), this tells the SAR to increase the digital number that it outputs. Vice versa, if
this output is too low (the DAC output is too high, as above), this tells the SAR to decrease
the digital number that it outputs. The two outputs are a digital output (whose number of bits
depend on the specs of the ADC) and an “end of conversion” (EOC) output that is ‘true’ or
‘false’ and indicates whether the current digital output data is “data valid”. This is an overall
output from the chip as well as an input to the output latch.
The sequence of successive approximation in the SAR occurs as follows:
§ T=0; clear all digital output bits, set EOC=’F’.
§ T=1; set the MSB to ‘1’. If this is too much, clear it; if too little, keep it.
§ T=2; set the next bit to ‘1’. If too much, clear it; if too little, keep it.
§ T=3 to N; continue as above until after LSB, then set EOC=’T’.

9.3.5 Digital to Analog Converter (DAC)

The DAC is part of the feedback loop inside the ADC. It converts the current digital
output (output from SAR) to an analog signal to be used as the second input to the
comparator (to be compared with the current analog input signal). A ladder configuration
DAC works as follows:

Based upon a certain input reference voltage, this type of DAC is essentially
achieving a set of binary weighted currents the come together into the summing junction of
an op-amp. For example, if the MSB is logic ‘1’, then a switch (CMOS, MOSFET, etc.) is
closed that allows a current “0.5*I” or “I/2” (i.e. half the maximum possible current; as the
MSB represents half of a total digital value) through to the summing junction. If the next
most significant bit is logic ‘1’, then a current “0.25*I” or “I/4” is allowed through to the
summing junction. Thus, for a 4-bit digital signal of ‘1001’, a current of I/2 + I/16 = 9/16*I
would appear at the input to the op-amp, added to an offset of I/16 equals 5/8*I or 5/8* Vref.
This makes sense as ‘1001’+’1’ is 5/8ths of ‘1111’+’1’ or the maximum total in this case.

IWIZ Learners Institute of Technical education Pvt Ltd 144


Embedded Primitive Level

9.3.6 Output Latch

The output latch simply serves as an interface between the digital output from the
SAR and the overall digital output of the ADC. If the EOC signal from the SAR is ‘true’,
then the SAR digital output is relayed through the output latch as the ADC’s main output.

After examining all the comprising parts, one can see how the ADC comes together.
An analog signal is imputed and compared with a D/A conversion of the current digital
output. As the starting digital output will be zeros, this will be gradually increased by the
SAR until the comparator tells the SAR that the input signal and analog conversion of the
output signal match. At this point, the next sample of the analog signal will enter into the
picture, the comparator will no longer detect a match, and the SAR will adjust the digital
output until it matches the changed value of the analog input. The process then continually
repeats itself.

9.4 ADC STRUCTURES

These are the most common ways of implementing an electronic ADC:

A direct conversion ADC or flash ADC has a comparator that fires for each decoded
voltage range. The comparator bank feeds a logic circuit that generates a code for each
voltage range. Direct conversion is very fast, but usually has only 8 bits of resolution (256
comparators) or fewer, as it needs a large, expensive circuit. ADCs of this type have a large
die size, a high input capacitance, and are prone to produce glitches on the output (by
outputting an out-of-sequence code). They are often used for video or other fast signals.

A successive-approximation ADC uses a comparator to reject ranges of voltages,


eventually settling on a final voltage range. The way successive approximation works is
through constantly comparing the input voltage to the output of an internal DAC (fed by the
current value of the approximation) until the best approximation is achieved. At each step in
this process, a binary value of the approximation is stored in a successive approximation
register (SAR). The SAR uses a reference voltage (which is the largest signal the ADC is to
convert) for comparisons. For example if the input voltage is 60V and the reference voltage is
100V, in the 1st clock cycle, 60V is compared to 50V (the reference, divided by two. This is
the voltage at the output of the internal DAC when the input is a '1' followed by zeros), and
the voltage from the comparator is positive (or '1') (because 60V is greater than 50V). At this
point the first binary digit (MSB) is set to a '1'. In the 2nd clock cycle the input voltage is
compared to 75V (being halfway between 100 and 50V: This is the output of the internal
DAC when its input is '11' followed by zeros) because 60V is less than 75V, the comparator
output is now negative (or '0'). The second binary digit is therefore set to a '0'. In the 3rd
clock cycle, the input voltage is compared with 62.5V (halfway between 50V and 75V: This
is the output of the internal DAC when its input is '101' followed by zeros). The output of the
comparator is negative or '0' (because 60V is less than 62.5V) so the third binary digit is set
to a 0. The fourth clock cycle similarly results in the fourth digit being a '1' (60V is greater
than 56.25V, the DAC output for '1001' followed by zeros). The result of this would be in the
binary form 1001. This is also called bit-weighting conversion, and is similar to a binary
search. The analogue value is rounded to the nearest binary value below, meaning this
converter type is mid-rise (see above). Because the approximations are successive (not
simultaneous), the conversion takes one clock-cycle for each bit of resolution desired. The
clock frequency must be equal to the sampling frequency multiplied by the number of bits of

IWIZ Learners Institute of Technical education Pvt Ltd 145


Embedded Primitive Level

resolution desired. For example, to sample audio at 44.1 kHz with 32 bit resolution, a clock
frequency of over 1.4 MHz would be required. ADCs of this type have good resolutions and
quite wide ranges. They are more complex than some other designs.

A delta-encoded ADC has an up-down counter that feeds a digital to analog converter
(DAC). The input signal and the DAC both go to a comparator. The comparator controls the
counter. The circuit uses negative feedback from the comparator to adjust the counter until
the DAC's output is close enough to the input signal. The number is read from the counter.
Delta converters have very wide ranges, and high resolution, but the conversion time is
dependent on the input signal level, though it will always have a guaranteed worst-case. Delta
converters are often very good choices to read real-world signals. Most signals from physical
systems do not change abruptly. Some converters combine the delta and successive
approximation approaches; this works especially well when high frequencies are known to be
small in magnitude.

A ramp-compare ADC (also called integrating, dual-slope or multi-slope ADC)


produces a saw-tooth signal that ramps up, then quickly falls to zero. When the ramp starts, a
timer starts counting. When the ramp voltage matches the input, a comparator fires, and the
timer's value is recorded. Timed ramp converters require the least number of transistors. The
ramp time is sensitive to temperature because the circuit generating the ramp is often just
some simple oscillator. There are two solutions: use a clocked counter driving a DAC and
then use the comparator to preserve the counter's value, or calibrate the timed ramp. A special
advantage of the ramp-compare system is that comparing a second signal just requires
another comparator, and another register to store the voltage value.
A pipeline ADC (also called sub ranging quantizes) uses two or more steps of sub ranging.
First, a coarse conversion is done. In a second step, the difference to the input signal is
determined with a digital to analog converter (DAC). This difference is then converted finer,
and the results are combined in a last step. This type of ADC is fast, has a high resolution and
only requires a small die size.

A Sigma-Delta ADC (also known as a Delta-Sigma ADC) over samples the desired
signal by a large factor and filters the desired signal band. Generally a smaller number of bits
than required are converted using a Flash ADC after the Filter. The resulting signal, along
with the error generated by the discrete levels of the Flash, is fed back and subtracted from
the input to the filter. This negative feedback has the effect of noise shaping the error due to
the Flash so that it does not appear in the desired signal frequencies. A digital filter
(decimation filter) follows the ADC, which reduces the sampling rate, filters off unwanted
noise signal and increases the resolution of the output. (Sigma-delta modulation, also called
delta-sigma modulation).

9.5 FACTORS TO BE CONSIDERED WHILE SELECTING AN ADC

Resolution

The resolution of the converter indicates the number of discrete values an ADC can
produce over the range of voltage values. It is usually expressed in bits. For example, an
ADC that encodes an analog input to one of 255 discrete values (0.255) has a resolution of
eight bits, since
28 − 1 = 255.

IWIZ Learners Institute of Technical education Pvt Ltd 146


Embedded Primitive Level

Resolution can also be defined electrically, and expressed in volts. The voltage resolution of
an ADC is equal to its overall voltage measurement range divided by the number of discrete
values as in the formula:

Where Q is resolution in volts, EFSR is the full scale voltage range, and M is resolution in
bits.

• Example 1

 Full scale measurement range = 0 to 10 volts


 ADC resolution is 12 bits: 212-1 = 4095 quantization levels
 ADC voltage resolution is: (10-0)/4095 = 0.00244 volts = 2.44 mV

• xample 2

 Full scale measurement range = -10 to +10 volts


 ADC resolution is 14 bits: 214 - 1 = 16383 quantization levels
 ADC voltage resolution is: (10-(-10))/16383 = 20/16383 = 0.00122 volts = 1.22 mV

In practice, the resolution of the converter is limited by the signal-to-noise ratio of the
signal in question. If there is too much noise present in the analog input, it will be impossible
to accurately resolve beyond a certain number of bits of resolution, the "effective number of
bits" (ENOB). While the ADC will produce a result, the result is not accurate, since its lower
bits are simply measuring noise. The signal-to-noise ratio should be around 6 dB per bit of
resolution required

9.6 DIFFERENT ADC ICS AVAILABLE

ADC207 – 7-bit flash A/D converter,20MHz sampling rate, Low power (250mW),Single
+5V Supply, 1.2 micron CMOS technology,7-bit latched 3-state output with overflow bit,
Surface-mount versions, High-reliability version, No missing codes.
ADC228 - 8-Bit flash A/D converter,20MHz sampling rate, Complete support circuitry, low
power1.5W, 7MHz full power bandwidth, and Sample-hold not required, Three-state outputs
MIL-STD-883 versions.

9.6.1 MAX112 :( SERIAL TYPE)

IWIZ Learners Institute of Technical education Pvt Ltd 147


Embedded Primitive Level

General Description

The max1112/max1113 are low power,8-bit,8-channel analog to digital converter that


features an internal track\hold, voltage reference, clock, and serial interface. They operate
from a single +4.5v to +5.5v supply
In addition, consume only 135ua while sampling at rates up to 50ksps. The max1112’s 8
analog inputs and the max113’s 4 analog inputs are software configurable.

Successive approximation conversions are performed using either the internal clock or
external serial interface clock. The max1112 is available in 20 pin sop and DIP packages. The
Max1113 is available in small 16 pin sop DIP packages

9.6.2 ADC0809 :( PARALLEL TYPE)


Pin detail (ADC0809)

General Description:

The ADC0808, ADC0809 data acquisition is a monolithic CMOS device with an 8 bit
analog to digital converter, 8 channels multiplexer and microprocessor compatible control
logic. The 8 bit A/D converter uses successive approximation as the conversion technique.
The converter features a high impedance chopper stabilized comparator a 256R voltage
divider with analog switch tree and a successive approximation register. The 8 channel
multiplexer can directly access any of 8 single ended analog signals.

The device eliminates the need for external zero and full scale adjustments. Easy
interfacing to microprocessor is provided by the latch and decoded multiplexer address inputs
and latched TTL TRI-STATE outputs.

1. Channel selection of ADC

#include<REGX51.H>
Sbit ch0=P3^2;
Sbit ch1=P3^3;
Sbit ch2=P3^4;
Void main()
{

IWIZ Learners Institute of Technical education Pvt Ltd 148


Embedded Primitive Level

While (1)
{
ch0=0; //selection of channel 0
ch1=0;
ch2=0;
ch0=1; //selection of channel 1
ch1=0;
ch2=0;

ch0=0; //selection of channel 2


ch1=2;
ch2=0;
}

9.7 APPLICATION

Digital cameras, cellular telephones, audio devices such as MP3 players, and video
equipment such as digital video disk (DVD) players, high definition digital television.

9.8 Technical question

 Use of resolution and its expressions in ADC


 How to Read the value from ADC using embedded c programming.
 Examine the value from ADC and display into LCD through Microcontroller.

Exercise
1. Write a program to interface ADC with controller using 2 channels
(ch0 and ch1).
2. Capturing the rapid variation to LCD display through controller from
analog device.
3. Analysis the analog equivalent digital value from temperature
Sensor.

9.9 DIGITAL TO ANALOG CONVERTER

Introduction

There is frequently a need to convert digital information into a voltage or current. As


noted in Data lines, bits, nibbles, bytes, words, binary and HEX, digital data changes in
steps. Turning on or off a bit increases or decreases a digital quantity.
A device for converting information in the form of combinations of discrete (usually binary)
states or a signal to information in the form of the value or magnitude of some characteristics
of a signal, in relation to a standard or reference. Most often, it is a device, which has
electrical inputs representing a parallel binary number, and an output in the form of voltage or
current.

Digital-to-analog (D/A) converters (sometimes called DACs) are used to present the
results of digital computation, storage, or transmission, typically for graphical display or for
the control of devices that operate with continuously varying quantities. D/A converter
circuits are also used in the design of analog-to-digital converters that employ feedback

IWIZ Learners Institute of Technical education Pvt Ltd 149


Embedded Primitive Level

techniques, such as successive approximation and counter-comparator types. In such


applications, the D/A converter may not necessarily appear as a separately identifiable entity.

The fundamental circuit of most D/A converters involves a voltage or current


reference; a resistive “ladder network” that derives weighted currents or voltages, usually as
discrete fractions of the reference; and a set of switches, operated by the digital input, that
determines which currents or voltages will be summed to constitute the output.

The output of the D/A converter is proportional to the product of the digital input
value and the reference. In many applications, the reference is fixed, and the output bears a
fixed proportion to the digital input. In other applications, the reference, as well as the digital
input, can vary; a D/A converter that is used in these applications is thus called a multiplying
D/A converter. It is principally used for imparting a digitally controlled scale factor, or
“gain,” to an analog input signal applied at the reference terminal. See also Amplifier; Analog
computer.

Except for the highest resolutions (beyond 18 bits), commercially available D/A
converters are generally manufactured in the form of integrated circuits, using bipolar, MOS,
and hybrid technologies. A single chip may include just the resistor network and switches; it
may also include a reference circuit, output amplifier, and one or more sets of registers (with
control logic suitable for direct microprocessor interfacing). See also Integrated circuits

9.10 Principle
Generate a current of magnitude proportional to the value of each bit in the
parallel digital word. Sum the currents of all the bits that are logic 1.

BLOCK DIAGRAM

Bias circuit
Bias circuit for power amplifier operated as a digital to analog converter.
An apparatus and method for biasing a power amplifier circuit operating as a Digital to
Analog Converter (DAC) are described. The bias circuit comprises a first transistor with a

IWIZ Learners Institute of Technical education Pvt Ltd 150


Embedded Primitive Level

reference voltage coupled to its base terminal, a second transistor coupled to the emitter
terminal of the first transistor at its collector terminal, and a third transistor with its base
terminal coupled to the first and second transistors, and to an input signal.

Switch circuit

A circuit for switching a shunt resistor of a resistive divider network in a digital-to-


analog converter to either of a low reference voltage and a high reference voltage,
comprising. The circuit of claim 1 wherein the resistance of the first reference resistor is
substantially different from the resistance.

9.11 DAC PERFORMANCE

DACs are at the beginning of the analog signal chain, which makes them very
important to system performance. The most important characteristics of these devices are:
Resolution: This is the number of possible output levels the DAC is designed to reproduce.
This is usually stated as the number of bits it uses, which is the base two logarithm of the
number of levels. For instance a 1 bit DAC is designed to reproduce 2 (21) levels while an 8
bit DAC is designed for 256 (28) levels. Resolution is related to the Effective Number of Bits
(ENOB), which is a measurement of the actual resolution attained by the DAC.
Maximum sampling frequency: This is a measurement of the maximum speed at which the
DACs circuitry can operate and still produce the correct output. As stated in the Shannon-
Nyquist sampling theorem, a signal must be sampled at over twice the bandwidth of the
desired signal. For instance, to reproduce signals in the entire audible spectrum, which
includes frequencies of up to 20 kHz, it is necessary to use DACs that operate at over 40 kHz.
The CD standard samples audio at 44.1 kHz, thus DACs of this frequency are often used. A
common frequency in cheap computer sound cards is 48 kHz - many work at only this
frequency, offering the use of other sample rates only through (often poor) internal
resampling.
Monotonic: This refers to the ability of DACs analog output to increase with an increase in
digital code or the converse. This characteristic is very important for DACs used as a low
frequency signal source or as a digitally programmable trim element.

9.12 DAC TYPES

The most common types of electronic DACs are

The Pulse Width Modulator, the simplest DAC type. A stable current or voltage is
switched into a low pass analog filter with a duration determined by the digital input code.
This technique is often used for electric motor speed control, and is now becoming common
in high-fidelity audio.

Over sampling DACs such as the Delta-Sigma DAC, use a pulse density conversion
technique. The over sampling technique allows for the use of a lower resolution DAC
internally. A simple 1-bit DAC is often chosen because the over sampled result is inherently
linear. The DAC is driven with a pulse density modulated signal, created with the use of a
low-pass filter, step nonlinearity (the actual 1-bit DAC), and negative feedback loop, in a
technique called delta-sigma modulation. This results in an effective high-pass filter acting on
the quantization (signal processing) noise, thus steering this noise out of the low frequencies
of interest into the high frequencies of little interest, which is called noise shaping (very high

IWIZ Learners Institute of Technical education Pvt Ltd 151


Embedded Primitive Level

frequencies because of the over sampling). The quantization noise at these high frequencies
are removed or greatly attenuated by use of an analog low-pass filter at the output (sometimes
a simple RC low-pass circuit is sufficient). Most very high resolution DACs (greater than 16
bits) is of this type due to its high linearity and low cost. Higher over sampling rates can
either relax the specifications of the output low-pass filter or enable further suppression of
quantization noise. Speeds of greater than 100 thousand samples per second (for example,
192kHz) and resolutions of 24 bits are attainable with Delta-Sigma DACs. A short
comparison with pulse width modulation shows that an 1-bit DAC with a simple first-order
integrator would have to run at 3 THz (which is physically unrealizable) to archive 24
meaningful bits of resolution, requiring a higher order low-pass filter in the noise-shaping
loop. A single integrator is a low pass filter with a frequency response inversely proportional
to frequency and using one such integrator in the noise-shaping loop is a first order delta-
sigma modulator. Multiple higher order topologies (such as MASH) are used to achieve
higher degrees of noise-shaping with a stable topology.

The Binary Weighted DAC, which contains one resistor or current source for each bit
of the DAC connected to a summing point. These precise voltages or currents sum to the
correct output value. This is one of the fastest conversion methods but suffers from poor
accuracy because of the high precision required for each individual voltage or current. Such
high-precision resistors and current-sources are expensive, so this type of converter is usually
limited to 8-bit resolution or less.

The R-2R Ladder DAC, which is a binary weighted DAC that uses a repeating
cascaded structure of resistor values R and 2R. This improves the precision due to the relative
ease of producing equal valued matched resistors (or current sources). However, a wide
converter performs slowly due to increasingly large RC-constants for each added R-2R link.
the Thermometer coded DAC,

Fig: analyzing of r-2r ladder

which contains an equal resistor or current source segment for each possible value of
DAC output? An 8-bit thermometer DAC would have 255 segments, and a 16-bit
thermometer DAC would have 65,535 segments. This is perhaps the fastest and highest

IWIZ Learners Institute of Technical education Pvt Ltd 152


Embedded Primitive Level

precision DAC architecture but at the expense of high cost. Conversion speeds of >1 billion
samples per second have been reached with this type of DAC.

The Segmented DAC, which combines the thermometer, coded principle for the
most significant bits and the binary weighted principle for the least significant bits. In this
way, a compromise is obtained between precision (by the use of the thermometer coded
principle) and number of resistors or current sources (by the use of the binary weighted
principle). The full binary weighted design means 0% segmentation; the full thermometer
coded design means 100% segmentation. Hybrid DACs, which use a combination of the
above techniques in a single converter. Most DAC integrated circuits are of this type due to
the difficulty of getting low cost, high speed and high precision in one device.

9.13 PIN DETAILS

General description

The DAC0808 is an 8 bit monolithic digital to analog converter featuring a full scale
output current setting time of 150ns while dissipating only 33mw with +5 v supplies. No
reference current trimming is required for most applications since the full scale output current
is typically +or- 1 LSB of 255 Iref/256. relative accuracies of better than + or - o.19% assure
8 bit monotonic and linearity while zero level output current of less than 4uA provides 8 bit
zero accuracy for I ref>=2 mA. The power supply current of the DAC0808 is independent of
bit codes.
Application:
Audio
CD players,
Digital music players,
PC sound cards.
Video
2.1 memory (RAM),
2.2 contrast and brightness.

IWIZ Learners Institute of Technical education Pvt Ltd 153


Embedded Primitive Level

9.14 Technical question

 Define resolution. What is the resolution of DAC that you have used in the lab?

Exercise

Write a program referred below circuit connection.

Connection of microcontroller to DAC0808

RD VCC
8051 WR Vref (+)
P1.0 D0 OUT -

P1.1 D1 +

P1.2 D2 Vref (-)

P1.3 D3

P1.4 D4

P1.5 D5

P1.6 D6

P1.7 D7

GND
VEE COMP

9.15. Keypad matrix

9.15.1 Introduction

Keypads are a part of HMI or Human Machine Interface and play really
important role in a small embedded system where human interaction or human input is
needed. Matrix keypads are well known for their simple architecture and ease of interfacing
with any microcontroller. In this part of tutorial we will learn how to interface a 4x4 matrix
keypad with AVR and 8051 microcontroller. In addition, we will see how to program then in
Assembly and C.

9.15.2 Constructing a Matrix Keypad

Construction of a keypad is really simple. As per the outline shown in the figure below we
have four rows and four columns. In between each overlapping row and column line there is
a key.

IWIZ Learners Institute of Technical education Pvt Ltd 154


Embedded Primitive Level

9.15.3scanning a matrix keypad

There are many methods depending on how you connect your keypad with your
controller, but the basic logic is same. We make the Coolum’s as I/p and we drive the rows
making them o/p, this whole procedure of reading the keyboard is called scanning.

In order to detect which key is pressed from the matrix, we make row lines low one
by one and read the columns. Let’s say we first make Row1 low, and then read the columns.

If any of the key in row1 is pressed will make the corresponding column as low i.e. if
second key is pressed in Row1, then column2 will give low. Therefore, we come to know that
key 2 of Row1 is pressed. This is how scanning is done.

Therefore, to scan the keypad completely, we need to make rows low one by one and
read the columns. If any of the buttons is pressed in a row, it will take the corresponding
column to a low state which tells us that a key is pressed in that row. If button 1 of a row is
pressed then Column 1 will become low, if button 2 then column2 and so on...

9.15.4 Application

(I).. Looking at the figure, you’ll notice a familiar 4x4 keypad with a single
difference —each row and column are separated by a resistor. If key #1 is pressed, the
resistance between nodes A and B (R1AB) is equal to 1.5*R; for key #2—R2AB = 1.5*R+R =
2.5*R; and so on ... key #N—RNAB = N.5*R. This variable resistor network is connected to a
555 timer (CMOS version), configured as an oscillator with the period of oscillation equal to
T = 1.4*RAB*C, directly proportional to RAB.

The oscillator runs only when a key is pressed, causing an interrupt request for the
microcontroller. The INT0 pin is set up as edge-sensitive. The general algorithm can be
described as: 1) after detecting the edge on the INT0 pin, wait 20 ms to eliminate ringing; 2)
detect the next edge and start the internal timer; 3) the following edge stops the internal timer.
The measured period (the time between two consecutive positive edges) will define the key
number. Any microcontroller with a built-in timer (the vast majority of microcontrollers) can
implement this idea.

For a specific example, I will use the 8051-family microcontroller with a 12-MHz
clock. In this situation, the single count of the timer will be 1 µs. If we choose 47 nF for the
capacitor and 3.9 kΩ as the resistor value, we will have T = 1.4*R*C = 256.6 ≈ 256 µs. That
is the period difference between oscillations produced by two serial keys. After calculating
the period interval produced by any key pressed, we need only to make integer division by
0xFF (25610) to get the key number of the depressed key. The value for R1 =1.5*R is chosen
to provide the highest error margin for the elements by moving the period value in the middle
of two consecutive numbers.

IWIZ Learners Institute of Technical education Pvt Ltd 155


Embedded Primitive Level

Some possible sources of errors in this application are: 1) component tolerances; 2)


256.6 µs instead of 256 for 1% resistors; 3) the closest value to 4*R, if R = 3.9k, will be
15.4K or 15.8K instead of the calculated 15.6k., an additional 1% error for each following
column; 4) the 555 oscillator inaccuracy—temperature drift of 75 ppm/C° and variation
0.03% for a power-supply variation of ±0.1 V.

9.15.5 Technical Question

1. If D3-D0-0111 is the data read from the columns, which column does the pressed key long
to?
2. To see if any key is pressed ,all rows grounded or not?
3. To identify the pressed key, one row at a time is grounded or not?
4. Key pressed detection and key identification require two different processes or not?

9.15.6Exercise
Write a c program to read a data from the 2x4 keypad and display it in LCD ?
(i)P2.0-P2.3 connected to rows.
(ii)P2.4-P2.7 connected to columns.
a)create password and check it with the keypad data.

IWIZ Learners Institute of Technical education Pvt Ltd 156


Embedded Primitive Level

9.15.7 Summary

In this chapter we learned

 How signals in the real world, which are analog, is converted to digital, using a ADC
circuit.
 Analog to digital (A/D, ADC) converters are electrical circuit devices that convert
continuous signals, such as voltages or currents, from the analog domain to the digital
domain where the signals are represented by numbers.
 ADC works by using a digital to analog converter and a comparator to perform a
binary search to input voltage
 The voltage resolution of an ADC is equal to its overall voltage measurement range
divided by the number of discrete values as in the formula:

After completing this chapter you can be able to read and examine a value from ADC, how
select the channels and get a data from a peripheral.
In addition, saw DAC, there is Generate a current of magnitude proportional to
the value of each bit in the parallel digital word. Also how to interface keypad with
microcontroller.

IWIZ Learners Institute of Technical education Pvt Ltd 157


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 158


Embedded Primitive Level

CHAPTER 10

COMMUNICATION

About this Chapter

 This chapter will give information about serial and parallel communication.
 You can learn about application of interfacing with PC and External
Peripherals.

After this Chapter

 You can able to know UART communication.


 You can able to send the data to PC and can get data from PC
 You can able to understand the hardware design and software design for
communication.

10.1 SERIAL 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 requiring turning on and off
one of the I/O lines in 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.

10.2 HARDWARE DESCRIPTION

The evaluation board consists of three major parts and provides a function to convert
the parallel data bus to RS232 serial port and vice versa. In addition, it provides an in-system
programming function. The functions of the three major parts are described as follows:

• • AT89C51 is an 8051 microcontroller. The microcontroller connection to the UART


is through the 8-bit parallel data bus and control signals - address, write, read, reset,
and chip select signals. The microcontroller acts as a host controlling the UART
device on the board with the embedded firmware.
• • Philips SC16Cxxx is a UART device interfacing between the microcontroller and
RS-232. The UART mainly consists of two sections: transmitter and receiver. The
transmitter performs parallel-to-serial conversion on data transmitted from the

IWIZ Learners Institute of Technical education Pvt Ltd 159


Embedded Primitive Level

microcontroller. The receiver performs serial-to-parallel conversion on data received


from a peripheral device.
• • Philips RS-232 drivers/receivers are the transceivers. The first one allows the
microcontroller to be in-system programmed through a PC’s serial port such as
COM1. The second one allows the UART to be in serial communication with a
peripheral device through another PC’s serial port such as COM2. The RS-232 mainly
consists of two sections: drivers (transmitters) and receivers. The drivers convert the
CMOS-logic output levels to RS-232 signals; whereas the receivers convert the RS-
232 signals to CMOS-logic output levels.

µC INTERFACE WITH PC

10.3 MAX 232 PIN DESCRIPTIONS

Capacitor Value Capacitor Value


No Name Purpose Signal Voltage
MAX232 MAX232A
+ connector for capacitor should
1 C1+ 1µF 100nF
capacitor C1 stand at least 16V
+10V, capacitor
output of voltage
2 V+ should stand at least 1µF to VCC 100nF to VCC
pump
16V
- connector for capacitor should
3 C1- 1µF 100nF
capacitor C1 stand at least 16V
4 C2+ + connector for capacitor should 1µF 100nF

IWIZ Learners Institute of Technical education Pvt Ltd 160


Embedded Primitive Level

capacitor C2 stand at least 16V


- connector for capacitor should
5 C2- 1µF 100nF
capacitor C2 stand at least 16V
-10V, capacitor
output of voltage
6 V- should stand at least 1µF to GND 100nF to GND
pump / inverter
16V
7 T2out Driver 2 output RS-232
8 R2in Receiver 2 input RS-232
9 R2out Receiver 2 output TTL
10 T2in Driver 2 input TTL
11 T1in Driver 1 input TTL
12 R1out Receiver 1 output TTL
13 R1in Receiver 1 input RS-232
14 T1out Driver 1 output RS-232
15 GND Ground 0V 1µF to VCC 100nF to VCC
16 VCC Power supply +5V

10.4 SETTING THE SERIAL PORT MODE

The first things 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, let’s present the "Serial Control" (SCON) SFR and define what each bit of the SFR
represents:

it Name Bit Address Explanation of Function


7 SM0 9Fh Serial port mode bit 0
6 SM1 9Eh Serial port mode bit 1.
5 SM2 9Dh Multiprocessor Communications Enable (explained later)
4 REN 9Ch Receiver Enable. This bit must be set in order to receive characters.
3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2 and 3.
2 RB8 9Ah Receive bit 8. The 9th bit received in mode 2 and 3.
1 TI 99h Transmit Flag. Set when a byte has been completely transmitted.
0 RI 98h Receive Flag. Set when a byte has been completely received.

Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:

IWIZ Learners Institute of Technical education Pvt Ltd 161


Embedded Primitive Level

SM0 SM1 Serial Mode Explanation Baud Rate


0 0 0 8-bit Shift Register Oscillator / 12
0 1 1 8-bit UART Set by Timer 1 (*)
1 0 2 9-bit UART Oscillator / 64 (*)
1 1 3 9-bit UART Set by Timer 1 (*)

(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.

The SCON SFR allows us to configure the Serial Port. Thus, well go through each bit
and review its function.

The first four bits (bits 4 through 7) are configuration bits.

Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive.
The four modes are defined in the chart immediately above. As you can see, selecting the
Serial Mode selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also
determines how the baud rate will be calculated. In modes 0 and 2 the baud rate is fixed
based on the oscillator’s frequency. In modes 1 and 3 the baud rate is variable based on how
often Timer 1 overflows. Well talk more about the various Serial Modes in a moment.

The next bit, SM2, is a flag for "Multiprocessor communication." Generally,


whenever a byte has been received the 8051 will set the "RI" (Receive Interrupt) flag. This
lets the program know that a byte has been received and that it needs to be processed.
However, when SM2 is set the "RI" flag will only be triggered if the 9th bit received was a
"1". That is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will
never be set. This can be useful in certain advanced serial applications. For now it is safe to
say that you will almost always want to clear this bit so that the flag is set upon reception of
any character.

The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want
to receive data via the serial port, set this bit. You will almost always want to set this bit.

The last four bits (bits 0 through 3) are operational bits. They are used when actually
sending and receiving data--they are not used to configure the serial port.

The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are
transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken
from TB8. If TB8 is set and a value is written to the serial port, the data bits will be written to
the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be "clear."

The RB8 also operates in modes 2 and 3 and functions essentially the same way as
TB8, but on the reception side. When a byte is received in modes 2 or 3, a total of nine bits
are received. In this case, the first eight bits received are the data of the serial byte received
and the value of the ninth bit received will be placed in RB8.

TI means "Transmit Interrupt." When a program writes a value to the serial port, a
certain amount of time will pass before the individual bits of the byte are "clocked out" the
serial port. If the program were to write another byte to the serial port before the first byte

IWIZ Learners Institute of Technical education Pvt Ltd 162


Embedded Primitive Level

was completely output, the data being sent would be garbled. Thus, the 8051 lets the program
know that it has "clocked out" the last byte by setting the TI bit. When the TI bit is set, the
program may assume that the serial port is "free" and ready to send the next byte.

Finally, the RI bit means "Receive Interrupt." It functions similarly to the "TI" bit, but
it indicates that a byte has been received. That is to say, whenever the 8051 has received a
complete byte it will trigger the RI bit to let the program know that it needs to read the value
quickly, before another byte is read.

10.5 WRITING TO THE SERIAL PORT

Once the Serial Port has been properly configured as explained above, the serial port
is ready to be used to send data and receive data. If you thought that configuring the serial
port was simple, using the serial port will be a breeze.

To write a byte to the serial port one must simply write the value to the SBUF (99h)
SFR. For example, if you wanted to send the letter "A" to the serial port, it could be
accomplished as easily as:

MOV SBUF,#A
Upon execution of the above instruction the 8051 will begin transmitting the character
via the serial port. Obviously transmission is not instantaneous--it takes a measurable amount
of time to transmit. And since the 8051 does not have a serial output buffer, we need to be
sure that a character is completely transmitted before we try to transmit the next character.

The 8051 lets us know when it is done transmitting a character by setting the TI bit in
SCON. When this bit is set we know that the last character has been transmitted and that we
may send the next character, if any. Consider the following code segment:

CLR TI; Be sure the bit is initially clear


MOV SBUF, #A; Send the letter A to the serial port
JNB TI,$ ;Pause until the TI bit is set.
The above three instructions will successfully transmit a character and wait for the TI
bit to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$,
in most assemblers, means "the same address of the current instruction." Thus the 8051 will
pause on the JNB instruction until the TI bit is set by the 8051 upon successful transmission
of the character.

Reading the Serial Port

Reading data received by the serial port is equally easy. To read a byte from the serial
port one just needs to read the value stored in the SBUF (99h) SFR after the 8051 has
automatically set the RI flag in SCON.

For example, if your program wants to wait for a character to be received and
subsequently read it into the Accumulator, the following code segment may be used:

JNB RI,$ ;Wait for the 8051 to set the RI flag


MOV A, SBUF; Read the character from the serial port

IWIZ Learners Institute of Technical education Pvt Ltd 163


Embedded Primitive Level

The first line of the above code segment waits for the 8051 to set the RI flag; again,
the 8051 sets the RI flag automatically when it receives a character via the serial port. So as
long as the bit is not set the program repeats the "JNB" instruction continuously.

10.6 COMMUNICATION BETWEEN MC AND PC:

Before going to implement we should know about SFR, which is used for serial
communication.

SCON (Serial Control, Addresses 98h, Bit-Addressable): 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.

Programming Tip: To use the 8051's on-board serial port, it is generally necessary to
initialize the following SFRs: SCON, TCON, and TMOD. This is because SCON controls the
serial port. However, in most cases the program will wish to use one of the timers to establish
the serial port's baud rate. In this case, it is necessary to configure timer 1 by initializing
TCON and TMOD.

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 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.

TCON (Timer Control, Addresses 88h, and 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 located
in the TCON SFR. These bits are used to configure the way in which the external interrupts
are activated and contain the external interrupt flags which are set when an external interrupt
has occurred.

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 auto reload 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.

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.

IWIZ Learners Institute of Technical education Pvt Ltd 164


Embedded Primitive Level

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

1. Write the program for sending string (“you can”) to PC using serial communication.
BR is 9600. Result should be displayed at hyper terminal

Implementation:

#include <REGX51.H>
#include<intrins.h>
void delay(unsigned int);
Void transmit data (char); // transmit the data
unsigned char transmit; // variable declaration to transmit
Void delay (unsigned int Valid) // delay routine
{
unsigned int i=0;
for(i=0;i<valid; i++)
{
_nop_();
}
}

/*####################MAINSTARTS#########################*/
void main()
{
P3=0xFF; // initialization
delay(100);
TMOD=0x20; //timer selection and mode selection for baud
rate generation
TH1=0xFD; // 9600 BR value
SCON=0x50; // serial communication enable
IE=0x80; // interrupt enable
TR1=1; // timer starts here
P0=0xFF; // pins initialization
P2=0xFF;
delay(500);
while(1)
{
delay(6000);
transmit data('Y');
transmit data('O');
transmit data('U');
transmit data(' ’);
transmit data('C');
transmit data('A');
transmit data('N');
delay(7000);

IWIZ Learners Institute of Technical education Pvt Ltd 165


Embedded Primitive Level

}
}
void transmit data(char x)
{
SBUF=x;
while(TI==0);
TI=0;
}
//*************************************************************************

Exercise:

1. Write programming for receiving data from PC , according to that control the relays….

10.7 PARALLEL COMMUNICATION

In computers, ports are used mainly for two reasons: Device control and
communication. We can program PC's Parallel ports for both. Parallel ports are mainly meant
for connecting the printer to the PC. But we can program this port for many more
applications beyond that.

Parallel ports are easy to program and faster compared to the serial ports. But main
disadvantage is it needs more number of transmission lines. Because of this reason parallel
ports are not used in long distance communications. Let us know the basic difference
between working of parallel port and serial port. In serial ports, there will be two data lines:
One transmission and one receive line. To send a data in serial port, it has to be sent one bit
after another with some extra bits like start bit, stop bit and parity bit to detect errors. But in
parallel port, all the 8 bits of a byte will be sent to the port at a time and a indication will be
sent in another line. There will be some data lines, some control and some handshaking lines
in parallel port. If three bytes of data 01000101 10011100 10110011 is to be sent to the port,
following figures will explain how they are sent to the serial and parallel ports respectively.
We can understand why parallel port communication is faster compared to that of serial.

25 pin D-SUB female connector

Female Male Dir


Shield Ground 1
Transmit Data 2 6
Receive Data 3 3
Request to Send 4 8
Clear to Send 5 1
Data Set Ready 6 2
Data Terminal Ready 20 7

IWIZ Learners Institute of Technical education Pvt Ltd 166


Embedded Primitive Level

10.8 PARALLEL PORT BASICS

In computers, ports are used mainly for two reasons: Device control and communication.
We can program PC's Parallel ports for both. Parallel ports are mainly meant for connecting
the printer to the PC. But we can program this port for many more applications beyond that

Parallel ports are easy to program and faster compared to the serial ports. But main
disadvantage is it needs more number of transmission lines. Because of this reason parallel
ports are not used in long distance communications. In parallel port, all the 8 bits of a byte
will be sent to the port at a time and a indication will be sent in another line. There will be
some data lines, some control and some handshaking lines in parallel port. If three bytes of
data 01000101 10011100 10110011 is to be sent to the port, following figures will explain
how they are sent to and parallel port. We can understand why parallel port communication is
faster compared to that of serial.

In the PC there will be D-25 type of female connector having 25 pins and in the
printer, there will be a 36-pin Centronics connector. Connecting cable will combine these
connecter using following convention. Pin structure of D-25 and Centronics connecters are
explained bellow.

Pin Details

Now let us know how communication between PC and printer takes place. Computer
places the data in the data pins, and then it makes the strobe low. When strobe goes low,
printer understands that there is a valid data in data pins. Other pins are used to send controls
to the printer and get status of the printer; you can understand them by the names assigned to
the pins.

To use the printer port for applications other than printing, we need to know how ports
are organized. There are three registers associated with LPT port: Data register, Control
register and Status register. Data register will hold the data of the data pins of the port. That
means, if we store a byte of data to the data register, that data will be sent to the data pins of
the port. Similarly control and status registers. The following table explains how these
registers are associated with ports.

IWIZ Learners Institute of Technical education Pvt Ltd 167


Embedded Primitive Level

10.9 INTERFACING WITH MICROCONTROLLER

Whenever we want to communicate with PC or other peripherals, we are using


parallel communication.
Using microcontroller, data pins (8), and ground is enough it’s made connection
between
Micro controller and PC.

Data pins- 2 to 9
Ground-18 to 25

Exercise

1. Write the program for sending string (‘First come, First Served) to PC using Parallel
communication. Result should be displayed on visual basic screen.

2. Write programming for receiving data from PC, according to that the 5 relays which is
connected to microcontroller.

Summary

 The serial interrupt TI,RI are the important for serial communication
 The SFR ‘s are very important for communication, especially TMOD,SCON,TCON.
 The crystal frequency is used to calculate the timer value which is used to determine
the baud rate.
 Visual basic and Hyper terminal is used to send the data through serial port

Technical questions

1. What is difference between baud rate and bit rate?


2. What is mean by logical level converter?
3. How to change the baud rate?
4. Who is going to control the serial interrupts?

IWIZ Learners Institute of Technical education Pvt Ltd 168


Embedded Primitive Level

CHAPTER 11

APPLICATION OF MOTORS

About this Chapter

 This chapter will give information about motor speed controlling methods.
 You can learn about application of stepper motor.

After this Chapter

 You can able to know robot design.


 You can able to design different driver circuits.

11.1 INTRODUCTION

The major application of motor is robotic control. Robot is an automatic device which
can be controlled by motors. The stepper motor is most suitable for robotic control. Because
the movement will be slow. If we want fast action the DC motor is suitable.

11.2 MOTORS USED TO ROBOTIC CONTROL

Motor is a device, which converts electrical energy into mechanical energy. The
important motor types are
1. DC motor
2. Stepper motor

11.2.1 Dc Motor
The operating voltage of DC motor is 12V DC. We can change the motor direction by
changing the supply input. Two relays are used to control the direction. The motor terminals
are connected from the COM terminal of the two relays. If relay1 is in ON condition (Relay2
is in OFF condition) then the motor will be in clockwise direction. If relay2 is in ON
condition (Relay1 is in ON condition) then the relay will be in anti-clockwise direction. We
see about relay function.

Relay

A relay is an electrically operated switch. Current flowing through the coil of the
relay creates a magnetic field, which attracts a lever and changes the switch contacts. The coil
current can be on or off so relays have two switch positions and they are double throw
(changeover) switches.

Relays allow one circuit to switch a second circuit which can be completely separate
from the first. For example a low voltage battery circuit can use a relay to switch a 230V AC

IWIZ Learners Institute of Technical education Pvt Ltd 169


Embedded Primitive Level

mains circuit. There is no electrical connection inside the relay between the two circuits; the
link is magnetic and mechanical.

The coil of a relay passes a relatively large current; typically 30mA for a 12V relay,
but it can be as much as 100mA for relays designed to operate from lower voltages. Most ICs
(chips) cannot provide this current and a transistor is usually used to amplify the small IC
current to the larger value required for the relay coil. The maximum output current for the
popular 555 timers IC is 200mA so these devices can supply relay coils directly without
amplification.

Relays are usually SPDT or DPDT but they can have many more sets of switch
contacts, for example relays with 4 sets of changeover contacts are readily available. For
further information about switch contacts and the terms used to describe them please see the
page on switches.

Most relays are designed for PCB mounting but you can solder wires directly to the
pins providing you take care to avoid melting the plastic case of the relay.

The supplier's catalogue should show you the relay's connections. The coil will be
obvious and it may be connected either way round. Relay coils produce brief high voltage
'spikes' when they are switched off and this can destroy transistors and ICs in the circuit. To
prevent damage you must connect a protection diode across the relay coil.

The animated picture shows a working relay with its coil and switch contacts. You
can see a lever on the left being attracted by magnetism when the coil is switched on. This
lever moves the switch contacts. There is one set of contacts (SPDT) in the foreground and
another behind them, making the relay DPDT.

Circuit symbol for a relay

IWIZ Learners Institute of Technical education Pvt Ltd 170


Embedded Primitive Level

Relays

Choosing a relay

You need to consider several features when choosing a relay:

1. Physical size and Pin Arrangement


If you are choosing a relay for an existing PCB you will need to ensure that its
dimensions and pin arrangement are suitable. You should find this information in the
supplier's catalogue.
2. Coil Voltage
The relay's coil voltage rating and resistance must suit the circuit powering the relay coil.
Many relays have a coil rated for a 12V supply but 5V and 24V relays are also readily
available. Some relays operate perfectly well with a supply voltage which is a little lower
than their rated value.
3. Coil Resistance
The circuit must be able to supply the current required by the relay coil. You can use
Ohm's law to calculate the current:
supply voltage
Relay coil current =
coil resistance
For example: A 12V supply relay with a coil resistance of 400 passes a current of
30mA. This is OK for a 555 timer IC (maximum output current 200mA), but it is too
much for most ICs and they will require a transistor to amplify the current.
4. Switch Ratings :( Voltage and Current)

IWIZ Learners Institute of Technical education Pvt Ltd 171


Embedded Primitive Level

The relay's switch contacts must be suitable for the circuit they are to control. You
will need to check the voltage and current ratings. Note that the voltage rating is usually
higher for AC, for example: "5A at 24V DC or 125V AC".
5. Switch Contact Arrangement :( SPDT, DPDT etc)
Most relays are SPDT or DPDT which are often described as "single pole
changeover" (SPCO) or "double pole changeover" (DPCO). For further information
please see the page on switches.
Advantages of relays:

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

Disadvantages of relay

• Relays are bulkier than transistors for switching small currents.


• Relays cannot switch rapidly (except reed relays), transistors can switch many times
per second.
• Relays use more power due to the current flowing through their coil.
• Relays require more current than many ICs can provide, so a low power transistor
may be needed to switch the current for the relay's coil.

Relay Controlling methods

There are two methods to controlling the relay. They are

1. Transistor switching circuit


2. Using ULN 2003

1. Transistor switching circuit

When a transistor is used as a switch it must be either OFF or fully ON. In the fully
ON state the voltage VCE across the transistor is almost zero and the transistor is said to be
saturated because it cannot pass any more collector current Ic. The output device switched
by the transistor is usually called the 'load'.

IWIZ Learners Institute of Technical education Pvt Ltd 172


Embedded Primitive Level

The power developed in a switching transistor is very small:

• In the OFF state: power = Ic × VCE, but Ic = 0, so the power is zero.


• In the full ON state: power = Ic × VCE, but VCE = 0 (almost), so the power is very
small.

This means that the transistor should not become hot in use and you do not need to
consider its maximum power rating. The important ratings in switching circuits are the
maximum collector current IC (max) and the minimum current gain hFE (min). The
transistor's voltage ratings may be ignored unless you are using a supply voltage of more than
about 15V.

Here relay coil act as a load. One end of the relay coil is connected with supply and
another one end is connected with transistor collector output. When the collector output is
high, the relay coil is not energized. Therefore the COM terminal is normally the COM
terminal will energize depending upon the collector output.

2. Using ULN 2003

The above figure shows the relay driver using ULN 2003. The input pins from 1 to 7
are connected with microcontroller. Output pins are connected with relay coil. If input is high
the output will be low. Therefore the relay is energized. If input pins are low the output will
be high.

METHOD TO CHANGE POLARITY

IWIZ Learners Institute of Technical education Pvt Ltd 173


Embedded Primitive Level

Hardware Description:

The total number of terminals in the relay is five. They are Coils, COM, NC, NO. The
NC and NO terminals should be inter-connected to each other. These inter connected
terminals are connected with power supply (+12V and GND). The one end of the relay coil is
connected with +12V and other end are connected with relay driver output. The two COM
terminals are connected with motor.

We can write small instruction for relay control. Assume two relays relay1 and relay2.

For move clockwise direction,

Relay1=1;

Relay=0;

Delay;

For move anti-clockwise direction,

Relay1=0;

Relay=1;

Delay;

11.2.2 STEPPER MOTOR

Definition
A motor that rotates in small, fixed increments and is used to control the movement of
the access arm on a disk drive.

History of stepper motor

Stepper motors were developed in the early 1960's as a low cost alternative to position
servo systems in the emerging computer peripheral industry. The main advantage of stepper
motors is that they can achieve accurate position control without the requirement for position
feedback. In other words, they can run "open-loop", which significantly reduces the cost of a
position control system.

Stepper motors utilize a doubly-salient topology, which means they have "teeth" on
both the rotor and stator. Torque is generated by alternately magnetizing the stator teeth
electrically, and the permanent magnet rotor teeth try to line up with the stator teeth. There
are many different configurations of stepper motors, and even more diverse ways to drive
them.

The most common stator configuration consists of two coils (A and B). These coils
are arranged around the circumference of the stator in such a way that if they are driven with
square waves which have a quadrate phase relationship between them, the motor will rotate.
To make the motor rotate in the opposite direction, simply reverse the phase relationship

IWIZ Learners Institute of Technical education Pvt Ltd 174


Embedded Primitive Level

between the A and B signals. A transition of either square wave causes the rotor to move by a
small amount, or a "STEP". Thus, the name "stepper motor".

The size of this step is dependent on the teeth arrangement of the motor, but a
common value is 1.8 degrees, or 200 steps per revolution. Speed control is achieved by
simply varying the frequency of the square waves.

Because stepper motors can be driven with square waves, they are easily controlled by
inexpensive digital circuitry and do not even require PWM. For this reason, stepper motors
have often been inappropriately referred to as "digital motors". However, by utilizing power
modulation techniques to change the quadrate square waves into sine and cosine waveforms,
even MORE step resolution is possible. This is called "micro-stepping", where each discrete
change in the sine and cosine levels constitutes one micro step.

Theoretically, there is no limit to the position resolution achievable with micro-


stepping, but in reality, it is limited by the motor mechanical and electrical tolerances. Some
stepper motors are designed specifically for micro-stepping, and consist of tightly matched
impedances between the A and B coils, and tighter machining tolerances on the teeth, at the
expense of higher cost.

Key characteristics

• Low cost solution for position control


• Inherent "zero-following" error in servo systems
• Easy to interface to digital controllers
• Inherently high torque/position gain resulting in excellent holding torque
• Heat is generated in the stator and is easy to remove
• Synchronous operation permits tight open-loop speed control.

Operation of stepper motor

The circuit diagram of stepper driver is shown in below. The current supplied from
microcontroller to stepper motor is not sufficient. Therefore we should improve the current.
The stepper driver circuit is used to improve the current from the microcontroller.

IWIZ Learners Institute of Technical education Pvt Ltd 175


Embedded Primitive Level

The sample coding for applying single pulse

P2=0x05;

delay(750);

P2=0x09;

delay(750);

P2=0x0a;

delay(750);

P2=0x06;

delay(750);

Applications:

• Cruise control
• Auto air vents
• Light leveling

IWIZ Learners Institute of Technical education Pvt Ltd 176


Embedded Primitive Level

• Printers
• Industrial machines
• Automotive gauges
• Office equipment
• Computer drives
• Medical scanners
• Scientific Instrumentation.

Summary:

 The stepper driver circuit is used to improve the current rating of the pulse.
 The DC motor can be controlled using two relays.
 The step angle is the angle when applying the single pulse from microcontroller.

Technical questions:

5. What is the use of driver circuit?


6. Describe the stepper driver circuit using transistors?
7. Draw the relay connection for controlling the DC motor?
8. What is step angle?
9. What is the use of free wheeling diode in stepper driver circuit?

Exercise:

1. Write a program for clockwise and anti-clockwise direction of stepper motor.

2. Write a program for clockwise and anti clockwise direction of different DC motors
Connected in mechanism.

IWIZ Learners Institute of Technical education Pvt Ltd 177


Embedded Primitive Level

CHAPTER 12

ENCODERS/DECODERS
About this Chapter

 This chapter will give information about encoders and decoders.


 You can learn about application of interfacing MC with encoders and decoders

After this Chapter

 You can able to know wireless communication.


 You can able to send the data to remote area from the microcontroller using
RF, and can able to receive the data from remote place.
 You can able to understand the hardware design and software design for
wireless transmission.

12 INTRODUCTIONS TO ENCODERS AND DECODERS

12.1 Encoder
An encoder is a device used to change a signal (such as a bit stream) or data into a
code. The code may serve any of a number of purposes such as compressing information for
transmission or storage, encrypting or adding redundancies to the input code, or translating
from one code to another. This is usually done by means of a programmed algorithm,
especially if any part is digital, while most analog encoding is done with analog circuitry.

12.1.1 Examples

• A compressor is used to encode data into a smaller form.


• A multiplexer combines multiple inputs into one output.
• A rotary encoder is a sensor, transducer for converting rotary motion or position to a
code of electronic pulses.
• A linear encoder is a sensor, transducer or read head paired with a scale that encodes
position.

12.2 DECODER

A decoder is a device which does the reverse of an encoder, undoing the encoding so
that the original information can be retrieved. The same method used to encode is usually just
reversed in order to decode.

In digital electronics this would mean that a decoder is a multiple-input, multiple-


output logic circuit that converts coded inputs into coded outputs, where the input and output
codes are different. e.g. n-to-2n, BCD decoders.

Enable inputs must be on for the decoder to function, otherwise its outputs assume a
single "disabled" output code word. Decoding is necessary in applications such as data
multiplexing, 7 segment display and memory address decoding.

IWIZ Learners Institute of Technical education Pvt Ltd 178


Embedded Primitive Level

12.3 REAL TIME IMPLEMENTATION

According to microcontroller, the data transmission between host (master) and


remote (slave) is implemented. The following diagram shows the interfacing encoder with
micro controller.

12.4 HT12E/ENCODER

Using this encoder can be sending the 4 bit data to the remote place; here the four pins
are connected to the microcontroller which can be used to send the data.

But the transmitter enable pin -14 is important, using this pin can control the entire
transmission, it should be active low pin i.e. Works when it is low.

VCC
HT12E 5V

IO1 IO10
IO2 IO11
IO3 IO12 RF-TX
IO4
IO5
IO13
IO14
R1 antenna
IO6 IO15 1.0MΩ
IO7 IO16
IO8 IO17 TX ENBLE
IO9 IO18

18 VCC
J1 5V

data in

HDR1X4
TO MICROCONTROLLER PORT

12.5 HT12D/DECODER

Using this decoder can decode the data from encoder; here the address should be same
at both encoder and decoder. Decoder receives the serial data from RF module, and then it
will be converted into parallel using decoder HT12D. Hence data can be used by
microcontroller according to application.

Here the address pins are important which is same at encoder.

IWIZ Learners Institute of Technical education Pvt Ltd 179


Embedded Primitive Level

12.6 INTERFACING DIAGRAM

J1
RF-RX
433MHZ
antenna

HT12D
HDR1X4
TO MICROCONTROLLER PORT
NC
IO1 IO10
IO2 IO11
IO3 IO12
IO4 IO13 DATA IN
IO5 IO14 R1 VCC
IO6 IO15
IO7 IO16 data in 5V
IO8 IO17 1.0MΩ
IO9 IO18

18 LED1
VCC
5V R2 1.0kΩ

12.7 IMPLEMENTATION

Write program for counting pulses from external, eye blink count from sensor and tell
the status of driver to remote using RF encoder and decoder.

12.7 EXERCISE

The following diagrams describe how to connect the 8 bit data encoder and decoder,
have to write the code for this application.

Interfacing 8 Bit Data Encoder/Decoder:


Connect the interfacing circuit to microcontroller, and read any one of the sensor
value from ADC
Send the value to remote controller using HT640 decoder.

12.8 ENCODER/HT640
TRANSMITTER

J2
A0
A1 RF-TX
A2
A3
A4
A5 VCC
data out to mc
A6 5V
J1
HT640 A8
IO1 IO13 A7
IO2 IO14
IO3 IO15 A9
IO4 IO16
IO5 IO17
IO6 IO18 HDR2X10 DATA OUT
IO7 IO19
IO8 IO20
IO9 IO21
IO10 IO22
R1 IO11
IO12
IO23
IO24

24 VCC
HDR1X8 5V VCC
1.0MΩ
TX ENBLE 5V

IWIZ Learners Institute of Technical education Pvt Ltd 180


Embedded Primitive Level

12.9 DECODER/HT648

Receive the value from encoder and display the value on LCDs which is connected to micro
controller.

RECEIVER RF-RX
433MHZ
J2 antenna
A0
A1
A2
A3 NC
A4
A5 VCC
data out to mc
A6 data in 5V
J1
HT648 A8
IO1 IO13 A7
IO2 IO14
IO3 IO15 A9
IO4 IO16
IO5 IO17
IO6 IO18 HDR2X10
IO7 IO19
IO8 IO20
IO9 IO21
IO10 IO22
R1 IO11
IO12
IO23
IO24

24 VCC DATA OUT


HDR1X8 5V
1.0MΩ
TX ENBLE

R2
1.0kΩ

LED1

Here write the code for the above application and test, and implement the Rf transmitter and
Rf receiver.

Summary

 The encoder is used to convert the parallel data into serial data, because we are using
FSK modulation for sending the data.
 The decoder is used to decode the data which is sent by transmitter,i.e the serial data
is converted into parallel.
 The transmitter enable pin is used to control the transmission .
 The receiver Vt pin is used to find out the reception of the data.

Technical questions

1. What is the distance between transmitter and receiver if the frequency is 433 MHz?
2. Which type of register used at encoder and decoder ic?
3. Is there possibility to send multi data at single channel using encoder and decoder?

IWIZ Learners Institute of Technical education Pvt Ltd 181


Embedded Primitive Level

CHAPTER13

I2C/TCP/IP/SPI
About this Chapter

 This chapter will give information about i2c, tcp/ip, spi protocols for
communication.
 You can learn about application of interfacing microcontroller with slave
devices.

After this Chapter

 You can able to know I2C, SPI, TCP/IP protocols communication.


 You can able to send the data to slave devices and can read data from slave
devices.
 You can able to understand the hardware design and software design for
protocols.
 You can able to learn real time applications like RTC, EEPROM.

CHARACTERISTICS OF THE I2C-BUS

The I2C-bus is for bidirectional, two-line communication between different ICs or


modules. The two lines are a serial data line (SDA) and a serial clock line (SCL). Both lines
must be connected to a positive supply via a pull-up resistor. Data transfer may be initiated
only when the bus is not busy.

BIT TRANSFER
One data bit is transferred during each clock pulse. The data on the SDA line must
remain stable during the HIGH period of the clock pulse as changes in the data line at this
time will be interpreted as a control signal.

START AND STOP CONDITIONS

Both data and clock lines remain HIGH when the bus is not busy. A HIGH-to-LOW
transition of the data line, while the clock is HIGH, is defined as the start condition (S). A

IWIZ Learners Institute of Technical education Pvt Ltd 182


Embedded Primitive Level

LOW-to-HIGH transition of the data line while the clock is HIGH is defined as the stop
condition (P).

SYSTEM CONFIGURATION
A device generating a message is a ‘transmitter’; a device receiving a message is the
‘receiver’. The device that controls the message is the ‘master’ and the devices which are
controlled by the master are the ‘slaves’.

Acknowledge

The number of data bytes transferred between the start and stop conditions from
transmitter to receiver is not limited. Each data byte of eight bits is followed by one
acknowledge bit. The acknowledge bit is a HIGH level put on the bus by the transmitter
whereas the master also generates an extra acknowledge related clock pulse. A slave receiver
which is addressed must generate an acknowledge after the reception of each byte. Also a
master must generate an acknowledge after the reception of each byte that has been clocked
out of the slave transmitter. The device that acknowledges has to pull down the SDA line
during the acknowledge clock pulse, so that the SDA line is stable LOW during the HIGH
period of the acknowledge related clock pulse. A master receiver must signal an end of data
to the transmitter by not generating an acknowledge on the last byte that has been clocked out
of the slave. In this event the transmitter must leave the data line HIGH to enable the master
to generate a stop condition.

IWIZ Learners Institute of Technical education Pvt Ltd 183


Embedded Primitive Level

I2C-bus protocol

After a start condition a valid hardware address has to be sent to a PCF8591 device.
The read/write bit defines the direction of the following single or multiple byte data transfer.
For the format and the timing of the start condition (S), the stop condition (P) and the
acknowledge bit (A) refer to the I2C-bus characteristics. In the write mode a data transfer is
terminated by sending either a stop condition or the start condition of the next data transfer.

EXAMPLE PROGRAMS
void ipdel (void)
{ // I2C delay
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
_nop_ ();
}
void ipchigh (void)
{ // I2C clock high
IPSCL = 1;
ipdel ();
}

IWIZ Learners Institute of Technical education Pvt Ltd 184


Embedded Primitive Level

void ipclow (void)


{ // I2C clock low
IPSCL = 0;
ipdel ();
}
void ipstart (void)
{ // start condition
IPSDA = 1;
IPSCL = 1;
IPSDA = 0;
ipdel ();
IPSCL = 0;
IPSDA = 1;
}
void ipstop (void)
{ // stop condition
IPSDA = 0;
IPSCL = 1;
ipdel ();
IPSDA = 1;
}
Bit irwrbyte (unsigned data)
{ // write one byte for ds1307
unsigned char i; // return 0 = ok
bit outbid; // return 1 = error
for (i=1;i<=8;i++) {
outbid = data & 0x80;
IPSDA = outbid;
data = data << 1;
ipchigh ();
ipclow ();
}
IPSDA = 1;
return (outbid);
}
void delay(unsigned int j)
{
unsigned int i;
for(i=0;i<j*100;i++);
for(i=0;i<j*100;i++);
}
unsigned char irrdbyte ()
{ // read last byte for ds1307 (not ack)
unsigned char i,dat;
bit in bit;
data = 0;
for (i=1;i<=8;i++) {
ipchigh ();
in bit = IPSDA;
data = data << 1;

IWIZ Learners Institute of Technical education Pvt Ltd 185


Embedded Primitive Level

data = data | in bit;


ipclow ();
}
IPSDA = 1;
ipchigh ();
ipclow ();
return (data);
}

Technical questions

1. What is the maximum distance of the I2C bus?


2. What bus speeds are available with I2C?
3. Why does the SCL line have to be bi-directional?
4. How can I test / debug the I2C bus?

SPI
The Serial Peripheral Interface Bus or SPI bus is a synchronous serial data link standard
named by Motorola that operates in full duplex mode. Devices communicate in master/slave
mode where the master device initiates the data frame. Multiple slave devices are allowed
with individual slave select (chip select) lines. Sometimes SPI is called a "four wire" serial
bus, contrasting with three, two, and one wire serial busses.

Operation

The SPI bus can operate with a single master device and with one or more slave devices.

If a single slave device is used, the SS pin may be fixed to logic low if the slave permits it.
Some slaves require the falling edge (high->low transition) of the slave select to initiate an
action such as the MAX1242 by Maxim, an ADC, which starts conversion on said transition.
With multiple slave devices, an independent SS signal is required from the master for each
slave device.

Most devices have tri-state outputs that become high impedance ("disconnected") when the
device is not selected. Devices without tristate outputs can't share SPI bus segments with
other devices; only one such slave may talk to the master, and only its chip select may be
activated.

Data Transmission

IWIZ Learners Institute of Technical education Pvt Ltd 186


Embedded Primitive Level

A typical hardware setup using two shift registers to form an inter-chip circular buffer
To begin a communication, the master first configures the clock, using a frequency less than
or equal to the maximum frequency the slave device supports. Such frequencies are
commonly in the range of 1-70 MHz.
The master then pulls the slave select low for the desired chip. If a waiting period is required
(such as for analog-to-digital conversion) then the master must wait for at least that period of
time before starting to issue clock cycles.

During each SPI clock cycle, a full duplex data transmission occurs:
• the master sends a bit on the MOSI line; the slave reads it from that same line
• the slave sends a bit on the MISO line; the master reads it from that same line
Not all transmissions require all four of these operations to be meaningful but they do
happen.

Transmissions normally involve two shift registers of some given word size, such as
eight bits, one in the master and one in the slave; they are connected in a ring. Data is usually
shifted out with the most significant bit first, while shifting a new least significant bit into the
same register. After that register has been shifted out, the master and slave have exchanged
register values. Then each device takes that value and does something with it, such as writing
it to memory. If there is more data to exchange, the shift registers are loaded with new data
and the process repeats.

Transmissions may involve any number of clock cycles. When there are no more data
to be transmitted, the master stops toggling its clock. Normally, it then deselects the slave.
Transmissions often consist of 8-bit words, and a master can initiate multiple such
transmissions if it wishes/needs. However, other word sizes are also common, such as 16-bit
words for touch screen controllers or audio codec’s, like the TSC2101 from Texas
Instruments; or 12-bit words for many digital-to-analog or analog-to-digital converters.
Every slave on the bus that hasn't been activated using its slave select line must disregard the
input clock and MOSI signals, and may not drive MISO. The master selects only one slave at
a time.

Clock polarity and phase

IWIZ Learners Institute of Technical education Pvt Ltd 187


Embedded Primitive Level

A timing diagram showing clock polarity and phas In addition to setting the clock
frequency, the master must also configure the clock polarity and phase with respect to the
data. Free scale’s SPI Block Guide [1] names these two options as CPOL and CPHA
respectively, and most vendors have adopted that convention.

The timing diagram is shown to the right. The timing is further described below and
applies to both the master and the slave device.
• At CPOL=0 the base value of the clock is zero
o For CPHA=0, data are read on the clock's rising edge (low->high transition)
and data are changed on a falling edge (high->low clock transition).
o For CPHA=1, data are read on the clock's falling edge and data are changed on
a rising edge.
• At CPOL=1 the base value of the clock is one (inversion of CPOL=0)
o For CPHA=0, data are read on clock's falling edge and data are changed on a
rising edge.
o For CPHA=1, data are read on clock's rising edge and data are changed on a
falling edge.
That is, CPHA=0 means sample on the leading (first) clock edge, while CPHA=1
means sample on the trailing (second) clock edge, regardless of whether that clock edge is
rising or falling. Note that with CPHA=0, the data must be stable for a half cycle before the
first clock cycle. Also, note that no matter what the CPOL and CPHA modes say, the initial
clock value must be stable before the chip select line goes active.
This adds more flexibility to the communication channel between the master and slave.

Mode Numbers

The combinations of polarity and phases are often referred to as modes which are
commonly numbered according to the following convention, with CPOL as the high order bit
and CPHA as the low order bit:

Mode CPOL CPHA


0 0 0
1 0 1
2 1 0
3 1 1
Independent slave SPI configuration

Typical SPI bus: master and three independent slaves

In the independent slave configuration, there is an independent slave select line for
each slave. This is the way SPI is normally used. Since the MISO pins of the slaves are
connected together, they are required to be tri-state pins.

IWIZ Learners Institute of Technical education Pvt Ltd 188


Embedded Primitive Level

Daisy chain SPI configuration

Daisy-chained SPI bus: master and cooperative slaves


Some products with SPI bus are designed to be capable of being connected in a daisy
chain configuration, the first slave output being connected to the second slave input, etc. The
SPI port of each slave is designed to send out during the second group of clock pulses an
exact copy of what it received during the first group of clock pulses. The whole chain acts as
an SPI communication shift register; daisy chaining is often done with shift registers to
provide a bank of inputs or outputs through SPI. Such a feature only requires a single SS line
from the master, rather than a separate SS line for each slave.
This somewhat resembles SGPIO, although SGPIO is limited to particular backplane
management activities and would not interoperate with most SPI chips.

Valid SPI communications

Some slave devices are designed to ignore any SPI communications in which the
number of clock pulses is greater than specified. Others don't care, ignoring extra inputs and
continuing to shift the same output bit. It is common for different devices to use SPI
communications with different lengths, as, for example, when SPI is used to access the scan
chain of a digital IC by issuing a command word of one size (perhaps 32 bits) and then
getting a response of a different size (perhaps 153 bits, one for each pin in that scan chain).

Interrupts

SPI devices sometimes use another signal line to send an interrupt signal to a host CPU.
Examples include pen-down interrupts from touch screen sensors, thermal limit alerts from
temperature sensors, alarms issued by real time clock chips, and headset jack insertions from
the sound codec in a cell phone.

Pros and cons of SPI

Advantages

• Full duplex communication


• Higher throughput than I²C or Bus
• Complete protocol flexibility for the bits transferred

IWIZ Learners Institute of Technical education Pvt Ltd 189


Embedded Primitive Level

o Not limited to 8-bit words


o Arbitrary choice of message size, content, and purpose
• Extremely simple hardware interfacing
o Typically lower power requirements than I²C or Bus due to less circuitry
(including pull-ups)
o No arbitration or associated failure modes
o Slaves use the master's clock, and don't need precision oscillators
o Transceivers are not needed
• Uses many fewer pins on IC packages, and wires in board layouts or connectors, than
parallel interfaces
• At most one "unique" bus signal per device (chip select); all others are shared

Disadvantages

• Requires more pins on IC packages than I²C, even in the "3-Wire" variant
• No in-band addressing; out-of-band chip select signals are required on shared busses
• No hardware flow control
• No slave acknowledgment (the master could be "talking" to nothing and not know it)
• Supports only one master device
• Without a formal standard, validating conformance is not possible
• Only handles short distances compared to RS-232, RS-485, or CAN-bus

Applications
The board real estate savings compared to a parallel I/O bus are significant, and have
earned SPI a solid role in embedded systems. That's true for most System-on-a-chip
processors, both with higher end 32-bit processors such as those using ARM and with lower
end microcontrollers such as the AVR, PIC and MSP430. These chips usually include SPI
controllers capable of running in either master or slave mode.

Chip or FPGA based designs sometimes use SPI to communicate between internal
components; on-chip real estate can be as costly as its on-board cousin.

The full-duplex capability makes SPI very simple and efficient for single
master/single slave applications. Some devices use the full-duplex mode to implement an
efficient, high-speed data stream for applications such as digital audio, digital signal
processing, or telecommunications channels, but most off-the-shelf chips stick to half-duplex
request/response protocols.

SPI is used to talk to a variety of peripherals, such as:

• Sensors: temperature, pressure, ADC, touch screens


• Control devices: audio codec, digital potentiometers, DAC
• Communications: Ethernet, USB, USART, CAN, IEEE 802.15.4
• Memory: flash and EEPROM
• Real-time clocks
• LCD displays, sometimes even for managing image data
• Any MMC or SD card

IWIZ Learners Institute of Technical education Pvt Ltd 190


Embedded Primitive Level

TCP/IP and LAN

TCP is a connection-oriented transport service; it provides end-to-end reliability, re


sequencing, and flow control. TCP enables two hosts to establish a connection and exchange
streams of data, which are treated in bytes. The delivery of data in the proper order is
guaranteed.

TCP can detect errors or lost data and can trigger retransmission until the data is
received, complete and without errors. TCP/IP (Transmission Control Protocol/Internet
Protocol) is a set of protocols independent of the physical medium used to transmit data. The
Rabbit Development Board module that is the RCM2200 uses an Ethernet interface to
communicate with other computers. The Ethernet can use either a bus or a star topology.
TCP/IP is the protocol suite upon which all Internet communications are based. Different
vendors have developed other networking protocols, but even most networking operating
systems with their own protocols, such as Netware support TCP/IP. It has become the de
facto standard.

Protocols are sometimes referred to as protocol stack or protocol suites. A protocol


stack is an appropriate term because it indicates the layered approach used to design the
networking software.

The TCP/IP protocol is divided into five layers such as the Application Layer, which
specifies a particular application uses a network. Transport layer specifies how to ensure
reliable transport of data. Internet Layer specifies packet format and routing Network layer
and specifies frame organization and transmittal. Physical Layer specifies the basic network
hardware.

Each host or router in the Internet must run a protocol stack. The software hides the
details of the underlying physical connections. The sending software at each layer
communicates with the corresponding layer at the receiving side through information stored
in header. The Web server uses this set of protocols to communicate between the Web server
and the Web browser.

A network is a system of hardware and software, put together for the purpose of
communication and resource sharing. A network includes transmission hardware, devices to
interconnect transmission media and to control transmissions, and software to decode and
format data, as well as to detect and correct problems.

TCP/IP Protocol Stack

TCP/IP is the protocol suite upon which all Internet communication is based.
Different vendors have developed other networking protocols, but even most network
operating systems with their own protocols, such as Netware, support TCP/IP. It has become
the de facto standard.

Protocols are sometimes referred to as protocol stacks or protocol suites. A protocol


stack is an appropriate term because it indicates the layered approach used to design the
networking software

IWIZ Learners Institute of Technical education Pvt Ltd 191


Embedded Primitive Level

Figure: Flow of data between two computers using TCP/IP stacks.

Each host or router in the Internet must run a protocol stack. The details of the
underlying physical connections are hidden by the software. The sending software at each
layer communicates with the corresponding layer at the receiving side through information
stored in headers. Each layer adds its header to the front of the message from the next higher
layer. The header is removed by the corresponding layer on the receiving side.

LAN [Local Area Network]

The most widely deployed type of network, LANs were designed as an alternative to the
more expensive point-to-point connection. A LAN has high throughput for relatively low
cost. LANs often rely on shared media, usually a cable, for connecting many computers.
This reduces cost. The computers take turns using the cable to send data.

TCP/IP [Transmission Control Protocol / Internet Protocol]

Physical Connections
The TCP/IP Development Board can be connected to your computer using a hub and
standard cable or directly to the computer using a cross-over cable. The Development Board
can also be a host connected directly to an Ethernet network.

Port Numbers
Port numbers are the mechanism for identifying particular client and server
applications. Servers select a port to wait for a connection. Most services have well-known
port numbers. For example, HTTP uses port 80. When a web browser (the client) requests a
web page it specifies port 80 when contacting the server. Clients usually have ephemeral port
numbers since they exist only as long as the session lasts.
Some of the common well-known TCP port numbers are listed in the table below.

Port Number Listening Application

IWIZ Learners Institute of Technical education Pvt Ltd 192


Embedded Primitive Level

7 Echo request
20/21 File Transfer Protocol (FTP)
23 Telnet
25 Simple Mail Transfer Protocol (SMTP)
53 Domain Name Server
80 HTTP Server

IP (INTERNET PROTOCOL)
IP provides communication between hosts on different kinds of networks. It is a
connectionless, unreliable packet delivery service. Connectionless means that there is no
handshaking, each packet is independent of any other packet. It is unreliable because there is
no guarantee that a packet gets delivered; higher-level protocols must deal with that.

IP Address

IP defines an addressing scheme that is independent of the underlying physical address.


IP specifies a unique 32-bit number for each host on a network. This number is known as the
Internet Protocol Address, the IP Address or the Internet Address. These terms are
interchangeable. Each packet sent across the Internet contains the IP address of the source of
the packet and the IP address of its destination.

For routing efficiency, the IP address is considered in two parts: the prefix, which
identifies the physical network, and the suffix, which identifies a computer on the network. A
unique prefix is needed for each network in an Internet. For the global Internet, network
numbers are obtained from Internet Service Providers (ISPs). ISPs coordinate with a central
organization called the Internet Assigned Number Authority.
IP (Internet Protocol) addresses are expressed as 4 decimal numbers separated by periods, for
example:
 216.103.126.155
 10.1.1.6
Each decimal number must be between 0 and 255. The total IP address is a 32-bit
number consisting of the 4 bytes expressed as shown above. A local network uses a group of
adjacent IP addresses. There are always 2N IP addresses in a local network. The net mask
(also called subnet mask) determines how many IP addresses belong to the local network.
The net mask is also a 32-bit address expressed in the same form as the IP address. An
example net mask is:
• 255.255.255.0
This net mask has 8 zero bits in the least significant portion, and this means that 28
addresses are a part of the local network.

IP Addresses Set Manually


Four pieces of information are needed by any host on a network:
1) The IP address of the host (e.g., the TCP/IP Development Board).
2) The part of the IP address that distinguishes machines on the host's network from
machines on other networks (the net mask).

IWIZ Learners Institute of Technical education Pvt Ltd 193


Embedded Primitive Level

3) The IP address of the router that connects the host's network to the rest of the world
(the default gateway).
4) The IP address of the local DNS server for the host's network. This is only necessary
if DNS backups are needed.

MY_IP_ADDRESS, MY_NETMASK, MY_GATEWAY and MY_NAMESERVER


respectively correspond to these four critical addresses.

IP Addresses Set Dynamically


The macro USE_DHCP enables the Dynamic Host Configuration Protocol (DHCP). If
this option is enabled, a DHCP client (e.g., TCP/IP Development Board) contacts a DHCP
server for the values of MY_IP_ADDRESS, MY_NETMASK, MY_GATEWAY and
MY_NAMESERVER.
DHCP servers are usually centrally located on a local network and operated by the network
administrator.

How IP Addresses are used


The actual hardware connection via an Ethernet uses Ethernet adapter addresses (also
called MAC addresses.) These are 48-bit addresses and are unique for every Ethernet adapter
manufactured. In order to send a packet to another computer, given the IP address of the other
computer, it is first determined if the packet needs to be sent directly to the other computer or
to the gateway.

In either case, there is an IP address on the local network to which the packet must be
sent. A table is maintained to allow the protocol driver to determine the MAC address
corresponding to a particular IP address. If the table is empty, the MAC address is determined
by sending an Ethernet broadcast packet to all devices on the local network asking the device
with the desired IP address to answer with its MAC address. In this way, the table entry can
be filled in. If no device answers, then the device is nonexistent or inoperative, and the packet
cannot be sent.

IP addresses are arbitrary and can be allocated as desired provided that they don't
conflict with other IP addresses. However, if they are to be used with the Internet, then they
must be numbers that are assigned to your connection by proper authorities, generally by
delegation via your service provider.

Dynamically Assigned Internet Addresses


In many instances, IP addresses are assigned temporarily. This normal procedure
when you use a dial-up Internet service provider (ISP). Your system will be provided with an
IP address that it can use to send and receive packets. This IP address will only be valid for
the duration of the call, and further may not actually be a real Internet IP address. Such an
address works for browsing the Web, but cannot be used for transactions originating
elsewhere since no other system has any way to know the Internet address except by first
receiving a packet from you.

In a typical corporate network that is isolated from the Internet by a firewall and/or
proxy server using address translation, the IP addresses are not usually actual Internet
addresses and may be assigned statically or dynamically. If they are assigned statically, you
only have to get an unused IP address and assign it to the RCM2200 board. If the IP

IWIZ Learners Institute of Technical education Pvt Ltd 194


Embedded Primitive Level

addresses are assigned dynamically, they you will have to get an IP address that is valid but
outside of the range of IP addresses that are assigned dynamically.

This will enable you to communicate from a PC on the network to the RCM2200
board. If you want to communicate to the RCM2200 board from the external Internet, then an
actual Internet IP address must be assigned to the RCM2200 board. It may be possible to
setup the firewall to pass a real IP address, or it may be necessary to connect the RCM2200
board in front of the firewall to accomplish this.

Net masks

Net masks are used to identify which part of the address is the Network ID and which
part is the Host ID. This is done by a logical bitwise-AND of the IP address and the net mask.
For class a networks the net mask is always 255.0.0.0; for class B networks it is 255.255.0.0
and for class C networks the net mask is 255.255.255.0.

Subnet Address

All hosts are required to support subnet addressing. While the IP address classes are the
convention, IP addresses are typically sub netted to smaller address sets that do not match the
class system. The suffix bits are divided into a subnet ID and a host ID. This makes sense for
class A and B networks, since no one attaches as many hosts to these networks as is allowed.
Whether to subnet and how many bits to use for the subnet ID is determined by the local
network administrator of each network.

If sub netting is used, then the net mask will have to reflect this fact. On a class B
network with sub netting, the net mask would not be 255.255.0.0. The bits of the Host ID that
were used for the subnet would need to be set in the net mask.

IP provides several other services:


 Fragmentation. IP packets may be divided into smaller packets. This permits a large
packet to travel across a network which only accepts smaller packets. IP fragments
and reassembles packets transparent to the higher layers.
 Timeouts. Each IP packet has a Time to Live (TTL) field that is decremented every
time a packet moves through a router. If TTL reaches zero, the packet is discarded.
 Options. IP allows a packet's sender to set requirements on the path the packet takes
through the network (source route); the route taken by a packet may be traced (record
route), and packets may be labeled with security features.

TCP Connection/Socket

A TCP connection is done with a 3-way handshake between a client and a server. The
following is a simplified explanation of this process.
 The client asks for a connection by sending a TCP segment with the SYN control bit
set.
 The server responds with its own SYN segment that includes identifying information
that was sent by the client in the initial SYN segment.
 The client acknowledges the server's SYN segment.
The connection is then established and is uniquely identified by a 4-tuple called a socket or

IWIZ Learners Institute of Technical education Pvt Ltd 195


Embedded Primitive Level

socket pair:
(Destination IP address, destination port number)
(Source IP address, source port number)
During the connection setup phase, these values are entered in a table and saved for the
duration of the connection.
Checksum - This 16-bit number is the one's complement of the one's complement sum of all
bytes in the TCP header, any data that is in the segment and part of the IP packet. A
checksum can only detect some errors, not all, and cannot correct any.

TCP/IP

Detailed Layers

Technical questions

1. If we r having OSI model they why nowadays we r using TCP/IP Model?


2. What is the difference between layer 2 and layer 3
3. What is flow and error control?
4. How many Layers in Network Layer
5. What is the concept of sub netting and why it’s used and where it is used?

IWIZ Learners Institute of Technical education Pvt Ltd 196


Embedded Primitive Level

IWIZ Learners Institute of Technical education Pvt Ltd 197


Embedded Primitive Level

CHAPTER 14

VISUAL BASIC USING PORT COMMUNICATIONS


About this Chapter

 This chapter will give information about serial and parallel communication.
 You can learn about application of interfacing with PC and External
Peripherals.

After this Chapter

 You can able to know UART communication.


 You can able to send the data to PC and can get data from PC
 You can able to understand the hardware design and software design for
communication.

14.1. VISUAL BASIC PROGRAMMING ACCESS I/O PORTS

We will use VB control "MSComm" that you should refer the control by Custom
control.

This programming guide assumes the user has a basic knowledge of Visual Basic
programming. The teaching method used is to show a basic example of a VB6.0 program
which communicates with an modem or PC to PC together by sending and receiving ASCII
data, and then direct the program to understand its operation.

• Total RS232 Control!


• Complete control over all RS232 line parameters.
• 16 different flow control settings built in.
• 32 modem handling properties and methods.
• Inter-character pace time calibration down to the millisecond on data transmissions.
• 20 selectable communications events.
• File transfers using ZMODEM, XMODEM, and YMODEM.
• CRC16 and CRC32 calculation methods.
• Supports VB4, VB5, VB6, C++, VB.NET, and C#.
• Wrapper class included for easy integration with Visual C++.
• Complete online documentation included.
• Working example programs included for all supported development environments.
• No Runtime Royalties.

PC's serial data acquisition interfaces require the sending and receiving of ASCII data
to operate. To communicate with the serial port using Visual Basic, the MsComm control
must be utilized to allow serial data transfer via a serial port (Com1-Com4). MSComm is a
custom control shipped with VB5.0 and VB6.0 and must be loaded using the Tools menu.

IWIZ Learners Institute of Technical education Pvt Ltd 198


Embedded Primitive Level

14.2. SELECT MENU PROJECT-->COMPONENTS

Follow to select in check box name is MSComm after it will display a telephone icon on
control box dialog that drag and drop it to your form of Project Please see thus picture below.

 Step one Select at top menu bar of Visual Basic thus as picture below

 Step two Select Control name is "Microsoft Comm. Control 6" thus picture below.

 Step three drag MS Comm. control from Toolbox to paste on Form thus as picture

IWIZ Learners Institute of Technical education Pvt Ltd 199


Embedded Primitive Level

Below.

14.3. SERIAL PORT INTERFACING METHODS

1. Interrupt communication.

Interrupt process is check device signal if the devices has already in sending code to
comm. port of computer. We are programming in COM Event and OnCommEvent that these
event will be active when coming signal from device.

2. Polling Communication

In PC system, the polling has some transferring between terminal and CPU in case
data is byte type that keyboard send coming.
The polling will be through checking signal from device such as keyboard polling as user
press button.

For CPU polling to check signal, we call “Wet Poll" that will be loss time 90%,We
can avoid the cycle time lose with using polling technique that call is "Round Robin" About
in VB programming ,we use Timer control for checking data from Serial port. MSComm
control has Event which use one only in Oncomm Event that communication is interrupt.For
programming in Serial Port communication normally using comm. event are comEvReceive,
comEvSend if it is communication in MODEM then using many one in check signal, please
refer help or MSDN.

14.4. MSCOMM ELEMENTS

Setting Communication of Serial Port

- Comport mean is Port interfacing RS-232 (Com1, Com2)


- Setting mean is Baud, Parity, Data (number of bits), Stop Ex. "1200, n, 8, 1 "
- Handshaking mean is we can define to 4 type.

IWIZ Learners Institute of Technical education Pvt Ltd 200


Embedded Primitive Level

1. ComNone
2. ComXonXoff

3. ComRTS

4. ComTRSXonXoff

Using Buffer For Receive And Sent Data

-In Buffer size mean is define buffer for receive data.


-Out Buffer size mean is defining buffer for send data.
- R threshold mean is define to occur in Event-driven for send data
- S threshold mean is define to occur in Event-driven for receive data
- Input Len mean is number of data to read in a buffer receive data
- EOF Enable mean is End-Of-File(EOF)

About Hardware

- Parity Replace mean is character value instead of occur Parity Error


- Null Discard mean is define in receive or not "NULL CHARACTER"
- RTSEnablemean is define signal RTS (Request To Send)
- DTSEnablemean is define signal DTR(Data Terminal Ready)

Define Mscomm Control Properties To Connect Port

1. Property Comport Select comm. port that we are using it thus as source code below
Example MSComm1.CommPort=1
in this using is Com1

2. Property Settings mean is setting value for receive /send data that will know baud rate of
device which connect ,how much thus as detail below
MSComm1.Settings="Baud(rate for receive/send data),Parity(N,Number of bits, bits Stop"
Example MSComm1.Settings="1200,N,8,1"

3. Property InputLenmean is define input buffer size when data incoming


Example MSComm1.InputLen=1

4. Property Port Open mean is open port to communicate Open =True, Close =False
Example MSComm1.PortOpen=True

5. Property Rthresholdmean is do activate occur with Event-driven when has data in receive
buffer (comm. port) that active the CommEvent in procedure OnComm Event
Example MSComm1.Rthreshold =1

We can use the MSComm properties allow the setting of communication parameters
including port selection and port enabling functions. Or we will be write to your code
from detail above, we will programming in VB procedure at Sub Form Load () or create new
Sub in case call in the future

Private Sub Form Load ()

IWIZ Learners Institute of Technical education Pvt Ltd 201


Embedded Primitive Level

MSComm1.Settings="1200, N, 8, 1"
MSComm1.CommPort=1
MSComm1.InputLen=1
MSComm1.PortOpen=True
MSComm1.Rthreshold =1
End Sub

14.5. HOW TO COMMUNICATE WITH SERIAL PORT

It defines the starting value of the communication port and open port to communicate with

RS-232 So, we can get data and send data with Property Output and Input
Output =send data to serial port
Input =receive data from port but this will being command to write at Event Property
OnComm that has in Sub MSComm_OnComm that read data from serial port or RS-232

Example:-

If we want print data to port while we are typing data to keyboard, we use event the Key
Press of Control Textbox

Sub txtRXTX_KeyPress (Key ASCII as Integer)


MSComm1.Output=Chr$(Key ASCII)
End Sub

For Property Input go to Event OnComm

Private Sub MSComm1_OnComm ()


Dim StrData as Variant 'define variable type as it is variant
Str=MSComm1.Input
Text1.Text=StrData
End Sub

I have get example program which is control step motor with command ASCII communicate
to Micro controller
A99 ' accelerate setting
V3 ' speed setting
D5000 ' step setting
H- 'direction setting
G ' go ,it is start motor command
We are assume use a button in my program thus as below

Private Sub Command1_Click()


MSComm1.Settings="1200,N,8,1"
MSComm1.CommPort=1
MSComm1.InputLen=1
MSComm1.PortOpen=True
MSComm1.Rthreshold =1
If MSComm1.PortOpen Then
MSComm1.Output ="A99 V3 D5000 H- G " ' character latest will be press space bar
1 time before put symbol "

IWIZ Learners Institute of Technical education Pvt Ltd 202


Embedded Primitive Level

End If
End Sub

Private Sub Form Load()


Dim strValue As String ' define Buffer value from Modem
MSComm1.CommPort = 1 ' select Com1
MSComm1.Settings = "9600,n,8,1" ' setting parameter in communicate with com port
MSComm1.InputLen = 0 'define size of Input buffer (coming with Modem)
MSComm1.PortOpen = True ' command open port
MSComm1.Output = "ATV1Q0" & Chr&(13) 'send AT command to Modem
Do
Do Events
strValue = strValue & MSComm1.Input ' get input data of Com Port
Loop Until InStr(strValue, "OK" & vbCrLf)
MSComm1.PortOpen = False 'Close port
End Sub

Some Important Tips

1. Port Enabling

- Port selection and enable functions can be programmed in the "load" and "unload"
subroutines in the "form" object or they may be controlled by radio buttons or pull down
menus.

2. Receiving Data

When receiving data from the serial port, be sure to wait for the correct number of
characters to be received in the serial buffer. Check your serial port programming manual for
the correct number of characters to be received and add one for the carriage return. The
command sends both a carriage return and line feed thus two must be added to the number of
characters expected.

3. Using Variables

- In many cases it may be desired to send a string incorporating a command and some
variable. For example, the "GO" command outputs to port A, the integer value position. If the
position is a variable 1500, a string to set the port to the value of this variable would look
like;

MSComm1.Output = “GO 1500" + Chr (13)


The Chr (13) is a carriage return.

You may be many question how to communicate with microcontroller, so, we can use
concept on above to apply in your project, process for communicate is like my example
programming but you will be know protocol of those device.

14.6. PROGRAMMING THE PARALLEL PORT IN VISUAL BASIC

If you have built any of the interfaces on my circuit’s page and now want to know
how to actually make use of them, this page is for you. This is a simple introduction to

IWIZ Learners Institute of Technical education Pvt Ltd 203


Embedded Primitive Level

programming the parallel port in Visual Basic. Note that most of the concepts in this page
apply to both 16 bit and 32 bit versions of VB. This document assumes that you are familiar
with the basic functions of Visual Basic itself.

Now before we go any further, we must figure out a way around some limitations
built into Visual Basic. VB cannot directly access the hardware on a system. All hardware
requests must go through Windows. Because of this, the closest we can get to manipulate the
parallel port is wit the Printer object. While this is all fine and good when you want to
actually print something, it is useless when we want direct hardware control. There may be
API calls to get round this, but as of yet I have been unable to find any. In order to control the
port directly, we must use something external to our program. It just so happens that there is a
great, free product that does exactly what we want. It is a DLL from a company called Soft
Circuits. You can download this DLL from their Programming Tools and Libraries page

Now that we have that finished with, let's get to the port. The parallel port is made up
of three different sections. These are the data lines, control lines and status lines. There are 8
data lines, and they are the primary means of getting information out of the port. In simple
projects, you will be concentrating mostly on the data lines. The control lines are another 4
outputs. They are meant to provide control signals to the printer (such as form feed or
initialize). The status lines are a standard parallel port's only inputs. There are 5 of them.
They were meant to allow the printer to communicate things such as error, paper out and
busy to the PC.

Each section is accessed by its own address and will act independently from the rest.
This is almost as if they were different ports. The addresses are as follows:

Port Address (Decimal) Address (Hex)


Data Lines 888 378h
Control Lines 890 37Ah
Status Lines 889 379h

You need to know the address of the port you want to use. You will also need two
other things; the command to access the port and the number you want to set it to. The
command will be explained in a little while. The ports work with numbers. These can be
expressed in hex, binary or decimal, but for this document all values will be expressed in
decimal. It's just easier that way. Anyway, you operate the port by sending it a number that
represents the binary pattern of the physical outputs on the port. For example, to set the 8 data
lines to 11111111, you would send 255. To set them to 00000000 you would send 0. Note
that these are all 8 bit binary numbers, and the port is also 8 outputs.

Small Description of Inpout32.dll

Here in this article, we are using a third party tool called inpout32.dll to connect to
ports available in your PC. We are using it because in Windows NT based versions, all the
low-level hardware access is prohibited and a separate I/O driver is needed. When we read
the status of the port, we have to take the support of that third party application.

In inpout32.dll, all of the system drivers and small tools needed to activate and run
that system driver are included. So, we don't have to consider much or think about how this

IWIZ Learners Institute of Technical education Pvt Ltd 204


Embedded Primitive Level

happens; it will do everything for us… As far as we are using a DLL file to communicate
with the hardware, we have to know the links that this particular file provides for the user, or
the entry points for that particular file. Here, I will describe all the entry points one by one.

DLL Entry used to read


Public Declare Function Inp Lib "inpout32.dll" Alias "Inp32" _
(By Val Port Addresses Integer) As Integer

DLL Entry used to output values


Public Declare Sub Out Lib "inpout32.dll" Alias "Out32" _
(By Val Port Address as Integer, By Val Value as Integer)

The Inp32 function can be used to read values from any address that is given through
its Port Address parameter. Also, the Out32 function is specifically used to write values to
data ports. A long description on both functions can be found below.

IWIZ Learners Institute of Technical education Pvt Ltd 205


Embedded Primitive Level

Parallel Port

Programming Tools for Port I/O and Interrupts

For Windows 95/98/NT/2000/Me/Xp

Inpout32.dll or Dllport.dll that is cover the sample source code ,The DLL compatible with
my Win9x inpout32.dll but works under all Windows editions from Win95/98/Me to
WinNT/2000/XP. For Windows NT etc., a kernel mode device driver is embedded in the
DLL in binary form. Get Port Address is a Visual Basic 6 application that retrieves parallel-
port addresses.

SAMPLE PROGRAM

Common General Code

Private Sub Command1_Click ()

Dim l As Integer

MSComm1.Output = Text1.Text

MsgBox "Data Sent"

End Sub

Private Sub Form Load ()

MSComm1.PortOpen = True

End Sub

Private Sub MSComm1_OnComm ()

Dim strBuff As String

IWIZ Learners Institute of Technical education Pvt Ltd 206


Embedded Primitive Level

Dim strTmp As String

Select Case MSComm1.CommEvent

Case comEvReceive

StrBuff = MSComm1.Input

Do

StrBuff = MSComm1.Input

StrTmp = MSComm1.Input

StrBuff = strBuff & strTmp

Loop until MSComm1.InBufferCount = 0

Text2.Text = strBuff

End Select

End Sub

Summary

 MSComm is very important to use the VB program.


 To communicate using serial and parallel port communication, we have to use the
MSComm Control and Element.
 Visual basic and Hyper terminal is used to send the data through serial port and
parallel port.

Technical questions

1. What is mean by port communication>

2. How many type of port communications in visual basic?

3. What is the difference between serial and parallel port?

4. How to interface port and pc?

IWIZ Learners Institute of Technical education Pvt Ltd 207


Embedded Primitive Level

CHAPTER 15

PIC MICROCONTROLLERS

15 INTRODUCTIONS TO PIC MICROCONTROLLERS

Microcontrollers are wonderfully useful devices. They incorporate all necessary parts
of a complete computer into a single IC that need almost no external parts to run.
Microcontrollers usually cost from $1-$20 depending on features and size.

15.1 Where are Microcontrollers Used?

Anything that is computerized but does not have a full-fledged PC inside most likely
uses a microcontroller. This includes things such as audio/video equipment, watches,
microwaves ovens, and more. A microcontroller is different from a microprocessor in that a
microprocessor usually requires a number of external parts such as RAM or ROM to operate.
A microprocessor such as a PC processor can't do anything by itself without a motherboard
and associated chips connected.

A microcontroller is sometimes referred to as an embedded processor because it can


be embedded into a device that has some function other than being a general purpose
computer. This generally implies that microcontrollers are less expensive and less powerful
than a full-fledged microprocessor, but don't be fooled! Because a microcontroller can be
dedicated to a specific task, it can actually do many things that a full PC is not very good at.
This is because a microcontroller and its program are very tightly integrated. Time-critical
applications are very well suited to a microcontroller. Often in PCs, timing-sensitive tasks are
performed by a microcontroller. A keyboard or mouse is a good example. If a PC spent all its
time scanning the keyboard and mouse, it would have trouble doing other tasks. Instead each
device contains a microcontroller that monitors user input. When something happens that the
computer needs to know about, it sends a message to the computer. The computer doesn't
care about the keyboard or mouse except when there is input. This also gives others
advantages such as reducing the number of wires needed to connect peripherals. The first PIC
ever designed, long before Microchip Inc. was around (General Instruments were the original
PIC developers) was made for the specific purpose of offloading work of I/O and other tasks
from the main CPU in a large computer.

15.2 BUILDING BLOCK OF A MICROCONTROLLER

In most microcontrollers all components are contained inside a single chip. Only a
few external parts are usually required to make the micro run. The major parts of a
microcontroller are:

• CPU - The CPU core. Many small micros use an 8-bit CPU, although 16 and 32 CPUs
also exist.
• Program Memory - Memory used to store the program to be run. Flash RAM is used
on modern micros.
• RAM - Temporary memory used during program execution. SRAM is usually used.
• EEPROM - Permanent storage to allow programs to save settings and other data when
the power is off.

IWIZ Learners Institute of Technical education Pvt Ltd 208


Embedded Primitive Level

• Oscillator - Support for different types of clock sources are usually available, including
crystals, resonators, external clock sources, and internal clocks. The clock affects the
speed of the program execution, timers and other parts. Speeds from 4-40MHz are
typical.
• I/O Ports - Pins for interfacing the micro to other devices. Most micros allow
individual control of each pin, making them very flexible.
• Peripherals - Many useful peripherals are common, such as:
o USARTs - Serial ports which can send and receive data at up to 1Mbps or
more.
o Comparators and A/D Converters - For sensing and measuring analog signals.
o Timers - For counting pulses and measuring accurate time intervals.
o Interrupts - A method of responding to external triggers or special conditions
of the other peripherals. (such as data being received on a USART)
o Pulse Width Modulators (PWM) - For controlling motors, lamps, LEDs and
other power control devices.

15.2.1 Getting Started With PIC Microcontrollers

Perhaps you've got a project in mind that you think would be good with a micro. Or maybe
you've heard about microcontrollers and don't know where to start. This page should help you
learn how to use microcontrollers in your own applications. We will focus on the PIC brand
of microcontrollers made by Microchip in this article.

Unlike other electronics projects, using a micro involves both software and hardware. You
can build a circuit with a PIC, but unless you put some software into it, the circuit will
probably be useless. But this is great for people that want to play with electronics but come
from the purely software side of things. Imagine coding for a device of your very own
design! It's also great because you can make simple circuits that do very sophisticated things.
I can't remember the last time I built a circuit that didn't have a micro in it. Modern circuits
can almost always benefit from being computerized.

Required Parts and Supplies

Playing with PIC microcontrollers can be a lot of fun, but you need to have a basic set of
parts, tools, and software before you begin. The following is a list of parts and supplies that
are recommended:

• PIC Microcontroller - The PIC16F627A is recommended as a good device for


beginners. Start with a DIP style package. Surface mounted (SMT) devices are only
useful in production prototypes, or when a DIP of your chosen part isn't available.
• PIC Datasheet - Make sure you download the PDF datasheet for the PIC that you are
using. You should at least read your first PIC datasheet cover to cover so that you
understand all the aspects of the micro. You'll find that other PICs (and indeed other
brands of micros) have many of the same features, and once you know one part, you
can easily master others.
• Prototyping Parts - A basic assortment of resistors, capacitors, LEDs, switches,
batteries, etc. will help you a lot. Also, some white plug-in prototyping board will
allow you to try out different circuits easily.

IWIZ Learners Institute of Technical education Pvt Ltd 209


Embedded Primitive Level

• Development Software / Compiler - You need some way of writing code and
compiling it. The Source boost IDE and compiler are highly recommended. A free
version supports all the features of the PIC16F627A.
• PIC Programmer Hardware / Software - You need some way of getting your compiled
program into the PIC. There are many free plans for PIC programmers on the web,
but the TechTools Quick Writer is worth every penny. I built and used many of the
free programmers on the web, and none of them were ever as good as the Quick
Writer. You need reliable tools for reliable results.

A Simple PIC Circuit

Once you've got all the bits and pieces you need, you're ready to get started. But you might be
wondering: How the heck do I get something happening? With a mix of hardware and
software, it's hard to know where to begin. You're probably eager to make something real, so
don't bother playing with simulators and the like. The most important thing is to make
something happen on a real circuit so that you can feel the excitement that comes from
powering up a micro and having it run your program at do something, even if it's just blinking
an LED.

15.3 MICROCHIP ADVATAGE

15.3.1 Low Risk product development


PIC microcontrollers achieve low-risk product developemtn by providing seamless
program size expansion. Pin compatibility facilitates drop in replacements of package types
as well as variations of reprogrammable (Flash) and one time programmable (OTP) program
memories without having to completely re-write code.

15.3.2 Faster time to market

It seamless migration path with standard pin schemes and code compatibility allows
engineers to reuse verified code and proven PCB layout. Adding higher memory options,
incremental I/O and analog peripherals can be accomplished without losing their software
investment, reducing time to market.

15.3.3 LOW TOTAL SYSTEM COST

An appropriate integration of both analog and digital peripherals, reading from simple
digital peripherals, ranging from simple digital to sophisticated analog modules. These
integrated peripherals minimize component count and thereby lower total system cost while
increasing reliability.

IWIZ Learners Institute of Technical education Pvt Ltd 210


Embedded Primitive Level

15.3.4 ADVANTAGES

 12, 14 and 16 bit wide instructions are upward compatible and tailored to maximize
processing efficiency and boost performance.
 Instructions and data are transferred on separate buses, avoiding processing
bottlenecks and increasing overall system performance.
 Two stage pipeling enables one instruction to be executed while the next instruction is
fetched.
 Single wide word instructions increase software code efficiency and reduce required
program memory.
 With only 33-79 instructions, programming and debugging tasks are easy to learn and
perform.
 Upward device compatibility allows designers to retain their capital investment in
code development.
 Data EPROM is an available option for those applications which require secure, non-
volatile memory for data that changes frequently.

IWIZ Learners Institute of Technical education Pvt Ltd 211

You might also like