Top Banner
SIX MONTHS INDUSTRIAL TRAINING REPORT submitted for partial fulfillment of award of BACHELOR OF ELECTRONICS & COMM. ENGINEERING 1
267

Embedded System

Aug 24, 2014

Download

Documents

RahulPoria

Embedded System using 8051 Traning Report
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Embedded System

SIX MONTHS INDUSTRIAL TRAINING

REPORT

submitted for partial fulfillment of award of

BACHELOR OF ELECTRONICS & COMM. ENGINEERING

Submitted by:

1

Page 2: Embedded System

CONTENTS

1) Acknowledgement

2) Company profile

3) PCB Designing

Functions of PCB

Classifications of PCBs

Technique used for PCB design

a) PCBs using Hand taping

Disadvantages of Hand taping

b) PCB design using CAD

Basic design steps in CAD system

A traditional design flow in cad system

PCB design software

4) OrCad design environment

PCB design steps in OrCad

a) Entry to schematic

b) Creating Netlist

Placement of Layout Plus

Setting board parameters

Creating board outline

Placement of components

Conductor routing

2

Page 3: Embedded System

Design rule check

Post processing

5) Power system design

Unregulated power supplies

Regulated power supplies

Bench supply diagram

Switch mode power supply

oBuck regulator

oBoost regulator

oBuck-Boost regulator

oFlyback regulator

5) Embedded System

What is Embedded System

Applications

Difference between microprocessor & micro controller

Types of microcontroller Architecture Difference between CISC & RISC History of 8051 8051 core architecture Pin description of 8051 Atmel’s AT89S52 microcontroller Feature of AT89S52 Pin description of AT89S52 Hardware interfacing & programming using AT89S52 Software used for Embedded system design using MCS-51 family Advantage of Embedded C over Assembly language programming Interfacing

LED3

Page 4: Embedded System

Switch Matrix Keyboard Relay Interfacing LCD ADC DAC Seven segment display DC motor Stepper Motor Parallel RTC Serial communication [b/w PC & microcontroller] Hardware interrupt programming Software interrupt programming I2C based serial RTC(DS1307) I2C based serial EEPROM

Why atmel’s AVR microcontrollers? Atmel’s ATmega8515

Features Pin details Input & output port registers

On chip pheripherals 8-bits timer /counter description 16-bits timer/counter description Analog comparator Software used for embedded system design using AVR

Hardware Interfacing & programming of atmega8515 (AVR) LED programming LCD interfacing ADC interfacing DAC interfacing PWM generation Analog Comparator Hardware Interrupts I2C based serial RTC(DS1307)

4

Page 5: Embedded System

PIC microcontrollers

PIC 16F73 features

Pin diagram of PIC16F73

Pin description of PIC16F73

Core Architecture

Programming of PIC

Compiler Used-mikroC

Features

Projects

Functionality

Programming and Interfacing

1) Advantages of C over Assembly language programming

2) Project no. 1- LED interfacing and its blinking(port programming)

3) Project no. 2- seven segment interfacing and display

4) Project no. 3- Interfacing and control of stepper motor with PIC

16F73

5) Project no. 4-LCD interfacing and display with PIC 16F73

6) Project no. 5-Builtin ADC of PIC16F73(Temperature Monitoring)

7) Project no. 6-To study switching action of PIC pins.

8) Project no. 7-Interfacing of keyboard matrix

9) Project no. 8-Serial communication [b/w PC & Microcontroller]

5

Page 6: Embedded System

ACKNOWLEDGEMENT

First of all I would like to thank almighty GOD who has given this wonderful gift of life to

us. He is the one who is guiding us in right direction to follow noble path of humanity. In

my six months industrial training it is a wonderful experience to be a part of NETMAX

TECHNOLOGIES . Where I have opportunity to work under brilliant minds. I owe my

deep regards for the supporting and kind staff authorities who are helping me in my lean

patches during these six months. The knowledge I am gaining throughout my studies have

the practical implementation during this period. I am grateful to all the staff of NETMAX

and for their timely support and sharing of their experience with me. I would like to

express my heartiest concern for Er.Rohit Khosla & Er.Harmesh lal for able guidance and

for inspiring attitude, praiseworthy attitude and honest support. Not to forget the pain

staking efforts of our college training and placement cell and specially my training and

placement officer Mr. NAVEEN GARG. Last but not the least I would express my utmost

regards for the electronics and communication department of our Institute.

6

Page 7: Embedded System

COMPANY PROFILE

Netmax Technologies is an organization which is established in the field of Network Support, Network training and Embedded systems. We provide Support and training in the field of networking solutions (CISCO, LINUX) and embedded systems (Micro controller based design, Electronics system design).

In Education we have strategic alliance with REDHAT Inc. We are also NOVELL EDUCATION PARTNER with which we provide NOVELL and SUSE LINUX courses. Netmax technologies also conduct courses in CADENCE based design tools.

Netmax Technologies also provide Technical Research & Development support and consultancy to some Electronics companies.

Our clients for R&D support in field of embedded systems.

1) Recorders and Medicare ltd Chandigarh.2) TELEBOX India ltd.3) Lotus Machines Pvt. Ltd. Chandigarh.4) Impearl Electronics Pvt. Ltd. Chandigarh.5) KANTA Electrical Ltd. Mohali.

The partial list of our clientele for network field is as below:

1) CEDTI, Mohali2) Premier ISP, Chandigarh3) Innovative Solutions, Chandigarh4) Emmtel ISP, Chandigarh5) NIPER, Mohali6) Navik Technologies, Chandigarh7) Software Technology Parks India, Mohali8) Glide Internet Services9) Rana Group10) IDS11) HFCL Infotel Ltd.

7

Page 8: Embedded System

12) Targus technologies pvt ltd13) STPI, Mohali14) BBMB15) The Tribune16) Quark17) Ind Swift

OUR TEAM

Presently we have a strong technical team of certified professionals for catering to these solutions and have presence in Chandigarh and Punjab. We have skilled team of engineers who are experienced in design, programming. We are having more than 10 engineers who are having prestigious certifications like ccna, ccnp, ccse, mcse and RHCE.

Support Area (network solutions)

a) LINUX / UNIX networksb) SUN networksc) CISCO devices (Routers, Switches, Firewalls, Cache Engine, RAS etc)d) Bandwidth Manager software and hardware e) Radio Linksf) Security Solutions

Design Services (Embedded systems)

a) AVR family b) MCS 51c) ELECTRONIC SYSTEM DESIGN

Network Training

a) CISCO CCNA, CCNPb) RED HAT LINUXc) SUN SOLARISd) WINDOWS 2000, 2003

8

Page 9: Embedded System

Our core strength is our commitment, technical expertise and cost effective solutions. We ensure high service levels and prompt support availability leading to lower downtime.

Netmax Technologies is a leader in education services and developer of innovative embedded solutions. To meet the demands of Post PC era Netmax provides complete solutions as well as design-to-order services to satisfy our customers.

For Netmax Technologies

Rohit khosla

9

Page 10: Embedded System

PCB DESINING

PCB stands for “PRINTED CIRCUIT BOARD”. Printed circuit board (PCB) provides

both the physical structure for mounting and holding the components as well as the

electrical interconnection between the components. That means a PCB = PWB (printed

wiring board) is the platform upon which electronic components such as integrated circuit

chips and other components are mounted. A PCB consists of a non-conducting substrate

(typically fiber glass with epoxy as resin) upon which the conductive pattern or circuitry is

formed. Copper is the most prevalent conductor although nickel, silver and tin are also

used in some cases.

Types of PCB

PCB may be of different types:-

1) Single-sided

2) Double-sided

3) Multilayer

Single sided PCBs: - As the name suggest in these designs the conductive pattern is only at

in one side. And also the size is large in these case but these are cheap.

Double sided PCBs: - These are the PCBs on which the conductive pattern is in on both

sides. The size of board is small in this case but it is costlier than that of above.

Multilayer PCBs: - In this case the board consists of alternating layers of conducting

pattern and insulating material. The conductive material is connected across the layers 10

Page 11: Embedded System

through plated through holes. The size of this PCB is smaller than that of double sided

PCB but it is very costly.

PCBs may also be either rigid, flexible, or the combination of two (rigid-flex). When the

electronic components have been mounted on the PCB, the combination of PCB and

components is an electronic assembly, also called PRINTED CIRCUIT ASSEMBLY. This

assembly is the basic building block for all the electronic appliances such as television,

computer and other goods.

FUNCTIONS OF PCB

Printed circuited boards are dielectric substrates with metallic circuitry formed on that.

They are some times referred to as the base line in electronic packaging. Electronic

packaging is fundamentally an inter connection technology and the PCB is the baseline

building block of this technology.

TECHNIQUE USED FOR PCB DESIGN

There mainly two techniques which are use for the PCB designs.

1. Hand Taping

2. Computer Aided Design

1) PCBs using Hand Taping:

o PCB design using hand taping is the process of technical drawing.11

Page 12: Embedded System

o In hand taping method layout should be prepared on grid paper.

o In hand taping, components pads can be prepared by using black pads.

o Routing of the board can be done by tapes with different widths.

Each layer (top, bottom) has to prepare separately.

DISADVANTAGS OF HAND-TAPING FOR PCB DESINING:

o Each layer has to be designed separately.

o We cannot generate NCD files for CNC drilling.

o Difficult to modify the design in the designing process or after designing.

o Difficult to get good design overview.

2) PCB DESIGNING USING CAD

All the above difficulties can be removed by using CAB system.

CAD system for PCB designing requires following:

o A computer system.

o PCB design software like OrCad, CADSTAR, Protel, TANGO, Mentor etc.

o A photo plotter for art work generation.

There are many enhanced features in electronics design automation tools which not

possible in the hand taping. The main advantages are given below:

o Auto placement

o Auto routing

o After routing, optimization of tracks can be done.

o Provides physical design reuse modules12

Page 13: Embedded System

o Electrical rule check (ERC)

o All the layers are generated from the same design by giving different

options.

o Bill of material can be generated which contains number of different

components used.

o We can draw conductors as an arc, semi-circular at different angles.

o Design Rule Check

o Advanced CAD systems have high speed analysis.

o CAD system provides all NCD files and Gerber data files for photo plotting.

BASIC DESIGN STEPS IN CAD- SYSTEM

The following design steps are very common while designing a PCD in CAD:

Entry the schematic diagram.

Net list file creation.

Placement of components manually or automatically.

Routing of the board using manual routing tools or auto router

Design rule check physical and electrical.

Artwork generation.

13

Page 14: Embedded System

A TRADITIONAL DESIGN FLOW IN CAD- SYSTEM

PCB Design Softwares

There many soft wares which are used for PCB designs. Some of them are given below:-

OrCad

CADSTAR

Capture

Libraries

Footprint libraries

Layout

Gerber tools

Gerber and drill files

Gerber and plotter drawing

14

Page 15: Embedded System

Protel

TANGO

Mentor

The most commonly software which are used for PCB design in India are Protel and

OrCad

OrCad Design Environment

OrCad has a long history of providing individuals and teams with a complete set of

technologies that offer unprecedented productivity, seamless tool integration, and

exceptional value. New 10.5 release continues that tradition.

Today's lower cost and yet highly sophisticated electronic design automation

systems have created a unique challenge to nearly every engineering department.

Therefore the use of EDA tools has become increasingly important as product

lifecycles have become shorter and shorter. Modern electronic design automation

(EDA) tools are beginning to support a more efficient and integrated approach to

electronic.OrCad Capture® design entry is the most widely used schematic entry

system in electronic design today for one simple reason: fast and universal design

entry. Whether you're designing a new analog circuit, revising schematic diagram

for an existing PCB, or designing a digital block diagram with an HDL module,

OrCad Capture provides simple schematic commands you need to enter, modify

and verify the design for PCB. OrCad Layout ® offers PCB designers and PCB

design teams the power and flexibility to create and share PCB data and

constraints across the design flow. OrCad Layout delivers all the capabilities to

designers need from netlist to place and route, to final output. The ease-of use and

15

Page 16: Embedded System

intuitive capabilities of OrCad Layout provides for quick startup and rapid learning

right out of the box.

PCB DESIGN STEPS IN OrCad 10.5

Entry of Schematic Diagram

Schematic diagram provides the functional flow and the graphical representation of an

electronic circuit. The entry of schematic diagram is the first step in PCB design using

OrCad.

A schematic diagram consists of:-

Electrical connections(nets)

Junctions

Integrated circuits symbols

Discrete components symbols like resistors, capacitors etc.

Input / output connectors

Power and ground symbols

Buses

No connection symbols

Components reference names

Text

The Schematic Page Editor:

16

Page 17: Embedded System

The schematic page editor is used to display and edit schematic pages. So that one can

parts; wires; buses and draw graphics. The schematic page editor has a tool palette that you

can use to draw and place everything you need to create a schematic page. One can print

from within the schematic page editor, or from the project window.

The Part editor:

The part editor is used to create and edit parts.

From the view menu of the part editor you can choose either part or package. In part view

one can:-

Create and edit parts and symbols, then store in new or existing libraries.

Create and edit power and ground symbols, off-page connector symbols, and title

block

Use the tool palette’s electrical tools to place pins on parts, and its drawing tools to

draw parts and symbols.

17

Page 18: Embedded System

The Session Log:

The session log lists the events that have occurred during the current Capture

session, includes message resulting from using capture’s tools. To display context-sensitive

help for an error message, put the cursor in the error message line in the session log press

F1.

The ruler along the top appears in either inches or mill meters, depending on which

measurement system is selected in the window panel. Your tab setting are saved and used

each time you start capture.

One can search for information in the session log using the find command on the Edit

menu. You can also save the contents of the of the session log to a file, which is useful

when working with Orcad’s technical support to solve technical problems. The default

filename is SESSION.TXT.

18

Page 19: Embedded System

The Toolbar:

Capture’s toolbar is dock able (that means you can select and drag the toolbar to new

location) as well as resizable, and displays tool tips for each tool; by choosing a tool button

you can quickly perform a task. If tool button is dimmed, you can’t perform that task in the

current situation.

Some of the tools operate only on what you have selected, while others give you a choice

of either operating on what is selected or expanding the scope to entire project.

You can hide the toolbar, then display it again when u need it. For hiding select from the

schematic page editor’s view menu, choose TOOLBAR.

The Tool Palette:

Capture has two tool palettes: one for the schematic page editor and one for the part editor.

Both tool palettes are dock able and resizable. They can also display tool tips that identify

each tool. The drawing tools on the two tool palettes are identical, however, each tool

palette has different electrical tools after you choose a tool, and you press the right mouse

button to display a context- sensitive pop-up menu.

The schematic page editor tool palette:19

Page 20: Embedded System

The first group of tools on the tool palette is electrical tools, used to place electrical

connectivity objects. The second group of tools is

Drawing tools, used to create graphical objects without electrical connectivity.

The part editor tool palette:

The first group of tools on the part palette is electrical tools, used to place pins and

symbols. They have been already explained above within the schematic page editor tools.

The second group of tools is drawing tools, used to create graphical objects without objects

any electrical connectivity and is described:

Pin Tools: Place pins on part

Pin Array: Place multiple pins on part

Selecting and deselecting of objects

Once one selects an object, one can perform operations on it, include moving, copying,

cutting, mirroring, rotating, resizing, or editing. One can also select multiple, objects and

edit them, or group them in to a single object. Grouping objects maintain relation ship

among them while one moves them to another location.

Creating Net list File20

Page 21: Embedded System

Net-list file is a document file which contains information about the logical

interconnections between signals and pins. Before one create a net list file, be sure one’s

project is completed, annotated and it is free from electrical rule violations.

A net list file consists of nets, components, connectors, junctions, no connection symbol,

power and ground symbols.

Creation of net list in capture:

Select your design in the project manager.

From the tools, choose create net list. The net list dialog box displays.

Choose a net list format tab.

If necessary, set the part value and PCB foot print combined property strings to

reflect the information you want in the net list.

Click ok to create the net list.

In the net list file text box, enter a name for the output file. If the selected format

creates an additional file, enter its file name in the second text box.

PLACEMENT OF LAYOUT PLUS

What is Layout Plus?

Layout plus is one part for the PCB design in which we place as well as route the

components an set unit of measurement, grids, and spacing in OrCad. Within other soft

wares you also have to place and route the components in similar way. For the placement

and routing of the components we normally use auto-placement and auto-routing.

21

Page 22: Embedded System

Unfortunately, in a lot of soft wares some critical signals have to be routed manually

before auto-routing. In layout plus we also define the layer stacks, pad stacks and via's.

Steps for board design:

At first, we have created a net list from our schematic diagram by using capture.

Layout plus includes design rules in order to guide logical placement and routing.

That means, load the net list into layout to create the board. At the same time you

have to specify the board parameters.

Specify board parameters: Specifying global setting for the board, including nits of

measurements, grid, and spacing

Place components: Use the components tool in order to place manually the

components which are fixed by the system designer on the board or otherwise use

auto-placement.

Route the board: Use different routing technologies to route the board and take

advantage of push and shove (a routing technology), which moves track you are

currently routing as well as you can also auto route the board.

Provide finishing of the board: Layout supplies an ordered progression of commands

on the auto menu for finishing your design. These commands include design rule

check, cleanup design, rename components, back annotate, run post processor, and

create reports.

The design window:

22

Page 23: Embedded System

The design window provides a graphical display of printed circuit board, it is primary

window you use when designing your board. It also provides tools to facilitate the

design process such as to update components and design rule violation.

Main window

Method to create a board with Layout Plus:

Ensure that net list with all footprints and necessary information has been created.

Create a directory in which the schematic design, net list, and boar will co-exit and

put the schematic design and net list. OrCad provides a directory for this purpose.

From the layout session frame’s file menu, choose New. The load template file in

the dialog box displayed.

23

Page 24: Embedded System

Design window

Select the technology template (.TCH), then choose the open button and load the net

list in other box.

Then apply the auto ECO.

If necessary, respond to link footprints to component dialog.

Draw the board outline by using the obstacle tool in the tool bar.

Setting board parameters:

There is some parameter which should be set before placing the components on board.

They are as follows:-

Set Datum

24

Page 25: Embedded System

Create a board outline

Set units of measurements

Set system grid

Add mount holes

Creating of board outline:

Board outline is the graphical representation of the size of the actual PCB board. So it is

the main step in layout, to draw the board outline of the actual size of PCB board.

Placement of components:

Placement of components means that to place the components in designed box. A designer

should follow the following steps before going for it:-

Optimize the board for component placement.

Load the placement strategy file.

Place components on the board.

Optimize placement using various placements

Components can be placed by using two techniques:-

1) Manual placement of components

2) Auto placement of components

Choose the components tool bar button. From the pop up men, choose the queue for

placement. The components selection criteria dialog box appears. Enter the reference

designator of the components that you want to place in the appropriate text box, and click

ok. Drag the components to desired location, place it there.

25

Page 26: Embedded System

Conductor Routing in Layout:-

After placing all the components the other main step is to route the board from the

electrical connections between the components. One may route board manually or

automatically by auto router.

100% auto routing can be achieved only when components are placed in the order of

functional flow of electronic circuit. The main routing tool available in OrCad is as flow:-

Add/edit route mode

Edit segment mode

Shove track mode

Auto path route mode

Design Rule Check:-

In manual designs every thing was checked as a possible source of error. Components

sizes, hole sizes, conductor widths and clearance, land-to-hole-ratio, board areas to be free

of components, clearance to the edges, positional accuracy and of course electrical

interconnections had tad to be personally reviewed with a great deal of care. After

completing the design of printed circuit board with the help of an EDA-Tool, a designer

has again to verify the PCB in order to find out errors. Such type of verifications/design

rule check contains beside the general verifications commonly two types:-

Physical verification

Electrical verification

Post processing:-

26

Page 27: Embedded System

Post processing can be done once the design is completed in all aspects. The common way

is still a process to generate GERBER data and NCD files which can be used for photo

plotting and for steps of CNC manufacturing and PCB- drilling.

POWER SYSTEM DESIGN

First part of electronics ckts. is power. The main power supply is in AC but mostly

electronic ckts. work with DC. So a system is required to convert ac to dc and these

sources should able to produce stable supplies.

Power supplies may be used in. may be of different types such as regulated, unregulated,

smps etc.

Unregulated power supplies

These are the power supplies in which the out put is not constant. That it is varies with

input voltage, load, and also effected by the environment conditions such as

temperature, etc. so these are the variable supplies. Commonly these supplies are not

employed as there efficiency is very less. The unregulated power can be obtained using

rectifying circuit after AC supply.

Regulated power supplies

These are the power supplies in which the output voltage is constant, i.e. the out put

voltage is independent of the input voltage, load and other external conditions. So to

obtain the regulated voltage using different regulators. The regulator voltage is mainly

the DC voltage, it may AC to or DC to DC voltage. A better approach to power supply

design is to use enough capacitance to reduce ripple to low level, then use an active

feedback circuit to eliminate the remaining ripple and dependence of output voltage on

input, load and environment conditions. These active devices are known as Regulators.

These regulators can be used to produce negative and positive voltage of required value.

The voltage regulators are of three types:-

10) Constant positive voltage regulators 27

Page 28: Embedded System

11) Constant negative voltage regulators

12) Variable voltage regulators

Constant positive voltage regulators:- These are the regulators which are able to

produce positive and constant voltage. Some of them are given below:-

S. no. Name of regulator Output voltage

1 LM 7805 5v

2 LM 7810 10v

3 LM 7812 12v

4 LM 7815 15v

These regulators are used according to the required voltage need.

Constant negative voltage regulators:- These are also the constant output voltage regulator

but there output is negative in polarity. These regulators are also employed according to

voltage requirements. Some of them are given below with there outputs:-

S. no Name of regulator Output voltage

1 LM7905 -5v

2 LM7910 -10v

3 LM7912 -12v

4 LM7915 -15v

Variable voltage regulators:- These are the regulator whose output voltage can be varied

according to the desired need. These regulators again of two types i.e.:-

Positive

Negative

28

Page 29: Embedded System

The output of these regulators can be varied by varying the resistance of the variable

resistance which is connected to the adjustable pin the regulators. So these are the most

commonly used regulators in the electronic industry as wide range of stable voltage can be

obtained from single chip by varying the resistance connected to the adjustable pin of the

regulators. The most commonly variable regulators are:-

LM317 (it is positive regulator)

LM 337(it is negative regulator)

There description is given below:-

LM317 3-Terminal Adjustable Regulator:-

General Description:

The LM317 series of adjustable 3-terminal positive voltage regulators is capable of

supplying in excess of 1.5A over a 1.2V to 37V output range. They are exceptionally easy

to use and require only two external resistors to set the output voltage. Further, both line

and load regulation is better than standard fixed regulators. Also, the LM117 is packaged

in standard transistor packages which are easily mounted and handled. In addition to higher

performance than fixed regulators, theLM317 series offers full overload protection

available only in IC’s. Included on the chip are current limit, thermal overload protection

and safe area protection. All overload protection circuitry remains fully functional even if

the adjustment terminal is disconnected. Normally, no capacitors are needed unless the

device is situated more than 6 inches from the input filter capacitors in which case an input

bypass is needed. An optional output capacitor can be added to improve transient response.

29

Page 30: Embedded System

The adjustment terminal can be bypassed to achieve very high ripple rejection ratios which

are difficult to achieve with standard voltage, supplies of several hundred volts can be

regulated as long as the maximum input to output differential is not exceeded, i.e., avoid

short-circuiting the output.

Also, it makes an especially simple adjustable switching regulator, a programmable output

regulator, or by connecting a fixed resistor between the adjustment pin and output,

theLM317 can be used as a precision current regulator. Supplies with electronic shutdown

can be achieved by clamping the adjustment terminal to ground which programs the output

to 1.2V where most loads draw little current.

Typical application:

U 1L M 3 1 7 / C Y L

V I N3

AD

J1

V O U T2

R 12 2 0 E

C 1. 1 u F

C 2. 1 u F

R 25 k

VOUTVIN

Features30

Page 31: Embedded System

1. Guaranteed 1% output voltage tolerance (LM317A)

2. Guaranteed max. 0.01%/V line regulation (LM317A)

3. Guaranteed max. 0.3% load regulation (LM317)

4. Guaranteed 1.5A output current

5. Adjustable output down to 1.2V

6. Current limit constant with temperature

7. P+ Product Enhancement tested

8. 80 dB ripple rejection

9. Output is short-circuit protected

Packages of LM317

I

31

Page 32: Embedded System

Application Hints:

In operation, the LM317 develops a nominal 1.25V reference voltage, VREF, between the

output and adjustment terminal. The reference voltage is impressed across program resistor

R1 and, since the voltage is constant, constant current I1 then flows through the output set

resistor R2, giving an output voltage of

Since the 100μA current from the

adjustment terminal represents an error

term, the LM317 was designed to

minimize IADJ and make it very

constant with line and load changes.

To do this, all quiescent operating

current is returned to the output

establishing a minimum load current

requirement. If there is insufficient

load on the output, the output will rise.

PROTECTION DIODES:-

When external capacitors are used with any IC regulator it is sometimes necessary to add

protection diodes to prevent the capacitors from discharging through low current points

into the regulator. Most 10μF capacitors have low enough internal series resistance to

deliver 20A spikes when shorted. Although the surge is short, there is enough energy to 32

Page 33: Embedded System

damage parts of the IC. When an output capacitor is connected to a regulator and the input

is shorted, the output capacitor will discharge into the output of the regulator. The

discharge current depends on the value of the capacitor, the output voltage of the regulator,

and the rate of decrease of VIN. In the LM317, this discharge path is through a large

junction that is able to sustain 15A surge with no problem. This is not true of other types of

positive regulators. For output capacitors of 25μF or less, there is no need to use diodes.

The bypass capacitor on the adjustment terminal can discharge through a low current

junction. Discharge occurs when either the input or output is shorted. Internal to the

LM317 is a 50resistor which limits the peak discharge current. No protection is needed

for output voltages of 25V or less and 10μF capacitance. Figure 3 shows an LM317 with

33

Page 34: Embedded System

protection diodes included for use with outputs greater than 25V and high values of output

capacitance.

LM337 3-Terminal Adjustable Regulator:-

General Description:

The LM337 is adjustable 3-terminal negative voltage regulators capable of supplying in

excess of −1.5A over an output voltage range of −1.2V to −37V. These regulators are

exceptionally easy to apply, requiring only 2 external resistors to set the output voltage and

1 output capacitor for frequency compensation. The circuit design has been optimized for

excellent regulation and low thermal transients. Further, the LM337 series features internal

current limiting, thermal shutdown and safe-area compensation, making them virtually

blowout-proof against overloads. The LM337 serves a wide variety of applications

including local on-card regulation, programmable-output voltage regulation or precision

current regulation. The LM337 are ideal complements to the LM317 adjustable positive

regulators.

Pin diagram

34

Page 35: Embedded System

Features:

1) Output voltage adjustable from −1.2V to −37V

2) 1.5A output current guaranteed, −55°C to +150°C

3) Line regulation typically 0.01%/V

4) Load regulation typically 0.3%

5) Excellent thermal regulation, 0.002%/W

6) 77 dB ripple rejection

7) Excellent rejection of thermal transients

35

Page 36: Embedded System

8) Temperature-independent current limit

9) Internal thermal overload protection

10) Standard 3-lead transistor package

11) Output is short circuit protected

These two Ic's i.e. LM337and LM317are mainly used in the regulated power supplies

because using these regulator a wide range of output can be obtain which can be varied

from 0v to 30v, which is much sufficient to drive any electronic circuit.

On next page there is diagram of the bench supply which is generally used to test the

instrument in the labs. This circuit is capable of producing positive and negative output

voltage.

36

Page 37: Embedded System

Bench supply diagram

L 2

I N D U C TO R A U D I O _ 0

1234

56

U 6

L M 3 3 7 / TO 2 2 0

ADJ

1

V I N2

V O U T3

J 7

C O N 3

123-V S

D 41 N 4 0 0 7

12

D 3

1N40

0712

C 8

2 2 0 0 u F 5 0 V

C 1 42 2 0 0 u F 5 0 V

J 8

C O N 3

123

C12

10uF

25V

TAN

T

D 51 N 4 0 0 7

1 2

C 1 5

470u

F 5

0V

C 1 1

1 0 4

D 21 N 4 0 0 7

12

R 8

R

C 1 71 0 4

R 1 7

R

C 9

470u

F 5

0V

U 5L M 3 1 7 / TO 2 2 0

V I N3

ADJ

1

V O U T2

C13

10uF

25V

TAN

T

-V S

R16

1K 1

W

R12

1K 1

W

C 1 0

C A P

- +

B R 1B R I D G E

2

1

4

3

C 1 6C A P

R 1 0P O TR 9

R

R 1 1

R

R 1 4P O TR 1 3

R

R 1 5

R

L 1

I N D U C TO R A U D I O _ 0

123 4

56

V S

37

Page 38: Embedded System

SWITCH MODE POWER SUPPLY

The switch mode regulated power supply is increasing in popularity because it offers the

advantages of higher power conversion efficiency and increased design flexibility

(multiple output voltages of different polarities can be generated from a single input

voltage). This paper will detail the operating principles of the four most commonly used

switching converter types:

Buck: used to reduce a DC voltage to a lower DC voltage.

Boost: provides an output voltage that is higher than the input.

Buck-Boost (invert): an output voltage is generated opposite in polarity to the input.

Flyback: an output voltage that is less than or greater than the input can be generated, as

well as multiple outputs.

Switching Fundamentals:

Before beginning explanations of converter theory, some basic elements of power

conversion will be presented:

38

Page 39: Embedded System

TRANSFORMER OPERATION:

A transformer is a device that has two or more magnetically-coupled windings. The action

of a transformer is such that a time-varying (AC) voltage or current is transformed to a

higher or lower value, as set by the transformer turns ratio The basic operation is shown in

Figure:-

.

The transformer does not add power, so it follows that the power (V X I) on either side

must be constant. That is the reason that the winding with more turns has higher voltage

but lower current, while the winding with less turns has lower voltage but higher current.

The dot on a transformer winding identifies its polarity with respect to another winding,

and reversing the dot results in inverting the polarity.

Example of Transformer Operation:

39

Page 40: Embedded System

An excellent example of how a transformer works can be found under the hood of your car,

where a transformer is used to generate the 40 kV that fires your cars spark plugs as in fig.

The "coil" used to generate the spark voltage is actually a transformer, with a very high

secondary-to-primary turns ratio.

When the points first close, current starts to flow in the primary winding and eventually

reaches the final value set by the 12V battery and the current limiting resistor. At this time,

the current flow is a fixed DC value, which means no voltage is generated across either

winding of the transformer. When the points open, the current in the primary winding

collapses very quickly, causing a large voltage to appear across this winding. This voltage

on the primary is magnetically coupled to (and stepped up by) the secondary winding,

generating a voltage of 30 kV - 40 kV on the secondary side. As explained previously, the

law of inductance says that it is not possible to instantly break the current flowing in an

inductor (because an infinite voltage would be required to make it happen).

This principle is what causes the arcing across the contacts used in switches that are in

circuits with highly inductive loads. When the switch just begins to open, the high voltage

generated allows electrons to jump the air gap so that the current flow does not actually

stop instantly. Placing a capacitor across the contacts helps to reduce this arcing effect. In

40

Page 41: Embedded System

the automobile ignition, a capacitor is placed across the points to minimize damage due to

arcing when the points "break" the current flowing in the low-voltage coil winding

PULSE WIDTH MODULATION (PWM):-

All of the switching converters that will be covered in this paper use a form of output

voltage regulation known as Pulse Width Modulation (PWM). Put simply, the feedback

loop adjusts (corrects) the output voltage by changing the ON time of the switching

element in the converter. As an example of how PWM works, we will examine the result

of applying a series of square wave pulses to an L-C filter (see Figure).

The series of square wave pulses is filtered and provides a DC output voltage that is equal

to the peak pulse amplitude multiplied times the duty cycle (duty cycle is defined as the

switch ON time divided by the total period). This relationship explains how the output

voltage can be directly controlled by changing the ON time of the switch.

41

Page 42: Embedded System

Switching Converter Topologies

The most commonly used DC-DC converter circuits will now be presented along with the

basic principles of operation.

BUCK REGULATOR:

The most commonly used switching converter is the Buck, which is used to down-convert

a DC voltage to a lower DC voltage of the same polarity. This is essential in systems that

use distributed power rails (like 24V to 48V), which must be locally converted to 15V,

12V or 5V with very little power loss. The Buck converter uses a transistor as a switch that

alternately connects and disconnects the input voltage to an inductor (see Figure).

Buck regulator

42

Page 43: Embedded System

The lower diagrams show the current flow paths (shown as the heavy lines) when the

switch is on and off. When the switch turns on, the input voltage is connected to the

inductor. The difference between the input and output voltages is then forced across the

inductor, causing current through the inductor to increase. During the on time, the inductor

current flows into both the load and the output capacitor (the capacitor charges during this

time). When the switch is turned off, the input voltage applied to the inductor is removed.

However, since the current in an inductor can not change instantly, the voltage across the

inductor will adjust to hold the current constant. The input end of the inductor is forced

negative in voltage by the decreasing current, eventually reaching the point where the

diode is turned on. The inductor current then flows through the load and back through the

diode. The capacitor discharges into the load during the off time, contributing to the total

current being supplied to the load (the total load current during the switch off time is the

sum of the inductor and capacitor current). The shape of the current flowing in the inductor

is similar to Figure:-

As explained, the current through the inductor ramps up when the switch is on, and ramps

down when the switch is off. The DC load current from the regulated output is the average

value of the inductor current. The peak-to-peak difference in the inductor current

43

Page 44: Embedded System

waveform is referred to as the inductor ripple current, and the inductor is typically selected

large enough to keep this ripple current less than 20% to 30% of the rated DC current.

R 2022 0 E

R 2 21 K

R 2 11 K

R 1 7R

C 1 94 7 3

C 1 4C

R 2 41 K

R 2 31 0 K P O T

U 1 7TL 4 3 1

3 1

2

J 3 0

C O N 8

V C C1

V C C2

g a te3

is e n s e4

v f b5

g n d6

g n d7

g n d8

v in

L 8

I N D U C TO R A U D I O

I N S 1 6 3 5 5 5123 4

56

R 1 8R

R 1 9R

C 1 7C

J 2 9

C O N 2

12

J 2 8

C O N 2

12

C 1 8C

L 9

I N D U C TO R A U D I O

I N S 1 3 9 2 6 1123 4

56

v o u tv in

C 1 5C

C 1 6C

L 7

I N D U C TO R A U D I O

I N S 1 3 9 4 2 1123 4

56

Q 3I R F Z 44 N / TO

D3 MB

R10

45/T

O

2

1 3

Buck regulator

44

Page 45: Embedded System

CONTINUOUS vs. DISCONTINUOUS OPERATION

In most Buck regulator applications, the inductor current never drops to zero during full-

load operation (this is defined as continuous mode operation). Overall performance is

usually better using continuous mode, and it allows maximum output power to be obtained

from a given input voltage and switch current rating. In applications where the maximum

load current is fairly low, it can be advantageous to design for discontinuous mode

operation. In these cases, operating in discontinuous mode can result in a smaller overall

converter size (because a smaller inductor can be used). Discontinuous mode operation at

lower load current values is generally harmless, and even converters designed for

continuous mode operation at full load will become discontinuous as the load current is

decreased

BOOST REGULATOR

The Boost regulator takes a DC input voltage and produces a DC output voltage that is

higher in value than the input (but of the same polarity). The Boost regulator is shown in

Figure, along with details showing the path of current flow during the switch on and off

time.

45

Page 46: Embedded System

Boost regulator

Whenever the switch is on, the input voltage is forced across the inductor which causes the

current through it to increase (ramp up).

When the switch is off, the decreasing inductor current forces the "switch" end of the

inductor to swing positive. This forward biases the diode, allowing the capacitor to charge

up to a voltage that is higher than the input voltage. During steady-state operation, the

inductor current flows into both the output capacitor and the load during the switch off

time. When the switch is on, the load current is supplied only by the capacitor.

OUTPUT CURRENT AND LOAD POWER

An important design consideration in the Boost regulator is that the output load current and

the switch current are not equal, and the maximum available load current is always less

than the current rating of the switch transistor. It should be noted that the maximum total

power available for conversion in any regulator is equal to the input voltage multiplied

times the maximum average input current (which is less than the current rating of the

switch transistor). Since the output voltage of the Boost is higher than the input voltage, it

follows that the output current must be lower than the input current.

46

Page 47: Embedded System

Q 1

IRF

Z44

N/T

O

R 5R

R 2R

C 5C

D 1

M B R 1 0 4 5 / TO

2

1

3

J 2 4

C O N 8

V C C1

V C C2

g a te3

is e n s e4

v f b5

g n d6

g n d7

g n d8

R 32 2 0 E

L 2T1 0 6

IN S 1 5 74 7 6123 4

56

R 61 K

C 4C

R 41 K

R 81 K

C 64 7 0 uF

R 71 0 K P O T

R 1R

v inJ 2 3

C O N 2

12

J 2 2

C O N 2

12

C 3C

L 1 4

I N D U C TO RL 1 5

I N D U C TO R

v o u t

v in

C 21 0 0 0u F 5 0 V

C 11 0 0 0u F 5 0 V

U 1 5TL 4 31

3 1

2

Boost regulator

BUCK-BOOST (INVERTING) REGULATOR

47

Page 48: Embedded System

The Buck-Boost or Inverting regulator takes a DC input voltage and produces a DC output

voltage that is opposite in polarity to the input. The negative output voltage can be either

larger or smaller in magnitude than the input voltage.

Buck- boost regulator

When the switch is on, the input voltage is forced across the inductor, causing an

increasing current flow through it. During the on time, the discharge of the output

capacitor is the only source of load current.

This requires that the charge lost from the output capacitor during the on time be

replenished during the off time. When the switch turns off, the decreasing current flow in

the inductor causes the voltage at the diode end to swing negative. This action turns on the

diode, allowing the current in the inductor to supply both the output capacitor and the load.

As shown, the load current is supplied by inductor when the switch is off, and by the

output capacitor when the switch is on.

48

Page 49: Embedded System

Q 1

IRF

Z44

N/T

O

R 5R

R 2R

C 5C

D 1

M B R 1 0 4 5 / TO

2

1

3

J 2 4

C O N 8

V C C1

V C C2

g a te3

is e n s e4

v f b5

g n d6

g n d7

g n d8

R 32 2 0 E

L 2T1 0 6

I N S 1 5 7 4 7 6123 4

56

R 61 K

C 4C

R 41 K

R 81 K

C 64 7 0 u F

R 71 0 K P O T

R 1R

v inJ 2 3

C O N 2

12

J 2 2

C O N 2

12

C 3C

L 1 4

I N D U C TO RL 1 5

I N D U C TO R

v o u t

v in

C 21 0 0 0 u F 5 0 V

C 11 0 0 0 u F 5 0 V

U 1 5TL 4 3 1

3 1

2

Buck- Boost regulator

FLYBACK REGULATOR

49

Page 50: Embedded System

The Flyback is the most versatile of all the topologies, allowing the designer to create one

or more output voltages, some of which may be opposite in polarity. Flyback converters

have gained popularity in battery-powered systems, where a single voltage must be

converted into the required system voltages (for example,+5V, +12V and -12V) with very

high power conversion efficiency. The basic single-output flyback converter is shown in

Figure:-

The most important feature of the Flyback regulator is the transformer phasing, as shown

by the dots on the primary and secondary windings. When the switch is on, the input

voltage is forced across the transformer primary which causes an increasing flow of

current

50

Page 51: Embedded System

through it. Note that the polarity of the voltage on the primary is dot-negative (more

negative at the dotted end), causing a voltage with the same polarity to appear at the

transformer secondary (the magnitude of the secondary voltage is set by the transformer

secondary-to-primary turns ratio). The dot-negative voltage appearing across the secondary

winding turns off the diode, preventing current flow in the secondary winding during the

switch on time. During this time, the load current must be supplied by the output capacitor

alone. When the switch turns off, the decreasing current flow in the primary causes the

voltage at the dot end to swing positive. At the same time, the primary voltage is reflected

to the secondary with the same polarity. The dot-positive voltage occurring across the

secondary winding turns on the diode, allowing current to flow into both the load and the

output capacitor. The output capacitor charge lost to the load during the switch on time is

replenished during the switch off time. Flyback converters operate in either continuous

mode (where the secondary current is always >0) or discontinuous mode.

v in

v o u tC 2 0

1 0 0 0 u F 5 0 VC 2 11 0 0 0 u F 5 0 V

L 1 0T1 0 6

IN S 1 0 3 8 1 9123 4

56

J 3 2

C O N 2

12

C 2 31 0 0 0 u F 5 0 V

L 1 1

T1 0 6

IN S 1 3 5 1 6 0123 4

56

J 3 3

C O N 8

V C C1

V C C2

g a t e3

is e n s e4

v f b5

g n d6

g n d7

g n d8

v in

R 2 72 2 0 E

R 2 91 K

R 2 81 K

C 2 54 7 3

R 3 21 K

R 3 11 0 K P O T

U 1 8TL 4 3 1

3 1

2

T1TR A N _ H M 3 1

1 4

3 6

R 3 01 0 E 4 W

J 3 1

C O N 2

12

R 2 55 0 0 K

C 2 4C A P N P

Q 4IR F Z 4 4 N /TO

R 2 6R

D 4

M B R 1 0 4 5 /TO

2

1

3C 2 21 0 0 0 u F 5 0 V

51

Page 52: Embedded System

Flyback Regulator

GE

GENERATING MULTIPLE OUTPUTS

Another big advantage of a Flyback is the capability of providing multiple outputs (see

Figure). In such applications, one of the outputs (usually the highest current) is selected to

provide PWM feedback to the control loop, which means this output is directly regulated.

The other secondary winding(s) are indirectly regulated, as their pulse widths will follow

the regulated winding. The load regulation on the unregulated secondary is not great

(typically 5 - 10%), but is adequate for many applications. If tighter regulation is needed

on the lower current secondary, an LDO post-regulator is an excellent solution. The

secondary voltage is set about 1V above the desired output voltage, and the LDO provides

excellent output regulation with very little loss of efficiency.

52

Page 53: Embedded System

Typical multiple output fly back

ANALOG SYSTEM:-

OP-AMP

The op-amp was originally designed to carry out mathematical operations in analogue computers, such as bombsights, but was soon recognized as having many other applications.

53

Page 54: Embedded System

The op-amp usually comes in the form of an 8 pin integrated circuit, the most common one being the type 741.

It has two inputs and one output. The input marked with a  - sign produces an amplified inverted output. The input marked with a + sign produces an amplified but non inverted output.

The op-amp requires positive and negative power supplies, together with a common ground. Some circuits can be designed to work from a single supply. If the two inputs are joined together, then the output voltage should be midway between the two supply rails, i.e. zero volts

Comparator :-

A varying input voltage is compared with a fixed reference voltage.

54

Page 55: Embedded System

If the input voltage is higher than the reference voltage, then the output is negative.

If the input voltage is lower than the reference, then the output is positive.

The gain can be set by negative feedback.

OP 07

GENERAL DESCRIPTION

The OP07 has very low input offset voltage (75 V max for OP07E) which is obtained by trimming at the wafer stage. These low offset voltages generally eliminate any need for external nulling. The OP07 also features low input bias current (ア4 nA for OP07E) and high open-loop gain (200 V/mV for OP07E). Thelow offsets and high open-loop gain make the OP07 particularly useful for high-gain instrumentation applications. The wide input voltage range of ア13 V minimum combined with high CMRR of 106 dB (OP07E) and high input impedance provides high accuracy in the non-inverting circuit configuration.Excellent linearity and gain accuracy can be maintained even at high closed-loop gains. Stability of offsets and gain with time or variations in temperature is excellent. The accuracy and stabilityof the OP07, even at high gain, combined with the freedom from external nulling have made the OP07 an industry standard for instrumentation applications. The OP07 is available in two standard performance grades. The OP07E is specified for operation over the 0ーC to 70ーC range, and OP07C over the –40ーC to +85ーC temperature range. The OP07 is available in epoxy 8-lead Mini-DIP and 8-lead SOIC.It is a direct replacement for 725,108A, and OP05 amplifiers; 741-types may be directly replaced by removing the 741’s nulling potentiometer.

PIN DIAGRAM

55

Page 56: Embedded System

FEATURES:

Low VOS: 75 _V MaxLow VOS Drift: 1.3 _V/_C MaxUltra-Stable vs. Time: 1.5 _V/Month MaxLow Noise: 0.6 _V p-p MaxWide Input Voltage Range: _14 VWide Supply Voltage Range: 3 V to 18 VFits 725,108A/308A, 741, AD510 Sockets125_C Temperature-Tested Dice

APPLICATIONS:

Wireless Base Station Control CircuitsOptical Network Control CircuitsInstrumentationSensors and ControlsThermocouplesRTDsStrain BridgesShunt Current MeasurementsPrecision Filters

INSTRUMENTATION AMPLIFIER

The term Instrumentation amplifier is used to denote a high gain dc coupled differential amplifier with single ended output, high input impedance, and high CMRR. They are used to amplify small differential signals coming from the transducers in which there may be a large common mode signal.

Types of the instrumentation amplifier

56

Page 57: Embedded System

Two op-amp design Three op- amp design

AD620

AD620 is an instrumentation amplifier with three OP-amp designs. The AD620 is a low cost, high accuracy instrumentation amplifier that requires only one external resistor to set gains of 1 to 1000. Furthermore, the AD620 features 8-lead SOIC and DIP packaging that is smaller than discrete designs, and offers lower power (only 1.3 mA max supply current), making it a good fit for battery powered, portable

PIN DIAGRAM:

(Or remote) applications. The AD620, with its high accuracy of 40 ppm maximum nonlinearity, low offset voltage of 50 V max and offset drift of 0.6 V/C max, is ideal for use in precision data acquisition systems, such as weigh scales and transducer interfaces. Furthermore, the low noise, low input bias current, and low power of the AD620 make it well suited for medical applications suchas ECG and noninvasive blood pressure monitors. The low input bias current of 1.0 nA max is made possible with the use of Superbeta processing in the input stage. The AD620 works well as a preamplifier due to its low input voltage noise of 9 nV/Hz at 1 kHz, 0.28 V p-p in the 0.1 Hz to 10 Hz band, 0.1 pA/Hz input current noise. Also, the AD620 is

57

Page 58: Embedded System

well suited for multiplexed applications with its settling time of 15 s to 0.01% and its cost is low enough to enable designs with one inamp per channel.

FEATURES:

EASY TO USE

Gain Set with One External Resistor (Gain Range 1 to 1000) Wide Power Supply Range (62.3 V to 618 V) Higher Performance than Three Op Amp IA Designs Available in 8-Lead DIP and SOIC Packaging Low Power, 1.3 mA max Supply Current

EXCELLENT DC PERFORMANCE (“B GRADE”):

50 mV max, Input Offset Voltage 0.6 mV/8C max, Input Offset Drift nA max, Input Bias Current 100 dB min Common-Mode Rejection Ratio (G = 10)

LOW NOISE:

9 nV/Hz, @ 1 kHz, Input Voltage Noise 0.28 mV p-p Noise (0.1 Hz to 10 Hz)

EXCELLENT AC SPECIFICATIONS:

120 kHz Bandwidth (G = 100) 15 ms Settling Time to 0.01%

THEORY OF OPERATION:

The AD620 is a monolithic instrumentation amplifier based on a modification of the classic three op amp approach. Absolute value trimming allows the user to program gain accurately (to 0.15% at G = 100) with only one resistor. Monolithic construction and laser wafer trimming allow the tight matching and tracking of circuit components, thus ensuring the high level of performance inherent in this circuit. The input transistors Q1 and Q2 provide a single differential pair bipolar input for high precision (Figure 33), yet offer 10´

58

Page 59: Embedded System

lower Input Bias Current thanks to Superbeta processing. Feedback through the Q1-A1-R1 loop and the Q2-A2-R2 loop maintains constant collector current of the input devices Q1, Q2 thereby impressing the input voltage across the external gain setting resistor RG. This creates a differential gain from the inputs to the A1/A2 outputs given by G = (R1 + R2)/RG + 1. The unity-gain subtracter A3 removes any common-mode signal, yielding a single-ended output referred to the REF pin potential. The value of RG also determines the transconductance of the preamp stage. As RG is reduced for larger gains, the transconductance increases asymptotically to that of the input transistors.

This has three important advantages:

(a) Open-loop gain is boosted for increasing programmed gain, thus reducing gain related errors. (b) The gain-bandwidth product (determined by C1, C2 and the preamp transconductance) increases with programmed gain, thus optimizing frequency response. (c) The input voltage noise is reduced to a value of 9 nV/Hz, determined mainly by the collector current and base resistance of the input devices.

The internal gain resistors, R1 and R2, are trimmed to an absolute value of 24.7 k, allowing the gain to be programmed accurately with a single external resistor.

The gain equation is then

APPLICATIONS:

Weigh Scales ECG and Medical Instrumentation Transducer Interface Data Acquisition Systems Industrial Process Controls Battery Powered and Portable Equipment

59

Page 60: Embedded System

THYRISTOR

The thyristor is also known as the silicon controlled rectifier (S.C.R.). It has the same characteristics as the diode, current flowing from cathode to anode, when the anode is positive with respect to the cathode

. However, it will only do this when the gate is also positive with respect to the cathode.

In the circuit, with the switch open as shown, no current flows.

When the switch is closed, the diode begins to conduct and current flows from cathode to anode.

There is a problem. If the switch is now opened, current continues to flow.

Conduction can be stopped by removing the cathode/anode voltage.

Another method of stopping current flow is to reverse the polarity of the cathode/anode voltage.

If the thruster is used with an ac supply then it will conduct on the positive half cycles and automatically switch off during the negative half cycles.

The resistor in series with the gate connection limits the gate current to a safe value.

60

Page 61: Embedded System

TRIAC AND DIAC:

The triac conducts in both directions and provides full wave control of power. Variable phase trigger pulses are provided by the pulse generator and are positive with respect b1.

The diac is high resistance below a certain voltage, say 30 volts, but when the applied voltage exceeds this value, it goes low resistance and conducts, applying a pulse to the gate.

It gives more reliable triggering of the triac.

Control of the Thyristor

To obtain full wave operation, so that the lamp can be provided with the full ac supply voltage, two thyristors are required as shown. Th1 is triggered during the positive half cycles of the ac supply, and Th2 during the negative half cycles.

61

Page 62: Embedded System

The waveforms show the thyristors being triggered halfway through each half cycle and the current through the lamp would be the sum of the two currents. The lamp will be at about half brightness

A pulse generator and a phase shift circuit is necessary to provide gate pulses which can adjust the power from minimum to maximum.

Since the gate voltages have to be positive with respect to the cathodes, attention must be paid to the polarity of the gating pulses with respect each other.

The high power ac circuit can be isolated from the control circuits by means of transformers or opto isolators.

Multivibrators:

Multivibrators (sometimes called FLIP-FLOPS) have two "cross coupled" transistors, say TR1 and TR2. This causes TR1 to be on (conducting) and TR2 off. They can be made to reverse states, with TR1 turning off and TR2 turning on. Multivibrators are of mainly two types

Astable multivibrator

Monostable multivibrator

555 timer

DESCRIPTION

The 555 monolithic timing circuit is a highly stable controller capable of producing accurate time delays, or oscillation. In the time delay mode of operation, the time is precisely controlled by one external resistor and capacitor. For a stable operation as an oscillator, the free running frequency and the duty cycle are both accurately controlled with two external resistors and one capacitor. The circuit may be triggered and reset on falling waveforms, and the output structure can source or sink up to 200 mA.

PIN DIAGRAM

62

Page 63: Embedded System

FEATURES

Turn-off time less than 2 s Max. operating frequency greater than 500 kHz Timing from microseconds to hours Operates in both astable and monostable modes Operates in both astable and monostable modes High output current Adjustable duty cycle TTL compatible Temperature stability of 0.005% per C

APPLICATIONS

Precision timing Pulse generation Sequential timing Time delay generation Pulse width modulation

EMBEDDED SYSTEM

What is Embedded System?

Embedded system employs a combination of software & hardware to perform a specific function. It is a part of a larger system which may not be a “computer”Works in a reactive & time constrained environment.Any electronic system that uses a CPU chip, but that is not a general-purpose workstation, desktop or laptop computer is known as embedded system. Such systems generally use microprocessors; microcontroller or they may use custom-designed chips

63

Page 64: Embedded System

or both. They are used in automobiles, planes, trains, space vehicles, machine tools, cameras, consumer and office appliances, cell phones, PDAs and other handhelds as well as robots and toys. The uses are endless, and billions of microprocessors are shipped every year for a myriad of applications.

In embedded systems, the software is permanently set into a read-only memory such as a ROM or flash memory chip, in contrast to a general-purpose computer that loads its programs into RAM each time. Sometimes, single board and rack mounted general-purpose computers are called "embedded computers" if used to cont

Embedded System Applications :- Consumer electronics, e.g., cameras, cell phones etc. Consumer products, e.g. washers, microwave ovens etc. Automobiles (anti-lock braking, engine control etc.) Industrial process controller & defense applications. Computer/Communication products, e.g. printers, FAX machines etc. Medical Equipments. ATMs Aircrafts

DIFFERENCE BETWEEN MICROPROCESSORS AND MICROCONTROLLERS:

A Microprocessor is a general purpose digital computer central processing

unit(C.P.U) popularly known as CPU on the chip. The Microprocessors

contain no RAM, no ROM, and no I/P O/P ports on the chip itself.

On the other hand a Microcontroller has a C.P.U(microprocessor) in addition

to a fixed amount of RAM, ROM, I/O ports and a timer all on a single chip.

64

Page 65: Embedded System

In order to make a Microprocessor functional we must add RAM, ROM, I/O

Ports and timers externally to them,i.e any amount of external memory can be

added to it.

But in controllers there is a fixed amount of memory which makes them ideal

for many applications.

The Microprocessors have many operational codes(opcodes) for moving data

from external memory to the C.P.U

Whereas Microcontrollers may have one or two operational codes.

DISADVANTAGES OF MICROPROCESSORS OVER MICROCONTROLLERS

System designed using Microprocessors are bulky

They are expensive than Microcontrollers

We need to add some external devices such as PPI chip, Memory,

Timer/counter chip, Interrupt controller chip,etc. to make it functional.

Types of microcontroller architecture:

There are two types of Microcontroller architecture designed for embedded system development. These are:

1)RISC- Reduced instruction set computer 2)CISC- Complex instruction set computer

Difference between CISC and RISC:

65

Page 66: Embedded System

CISC stands for Complex Instruction Set Computer. Most PC's use CPU based on this architecture. For instance Intel and AMD CPU's are based on CISC architectures. Typically CISC chips have a large amount of different and complex instructions. In common CISC chips are relatively slow (compared to RISC chips) per instruction, but use little (less than RISC) instructions. MCS-51 family microcontrollers based on CISC architecture.

RICS stands for Reduced Instruction Set Computer. The philosophy behind it is that almost no one uses complex assembly language instructions as used by CISC, and people mostly use compilers which never use complex instructions. Therefore fewer, simpler and faster instructions would be better, than the large, complex and slower CISC instructions. However, more instructions are needed to accomplish a task. Atmell’s AVR microcontroller based on RISC architecture.

History of 8051

Intel Corporation introduced an 8-bit microcontroller called 8051 in 1981 this controller had 128 bytes of RAM, 4k bytes of on chip ROM, two timers, one serial port, and four ports all are on single chip. The 8051 is an 8 bit processor, meaning that the CPU can work on only 8 bit data at a time. Data larger than 8 bits broken into 8 bit pieces to be processed by CPU. It has for I/O 8 bit wide.

Features of the 8051:-

Feature Quantity ROM 4K bytesRAM 128 bytesTimer 2I/O pins 32Serial port 1Interrupt sources 6

8051 Architecture Overview

The 8051 family is one of the most common microcontroller architectures used worldwide.

8051 based microcontrollers are offered in hundreds of variants from many different

silicon manufacturers.

66

Page 67: Embedded System

The 8051 is based on an 8-bit CISC core with Harvard architecture. It's an 8-bit CPU,

optimized for control applications with extensive Boolean processing (single-bit logic

capabilities), 64K program and data memory address space and various on-chip

peripherals.

The 8051 microcontroller family offers developers a wide variety of high-integration and

cost-effective solutions for virtually every basic embedded control application. From traffic

control equipment to input devices and computer networking products, 8051

microcontrollers deliver high performance together with a choice of configurations and

options matched to the special needs of each application. Whether it's low power operation,

higher frequency performance, expanded on-chip RAM, or an application-specific

requirement, there's a version of the 8051 microcontroller that's right for the job.

When it's time to upgrade product features and functionality, the 8051 architecture puts

you on the first step of a smooth and cost-effective upgrade path - to the enhanced

performance of the 151 and 251 microcontrollers

Block diagram of 8051

67

Page 68: Embedded System

68

Page 69: Embedded System

Internal Architecture of 8051

69

Page 70: Embedded System

Pin configuration of 8051

70

Page 71: Embedded System

71

Page 72: Embedded System

   There are four ports P0, P1, P2 and P3 each use 8 pins, making them 8-bit ports. All the

ports upon RESET are configured as output, ready to be used as output ports. To use any of

these ports as an input port, it must be programmed.

Port 0:- Port 0 occupies a total of 8 pins (pins 32-39) .It can be used for input or output. To

use the pins of port 0 as both input and output ports, each pin must be connected externally

to a 10K ohm pull-up resistor. This is due to the fact that P0 is an open drain, unlike P1,

P2, and P3.Open drain is a term used for MOS chips in the same way that open collector is

used for TTL chips. With external pull-up resistors connected upon reset, port 0 is

configured as an output port. For example, the following code will continuously send out

to port 0 the alternating values 55H and AAH

MOV A,#55H

BACK: MOV P0,A

ACALL DELAY

CAPL A

SJMP BACK

Port 0 as input:-  With resistors connected to port 0, in order to make it an input, the port

must be programmed by writing 1 to all the bits. In the following code, port 0 is configured

first as an input port by writing 1's to it, and then data is received from the port and sent to

P1.                   

72

Page 73: Embedded System

                         

                     MOV A,#0FFH         ; A = FF hex

                        MOV P0,A                ; make P0 an input port

              BACK: MOV A,P0               ;get data from P0 

                        MOV P1,A                ;send it to port 1

                        SJMP BACK 

Dual Role of Port 0 :-Port 0 is also designated as AD0-AD7, allowing it to be used for both

address and data. When connecting an 8051/31 to an external memory, port 0 provides

both address and data. The 8051 multiplexes address and data through port 0 to save pins.

ALE indicates if P0 has address or data. When ALE = 0, it provides data D0-D7, but when

ALE =1 it has address and data with the help of a 74LS373 latch.

Port 1:- Port 1 occupies a total of 8 pins (pins 1 through 8). It can be used as input or

output. In contrast to port 0, this port does not need any pull-up resistors since it already

has pull-up resistors internally. Upon reset, Port 1 is configured as an output port. For

example, the following code will continuously send out to port1 the alternating values 55h 

73

Page 74: Embedded System

& AAh

 

MOV A,#55H                   ; A = 55 hex

       BACK: MOV P1,A                        ;send it to Port 1

  ACALL DELAY                  ;call delay routine   

CPL A                              ;make A=0

                    SJMP BACK                            

Port 1 as input:-To make port1 an input port, it must be programmed as such by writing 1

to all its bits. In the following code port1 is configured first as an input port by writing 1’s

to it, then data is received from the port and saved in R7 ,R6 & R5.

MOV A,#0FFH   ;A=FF HEX

         MOV P1,A         ;make P1 an input port by writing all 1’s to it

MOV A,P1         ;get data from P1

MOV R7,A         ;save it in register R7

ACALL DELAY    ;wait

MOV  A,P1         ;get another data from P1

MOV R6,A          ;save it in register R6

ACALL DELAY     ;wait

MOV  A,P1          ;get another data from P1

         MOV R5,A           ;save it in register R5                   

74

Page 75: Embedded System

Port 2 :-Port 2 occupies a total of 8 pins (pins 21- 28). It can be used as input or output.

Just like P1, P2 does not need any pull-up resistors since it already has pull-up resistors

internally. Upon reset,Port 2 is configured as an output port. For example, the following

code will send out continuously to port 2 the alternating values 55h and AAH. That is all

the bits of port 2 toggle continuously.

     MOV A,#55H          ; A = 55 hex

         BACK: MOV P2,A                      ;send it to Port

ACALL DELAY                 ;call delay routine   

  CPL A                              ;make A=0

                    SJMP BACK                           

  Port 2 as input:- To make port 2 an input, it must programmed as such by writing 1 to all

its bits. In the following code, port 2 is configured first as an input port by writing 1’s to it.

Then data is received from that port and is sent to P1 continuously.

    MOV A,#0FFH     ;A=FF hex

MOV P2,A           ;make P2 an input port by writing all 1’s to it

BACK: MOV A,P2           ;get data from P2

  MOV P1,A            ;send it to Port1

                SJMP BACK         ;keep doing that

Dual role of port 2:- In systems based on the 8751, 8951, and DS5000, P2 is used as

simple I/O. However, in 8031-based systems, port 2 must be used along with P0 to provide

the 16-bit address for the external memory. As shown in pin configuration 8051, port 2 is

also designed as A8-A15, indicating the dual function. Since an 8031 is capable of

75

Page 76: Embedded System

accessing 64K bytes of external memory, it needs a path for the 16 bits of the address.

While P0 provides the lower 8 bits via A0-A7, it is the job of P2 to provide bits A8-A15 of

the address. In other words, when 8031 is connected to external memory, P2 is used for the

upper 8 bits of the 16 bit address, and it cannot be used for I/O.

Port 3:- port 3 occupies a total of 8 pins, pins 10 through 17. It can be used as input or output. P3 does not need any pull-up resistors, the same as P1 and P2 did not. Although port 3 is configured as an output port upon reset. Port 3 has the additional function of providing some extremely important signals such as interrupts. This information applies both 8051 and 8031 chips. There functions are as follows:- 

        P3.0 and P3.1 are

used for the RxD and

TxD serial

communications signals.

Bits P3.2 and P3.3 are set

aside for external

interrupts. Bits P3.4 and

P3.5 are used for timers 0 and 1. Finally P3.6 and P3.7 are used to provide the WR and RD

signals of external memories connected in 8031 based systems.    

 Read modify write features:-

       The ports in the 8051 can be accessed by the read-modify-write technique. This feature

saves many lines of code by combining in a single instruction all three action of (1) reading

the port, (2) modifying it, and (3) writing to the port. The following code first places

01010101 (binary) into port 1. Next, the instruction “XLR P1,#0FFH” performs an XOR

logic operation on P1 with 1111 1111 (binary), and then writes the result back into P1.

76

PORT 3 Function pinP3.0 RxD 10P3.1 TxD 11P3.2 ___

Int0 12

P3.3 ___Int1

13

P3.4 T0 14P3.5 T1 15P3.6 ___

WR16

P3.7 ___RD

17

Page 77: Embedded System

  MOV P1,#55H

AGAIN: XLR P1,#0FFH

ACALL DELAY

SJMP AGAIN

 Notice that XOR of 55H and FFH gives AAH. Likewise, the XOR of AAH and FFH gives

55H.

 Single bit addressability of ports:-

There are times that we need to access only 1 or 2 bits of the port instead of the entire 8

bits. A powerful feature of 8051 I/O ports is their capability to access individual bits of the

port without altering the rest of the bits in that port.

For example, the following code toggles the bit p1.2 continuously.

 BACK:  CPL P1.2                   ; complement p1.2 only

  ACALL DELAY

      SJMP BACK

      Notice that P1.2 is the third bit of P1, since the first bit is P1.0, the second bit is P1.1,

and so on. Notices in example of those unused portions of port1 are undisturbed. Table

bellow shows the bits of 8051 I/O ports. This single bit addressability of I/O ports is one of

the features of the 8051 microcontroller.

 Single bit addressability of ports:

77

Page 78: Embedded System

PORT 0 PORT 1 PORT 2 PORT 3 PORT BITP0.0 P1.0 P2.0 P3.0 D0P0.1 P1.1 P2.1 P3.1 D1P0.2 P1.2 P2.2 P3.2 D2P0.3 P1.3 P2.3 P3.3 D3P0.4 P1.4 P2.4 P3.4 D4P0.5 P1.5 P2.5 P3.5 D5P0.6 P1.6 P2.6 P3.6 D6P0.7 P1.7 P2.7 P3.7 D7

AT89s52

AT89S8252 is an ATMEL controller with the core of intel MCS-51. It has same pin configuration as give above.

The AT89S8252 is a low-power, high-performance CMOS 8-bit microcomputer with 8K bytes of Downloadable Flash programmable and erasable read only memory and 2K bytes of EEPROM. The device is manufactured using Atmel’s high density nonvolatile memory technology and is compatible with the industry standard 80C51 instruction set and pinout. The on-chip Downloadable Flash allows the program memory to be reprogrammed in-system through an SPI serial interface or by a conventional nonvolatile memory programmer. By combining a versatile 8-bit CPU with Downloadable Flash on a monolithic chip, the Atmel AT89S8252 is a powerful microcomputer which provides a highly flexible and cost effective solution to many embedded control applications. The AT89S8252 provides the following standard features: 8K bytes of Downloadable Flash, 2K bytes of EEPROM, 256 bytes of RAM, 32 I/O lines, programmable watchdog timer, two Data Pointers, three 16-bit timer/counters, a six-vector two-level interrupt architecture, a full duplex serial port, on-chip oscillator, and clock circuitry. In addition, the AT89S8252 is designed with static logic for operation down to zero frequency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port, and interrupt system to continue functioning. The Power Down Mode saves the RAM contents but freezes the oscillator, disabling all other chip functions until the next interrupt or hardware reset.

78

Page 79: Embedded System

The Downloadable Flash can be changed a single byte at a time and is accessible through the SPI serial interface. Holding RESET active forces the SPI bus into a serial programming interface and allows the program memory to be written to or read from unless Lock Bit 2 has been activated.

Block diagram of AT89s52

Features• Compatible with MCS-51™Products• 8K bytes of In-System Reprogrammable Downloadable Flash Memory- SPI Serial Interface for Program Downloading- Endurance: 1,000 Write/Erase Cycles• 2K bytes EEPROM- Endurance: 100,000 Write/Erase Cycles• 4.0V to 6V Operating Range• Fully Static Operation: 0 Hz to 24 MHz• Three-Level Program Memory Lock

79

Page 80: Embedded System

• 256 x 8 bit Internal RAM• 32 Programmable I/O Lines• Three 16 bit Timer/Counters• Nine Interrupt Sources• Programmable UART Serial Channel• SPI Serial Interface• Low Power Idle and Power Down Modes• Interrupt Recovery From Power Down• Programmable Watchdog Timer• Dual Data Pointer• Power Off Flag

Pin Description

Furthermore, P1.4, P1.5, P1.6, and P1.7 can be configured as the SPI slave port select, data input/output and shift clock input/output pins as shown in the following table.

Port 1 also receives the low-order address bytes during Flash programming and verification.

80

Page 81: Embedded System

Port 2:

Port 2 is an 8-bit bidirectional I/O port with internal pullups. The Port 2 output buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins, they are pulled high bythe internal pullups 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 pullups. 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 use 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.

Port 3

Port 3 is an 8 bit bidirectional I/O port with internal pullups. The Port 3 output buffers can sink/source four TTL inputs. When 1s are written to Port 3 pins, they are pulled high bythe internal pullups and can be used as inputs. As inputs, Port 3 pins that are externally being pulled low will source current (IIL) because of the pullups. Port 3 also serves the functions of various special features of the AT89S8252, as shown in the following table. Port 3 also receives some control signals for Flash programming and verification.

81

Page 82: Embedded System

RST

Reset input. A high on this pin for two machine cycles while the oscillator is running resets the device.

ALE/PROG

Address Latch Enable 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.

PSEN

Program Store Enable is the read strobe to external program memory. When the AT89S8252 is executing code from external program memory, PSEN is activated twice each machinecycle, except that two PSEN activations are skipped during each access to external data memory.

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 when 12-volt programming is selected.

XTAL1

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

XTAL282

Page 83: Embedded System

Output from the inverting oscillator amplifier.

Hardware interfacings and programming

There are two types of programming language used for microcontroller programming: 1)Low Level Language(Assembly Language)2) High Level Language(C Language)_

We have used high level language for microcontroller programming due to its given advantages over assembly:

Advantages of C over Assembly language programming:

Knowledge of the processor instruction set is not required.

Details like register allocation and addressing of memory and data is managed by the

compiler.

Programs get a formal structure and can be divided into separate functions.

Programming and program test time is drastically reduced, this increases efficiency.

Keywords and operational functions can be used that come closer to how humans

think.

The supplied and supported C libraries contain many standard routines such as

numeric conversions.

Reusable code: Existing program parts can be more easily included into new

programs, because of the comfortable modular program construction techniques.

The C language based on the ANSI standard is very portable. Existing programs can

be quickly adapted to other processors as needed.

1)LED Interfacing(PORT as o/p):Port as output: In this topic we study how we send the values on ports and how we observe that value on ports. The microcontroller always loads the

83

Page 84: Embedded System

binary equivalent of value on the ports. For example we send 0x0A. Here 0x shows the value is in hexadecimal. The binary equivalent of 0x0A is 00001010. So if we send 0x0A the equivalent binary is observed on the port. The LSB is observed on the LSB pins of port and MSB observed on the MSB pins of port. Now how we observe the 0 and one’s physically. There is specific voltage level concerned with 0 and 1. These levels are TTL compatible.

Logic Out put pin

0 Low (0 volt)

1 High(5v10ma according to data sheet)

So we can verify the loaded value by checking voltage level using multimeter or by driving led from this voltage.

84

Page 85: Embedded System

Hardware interfacing of LED with AT89s8252

Tit le

S ize D o c u m en t N um be r R e v

D a te : S h e e t o f

<D oc > <R ev C od e >

<Tit le >

C u s t o m

1 1Tu es da y , D e c e m be r 2 6 , 2 0 0 6

Q 2 1B C 5 4 7A

Q 1 4 B C 5 4 7A

D 2 6

LE D

V C C

R 4 0

33 0E

D 2 7

LE D

V C C

R 4 1

33 0E

V C C

D 2 8

LE D

R 6 1

33 0E

D 2 9

LE D

R 6 2

33 0E

V C C

Q 1 5

B C 5 4 7 A

D 2 2

LE D

R 3 7

33 0E

V C C

Q 1 6

B C 5 4 7 A

Q 1 7

B C 5 4 7 A

Q 1 8B C 5 4 7A

D 2 3

LE D

V C C

R 3 8

33 0E

Q 1 9B C 5 4 7A D 2 4

LE D

V C C

R 3 9

33 0E

D 2 5

LE D

R 6 3

33 0E

V C C

Q 2 0B C 5 4 7A

U 1 0

A T89 S 8 25 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N29

A L E / P R O G30

EA

/VP

P31

VC

C40

P 1 .0 / T21

P 1 .1 / T2 -E X2

P 1 .23

P 1 .34

P 1 .4 / S S5

P 1 .5 / M O S I6

P 1 .6 / M I S O7

P 1 .7 / S C K8

P 2 .0 / A 821

P 2 .1 / A 922

P 2 .2 / A 1 023

P 2 .3 / A 1 124

P 2 .4 / A 1 225

P 2 .5 / A 1 326

P 2 .6 / A 1 427

P 2 .7 / A 1 528

P 3 .0 / R XD10P 3 .1 / TXD11

P 3 .2 / IN T01 2

P 3 .3 / IN T11 3

P 3 .4 / T01 4

P 3 .5 / T11 5

P 3 .6 / W R16P 3 .7 / R D17

P 0 .0 / A D 039

P 0 .1 / A D 138

P 0 .2 / A D 237

P 0 .3 / A D 336

P 0 .4 / A D 435

P 0 .5 / A D 534

P 0 .6 / A D 633

P 0 .7 / A D 732

C 4 533 pF

C 4 633 pF

Y 8

8 M h z

12

3

4

V C C V C C

R 710 K

C 4 71 0 uF /1 6 V

V C C

C 4 810 4

85

Page 86: Embedded System

C code for Blinking LEDs connected on PORT2:

#include<at89s52.h> void delay(unsigned int i);void main(void){

While(1){P2=0x00;Delay(0xffff);P2=0x00;Delay(0xff);}}void delay(unsigned int i)

{while(i!=0){i--;}}

C code for running LED connected on PORT2:

#include<at89s8252.h>void delay(unsigned int i);void main (){P0=0x00;while (1){delay(0xffff);P2_0=1;

86

Page 87: Embedded System

delay(0xffff);P2_0=0;P2_1=1;delay(0xffff);P2_1=0;P2_2=1;delay(0xffff);P2_2=0;P2_3=1;delay(0xffff);P2_3=0;P2_4=1;delay(0xffff);P2_4=0;P2_5=1;delay(0xffff);P2_5=0;P2_6=1;delay(0xffff);P2_6=0;P2_7=1;delay(0xffff);P2_7=0;P2_0=1

}}

void delay(unsigned int i){while (i!=0){i--;}}

2)Switch (PIN as input): Whenever we want take the output from microcontroller according to input we can use switch to give input with input configuration of port or pin. This switch may be mechanical switch or electronic switch(transistors, MOSFET etc)

87

Page 88: Embedded System

The inputs understandable by uc are only digital logic means 0 and 1. These logics according to the given voltage level:

Logic Voltage level1 >1 to 5v ( up to VCC )0 <1 to -5v

The current rating with this voltage level must be up to sink current.

C- Code for Key control Led’s Pattern.88

Page 89: Embedded System

#include<at89s8252.h>void delay(unsigned int i);

void main(void){unsigned char x=0;P2=0x00;P0_0=1; while(1) { if (P0_0==0){x++;} if (x==1){P2=0x00;delay(0xffff);P2=0xff;delay(0xffff);

} if(x==2) { P2=0xf0;delay(0xffff);P2=0x0f;delay(0xffff);}if(x==3) { x=0;P2=0;}} }

void delay(unsigned int i){ while(i!=0) { i--; } }

89

Page 90: Embedded System

3)Relay: A relay is an electrically controllable switch widely used in industrial controls, automobiles and appliances. It allows the isolation of two separate sections of a system with two different voltage sources. The electromechanical (or electromagnetic) relay (EMR) has 3 components: the coil, spring and contacts. When current flows through the coil, a magnetic field is created around the coil (the coil is energized) which causes the armature to be attracted to the coil. The armature’s contact acts like a switch and closes or opens a circuit.

When the coil is not energized, a spring pulls the armature to its normal state of open or closed.

In choosing a relay, the following characteristics need to be considered:

1. The contacts can be normally open (NO) or normally closed (NC). In the NC type, the contacts are closed when the coil is not energized. In the NO, the contacts are open when the coil is un-energized.

2. There can be one or more contacts (SPST, SPDT, DPDT relays).The voltage and current needed to energize the coil. The voltage can vary from a few volts to 50 volts, while the current can be from few mA to 20mA. The relay has a minimum voltage below which the coil will not be energized. This minimum voltage is called the “pull-in” voltage.

V C C

J 2 3

TO C O N TR O L L E R P I N

1

LS 1

R E L A Y S P D T

35

412

J 2 22 2 0 V A C (M A I N L E A D )

1 2

L 1B U L B

D 3 0

1N40

07

Q 2 2

B C 5 4 7Q 2 3

B C 5 4 7

R 6 51 0 0 k

R 6 4

1 0 0 E

V C C

J 2 45 V D C

1 2

C- code To ON/OFF AC Bulb through Relay:

#include<at89s8252.h>#define relay P0_0#define key1 P2_0

90

Page 91: Embedded System

void delay(unsigned int i);

void main (void){unsigned char x=0;

while(1){if(key1==0){ if(x==0){x=1;delay(0xffff);relay=1;}else{x=0;delay(0xffff);relay=0;}}} void delay(unsigned int i){ while(i!=0) { i--; } }

91

Page 92: Embedded System

4)Seven Segment display :

R 1 31 5 0K

R 1 41 5 0K

B

R 1 51 5 0 K

AF

G

R 1 61 5 0 K

BAG

F

Q 1

B C 5 57

BFAG

R19

100E

Q 2

B C 5 57

Q 3

B C 5 5 7

Q 4

B C 5 5 7

V C C

V C C

A

V C C

B

R20

100E

V C C

F R21

100E

G R22

100E

E

DC C

E E

DD

CJ 4

TO u c P O R T

1234

5678

U 1 774 L S 4 7

D 07

D 11

D 22

D 36

B I / R B O4

R B I5

L T3

A1 3B1 2

C1 1

D1 0

E9

F1 5

G1 4

VC

C16

GN

D8

C

J 1

5 V dc

12

D

R 24 2 2 0 E

R 25 2 2 0 ER 26 2 2 0 E

V C C

R 27 2 2 0 ER 28 2 2 0 E

V C C

R 29 2 2 0 ER 30 2 2 0 E

V C CV C C

E

R 3 11 0 k S IP 8

12 3 4 5 6 7 8

R 3215 0 K

V C C

R 3 31 5 0K

V C C

R 3 41 5 0 K

V C C

U 18

F o u r 7 S E G M E N T

d2

e1

d7

G/V

3

c4

dot

5

e6

G/V

8

c9

dot

10

b21

a22

G/v

23g

25b

26a

27G

/V28

f29

g30

f24

g40

f39

G/V

38

a37

b36

g35

f34

G/v

33

a32

b31

e11

d12

G/V

13

c14

dot

15

e16

d17

G/V

18

c19

dot

20

V C C

R 3515 0 K

ED C

B

J 5

To u c p in s f o r d o t d is p la y

1234

A

Q 5B C 5 47

Q 6B C 5 4 7

F

Q 7B C 5 4 7

G

Q 8B C 5 4 7

// four seven segment using single decoder counts the value up to 9999

#include <at89s8252.h>

#define cs0 P0_4#define cs1 P0_5#define cs2 P0_6#define cs3 P0_7void delay(unsigned int i);unsigned char read_adc(void);

92

Page 93: Embedded System

void dec(unsigned int digit) ;void dec2(unsigned int x); void disp_hex(unsigned char digit);

void main(void)

{unsigned int a=990;unsigned char c=0;//P0=0xff;//delay(0xffff);cs0=1;cs1=1;cs2=1;cs3=1;

while(1){a++;dec2(a);}}

void dec2(unsigned int x) { unsigned int a=0; unsigned char q=0; unsigned char y=0; unsigned char z=0; unsigned char m=0; unsigned char n=0; unsigned char r=0; unsigned char p=0;

unsigned char s=0;

93

Page 94: Embedded System

if(x<=99) {

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

{y=(x/10)*6+x;y=y>>4;y=y|0xe0;P0=y;delay(250);z=(x/10)*6+x;z=z&0x0f;z=z|0xd0;P0=z;delay(250);}}

if(x>99 && x<1000){for(a=0;a<=90;a++){y=x/100;z=y|0xe0;P0=z;delay(200);q=x-(y*100); m=q/10;n=m|0xd0;P0=n;

P1=z;delay(200);p=q-(m*10);p=p|0xb0;P0=p;delay(200);}}if(x>999 && x<10000){for(a=0;a<=70;a++){

94

Page 95: Embedded System

y=x/1000;z=y|0xe0;P0=z;delay(200);q=x-(y*1000); m=q/100;n=m|0xd0;P0=n;

P1=z;delay(200);p=q-(m*100);r=p/10;r=r|0xb0;P0=r;delay(200);p=p-(r*10);p=p|0x70;P0=p;delay(200);

}}}

void delay (unsigned int i){while(i!=0){i--;}}

5)DC motor:

6)Hardware interfacing of LCD(JHD162A):

On most displays, the pins are numbered on the LCD’s printed circuit board, but if not, it is

quit easy to locate pin1. Since the pin is connected to ground, it often has a thicker PCB

track connected to it, and it is generally connected to the metal work at some point.

95

Page 96: Embedded System

The function of each of the connections is shown in the table below:-

Pins 1 & 2 are the power supply lines, Vss & Vdd. The Vdd pin should be connected to the

positive supply & Vss to the 0V supply or ground.

Although the LCD module data sheets specify 5V D.C. supply (at only a few milliamps),

supplies of 6V & 4.5V both work well, and even 3V is sufficient for some modules.

Consequently, these modules can be effectively and economically powered by batteries.

Pin 3 is a control pin, Vee, which is used to alter the contrast of the display. Ideally, these pin

should be connected to a variable voltage supply. A preset potentiometer connected between

the power supply lines, with its wiper connected to the contrast pin is suitable in many cases,

but be aware that some modules may require a

negative potential; as low as 7V in some cases. For absolute simplicity, connecting this pin to

0V will often suffice.

Pin 4 is register select (RS) line.

PIN NO. NAME FUNCTION

1 Vss Ground

96

Page 97: Embedded System

2 Vdd +ve supply

3 Vee contrast

4 RS Register select

5 R/W Read/Write

6 E Enable

7 D0 Data Bit 0

8 D1 Data Bit 1

9 D2 Data Bit 2

10 D3 Data Bit 3

11 D4 Data Bit 4

12 D5 Data Bit 5

13 D6 Data Bit 6

14 D7 Data Bit 7

Three command control inputs. When this line is low, data bytes transferred to the display are treated as commands, and data bytes read from the display indicate its status. By setting the RS line high, character data can be transferred to and from the module.

Pin 5 is (R/W) line. This line is pulled low in order to write commands or character data to the module, or pulled high to read character data or status information from its registers.

Pin 6 is Enable (E) line. This input is used to initiate the actual transfer of commands or character data between the module and the data lines. When writing to the display, data is transferred only on the high to low transition of this signal. However, when reading from the display, data will become available shortly after the low to high transition and remain available until the signal falls low again.

Pins 7 to 14 are the eight data bus lines (D0 to D7). Data can be transferred to and from the display, either as a single 8-bit byte or as two 4-bit “nibbles”. In the latter case, only

97

Page 98: Embedded System

the upper four data lines (D4 to D7) are used. This $-bit mode is beneficial when using a microcontroller, as fewer I/O lines are required.

98

Page 99: Embedded System

U 1

A T8 9S 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9

A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 . 0 / T21

P 1 . 1 / T2 -E X2

P 1 . 23

P 1 . 34

P 1 . 4 / S S5

P 1 . 5 / M O S I6

P 1 . 6 / M I S O7

P 1 . 7 / S C K8

P 2 . 0 / A 82 1

P 2 . 1 / A 92 2

P 2 . 2 / A 1 02 3

P 2 . 3 / A 1 12 4

P 2 . 4 / A 1 22 5

P 2 . 5 / A 1 32 6

P 2 . 6 / A 1 42 7

P 2 . 7 / A 1 52 8

P 3 . 0 / R XD1 0

P 3 . 1 / TXD1 1

P 3 . 2 / IN T01 2

P 3 . 3 / I N T11 3

P 3 . 4 / T01 4

P 3 . 5 / T11 5

P 3 . 6 / W R1 6P 3 . 7 / R D1 7

P 0 . 0 / A D 03 9 P 0 . 1 / A D 13 8 P 0 . 2 / A D 23 7 P 0 . 3 / A D 33 6 P 0 . 4 / A D 43 5 P 0 . 5 / A D 53 4 P 0 . 6 / A D 63 3 P 0 . 7 / A D 73 2

J 2 L C D

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

C 13 3 p F

C 23 3 p F

Y 1

12

3

4

R 11 0 K

C 31 0 u F 1 6 V

V C C

VC

C R 5 2

5 6 E

VC

C

V C C

RS

Hardware intetrfacing of LCD with AT89s52 microcontroler

EN

C code for LCD display#include <at89s8252.h>#define LCDPRT P1#define RS P3_3#define EN P3_4 void delay(unsigned int i); void lcd_cmd(unsigned char a); void display(unsigned char b); void wait(void); void Init_lcd(void); void cursor_position(unsigned char c);

99

Page 100: Embedded System

void main(void){init_lcd();while(1)

{cursor_position(0x01);display('N');cursor_position(0x02);display('E');cursor_position(0x03);display('T');cursor_position(0x04);display('M');cursor_position(0x05);display('A');cursor_position(0x06);display('X'); }

}

void delay (unsigned int i) { while (i!=0) { i--; } }

void lcd_cmd(unsigned char a) { wait(); LCDPRT=a; RS=0; EN=1; EN=0; }

10

Page 101: Embedded System

void display(unsigned char b) { wait (); LCDPRT=b; RS=1; EN=1; EN=0; } void wait(void) { unsigned int count=300; while(count!=0) { count--; }

}

void Init_lcd(void) { lcd_cmd(0x3c); lcd_cmd(0x0c); lcd_cmd(0x06); lcd_cmd(0x01);

} void clear_lcd(void) { lcd_cmd(0x01); } void cursor_position(unsigned char c) { lcd_cmd(c+0x80); }

C code for string display on LCD:

#include<at89s8252.h>10

Page 102: Embedded System

#define LCDPRT P1#define RS P3_3#define EN P3_4code unsigned char name_arry[]={"NETMAX$"};void display_string(unsigned char *sp);void lcd_cmd(unsigned char a);void display(unsigned char b);void wait(void);void Init_lcd(void);void cursor_position(unsigned char c);

void main(void){Init_lcd();cursor_position(0x40);display_string(&name_arry); } void display_string(unsigned char *sp) { while(*sp!='$') {

display(*sp);

sp=sp+1; } }

void lcd_cmd(unsigned char a) { wait (); LCDPRT=a; RS=0; EN=1; EN=0;

10

Page 103: Embedded System

} void display(unsigned char b) { wait (); LCDPRT=b; RS=1; EN=1; EN=0; } void wait(void) { unsigned int count=300; while(count!=0) { count--; } } void Init_lcd(void) { lcd_cmd(0x3c); lcd_cmd(0x0c); lcd_cmd(0x06); lcd_cmd(0x01); } void cursor_position(unsigned char c) { lcd_cmd(c+0x80); }

3) ADC-0804 interfacing with AT89s52:

The ADC0804 family is CMOS 8-Bit, successive-approximation A/D converters

which use a modified potentiometer ladder and are designed to operate with the

8080A control bus via three-state outputs. These converters appear to the

10

Page 104: Embedded System

processor as memory locations or I/O ports, and hence no interfacing logic is

required. The differential analog voltage input has good common mode- rejection

and permits offsetting the analog zero-input voltage value. In addition, the voltage

reference input can be adjusted to allow encoding any smaller analog voltage span

to the full 8 bits of resolution.

Features• 80C48 and 80C80/85 Bus Compatible - No Interfacing Logic Required

• Conversion Time < 100s

• Easy Interface to Most Microprocessors

• Differential Analog Voltage Inputs

• TTL Compatible Inputs and Outputs

• On-Chip Clock Generator

• 0V to 5V Analog Voltage Input Range (Single + 5V Supply)

• No Zero-Adjust Required

PIN DIAGRAM

10

Page 105: Embedded System

Hardware interfacing of ADC-0804 for Temperature monitoring

R 210 K

C 61 0 u F 1 6 V

V C C

C 1 31 0 4

EOC

SOC

V C C

C 141u f /1 6v

R 622 0 E

U 4A D C 0 80 4

+I N6

-I N7

AG

ND

8

V R E F / 29

GN

D10

D B 711 D B 612 D B 513 D B 414 D B 315 D B 216 D B 117 D B 018

C LK R1 9V

CC

/VR

EF

20

C L K I N4

I N TR5

C S1

R D2

W R3

V C C

R 51 0 K

R 1 71 0 K

C 71 5 0 p F

U 21TL 4 31

23

1

C 81 u f / 1 6 v

C 9C A P

R SE N

LC D

C O N 1 6 _ 0

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

V C CR S E N R 5 5

5 6 E

Temprature monitoring system

U 2 2 L M 3 5 / S O

G N D3

V C C1

2

O U TP U T

R 5 31 k

V C C

U 2

A T8 9 S 8 2 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9 A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 . 0 / T21

P 1 . 1 / T2 -E X2

P 1 . 23

P 1 . 34

P 1 . 4 / S S5

P 1 . 5 / M O S I6

P 1 . 6 / M I S O7

P 1 . 7 / S C K8

P 2 . 0 / A 82 1

P 2 . 1 / A 92 2

P 2 . 2 / A 1 02 3

P 2 . 3 / A 1 12 4

P 2 . 4 / A 1 22 5

P 2 . 5 / A 1 32 6

P 2 . 6 / A 1 42 7

P 2 . 7 / A 1 52 8

P 3 . 0 /R XD1 0

P 3 . 1 /TXD1 1

P 3 . 2 / I N T0 1 2

P 3 . 3 / I N T11 3

P 3 . 4 /T01 4

P 3 . 5 / T11 5

P 3 . 6 /W R1 6

P 3 . 7 /R D1 7

P 0 . 0 /A D 03 9 P 0 . 1 /A D 13 8 P 0 . 2 /A D 23 7 P 0 . 3 /A D 33 6 P 0 . 4 /A D 43 5 P 0 . 5 /A D 53 4 P 0 . 6 /A D 63 3 P 0 . 7 /A D 73 2

C 43 3 p F

C 53 3 p F

Y 2

C R Y S TA L

12

3

4

V C CV C C

When interfacing is being done then gets lowered then only it allows the

controller to read the data, otherwise controller can not read the data.

is always grounded.

is software controlled.

10

Page 106: Embedded System

C- code For temperature monitoring system

#include <at89s8252.h>#define LCDPRT P1#define RS P3_3#define EN P3_4#define SOC P3_2#define EOC P3_5 unsigned char read_adc(void); void delay(unsigned int i); void lcd_cmd(unsigned char a); void display(unsigned char b); void wait(void); void Init_lcd(void); void clear_lcd(void); void cursor_position(unsigned char c);void disp_dec(unsigned int digit); code unsigned char table[16]={'0','1','2','3','4','5','6','7','8','9'}; void main(void){ unsigned char e; P2=0xff; Init_lcd(); while(1) { cursor_position(0x00); e=read_adc(); disp_dec(e); }} unsigned char read_adc(void) { unsigned char n; SOC=0; SOC=1; while(EOC==1)

10

Page 107: Embedded System

{ n=P2; }

return n; }

void delay (unsigned int i) { while (i!=0) { i--; } } void lcd_cmd(unsigned char a) { wait(); LCDPRT=a; RS=0; EN=1; EN=0; } void display(unsigned char b) { wait (); LCDPRT=b; RS=1; EN=1; EN=0; } void wait(void) { unsigned int count=300; while(count!=0) { count--; } } void Init_lcd(void) {

10

Page 108: Embedded System

lcd_cmd(0x3c); lcd_cmd(0x0c); lcd_cmd(0x06); lcd_cmd(0x01); }

void cursor_position(unsigned char c) { lcd_cmd(c+0x80); }

void disp_dec(unsigned int digit) {unsigned int temp;if(digit<100)

{temp=digit/10;display(table[temp]);temp=digit-temp*10;display(table[temp]);}

if(digit>99 && digit<1000){temp=digit/100;display(table[temp]);digit=digit-(temp*100);temp=digit/10;display(table[temp]);digit=digit-(temp*10);temp=digit;display(table[temp]);}

10

Page 109: Embedded System

4) Interfacing of Real time clock-DS12887

The DS12887 is real-time clocks (RTCs). The devices provide a real-time

clock/calendar, one time-of-day alarm, three maskable interrupts with a common

interrupt output, a programmable square wave, and 114 bytes of battery backed

static. The DS12887 integrates a quartz crystal and lithium energy source into a

24-pin encapsulated DIP package. The DS12C887 adds a century byte at address

32h. For all devices, the date at the end of the month is automatically adjusted for

months with fewer than 31 days, including correction for leap years. The devices

also operate in either 24-hour or 12-hour format with an AM/PM indicator. A

precision temperature-compensated circuit monitors the status of Vcc. If a primary

power failure is detected, the device automatically switches to a backup supply. A

lithium coin-cell battery can be connected to the VBAT input pin on the DS12885 to

maintain time and date operation when primary power is absent. The device is

accessed through a multiplexed byte-wide interface, which supports both Intel and

Motorola mode

Pin diagram

10

Page 110: Embedded System

PIN DESCRIPTIONAD0–AD7 – Multiplexed Address/Data BusNC – No ConnectionMOT – Bus Type SelectionCS – Chip SelectAS – Address StrobeR/ W – Read/Write InputDS – Data StrobeRESET – Reset InputIRQ – Interrupt Request OutputSQW – Square Wave OutputVCC – +5 Volt SupplyGND – GroundFeatures ♦ RTC Counts Seconds, Minutes, Hours, Day, Date, Month, and Year with Leap

Year Compensation Through 2099

♦ Binary or BCD Time Representation

♦ 12-Hour or 24-Hour Clock with AM and PM in 12-Hour Mode

♦ Daylight Saving Time Option

♦ Interfaced with Software as 128 RAM Locations

♦ 14 Bytes of Clock and Control Registers

♦ 114 Bytes of General-Purpose, Battery-Backed RAM (113 Bytes in the

DS12C887 and DS12C887A)

♦ Time-of-Day Alarm Once Per Second to Once Per Day

♦ Periodic Rates from 122μs to 500ms

♦ Programmable Square-Wave Output

♦ Automatic Power-Fail Detect and Switch Circuitry

♦ Optional 28-Pin PLCC Surface Mount Package or 32-Pin TQFP (DS12885

♦ Optional Encapsulated DIP (EDIP) Package with Integrated Crystal and Battery

(DS12887, DS12887A, DS12C887, DS12C887A)

♦ Optional Industrial Temperature Range Available11

Page 111: Embedded System

♦ Underwriters Laboratory (UL) Recognized

ADDRESS MAPThe address map of the DS12887 is shown in Figure 2. The address map consists of 114 bytes of userRAM, 10 bytes of RAM that contain the RTC time, calendar, and alarm data, and 4 bytes which are usedfor control and status. All 128 bytes can be directly written or read except for the following:1. Registers C and D are read–only.2. Bit 7 of Register A is read–only.3. The high order bit of the seconds byte is read–only.The contents of four registers (A,B,C, and D) are described in the “Registers” section.ADDRESS MAP DS12887

Register A:

11

UIP DV2 DV1 DV0 RS3 RS2 RS1 RS00 0 1 0 0 0 0 0

Page 112: Embedded System

UIPThe Update In Progress (UIP) bit is a status flag that can be monitored. When the UIP bit is a 1, theupdate transfer will soon occur. When UIP is a 0, the update transfer will not occur for at least 244 s.The time, calendar, and alarm information in RAM is fully available for access when the UIP bit is 0. TheUIP bit is read only and is not affected by RESET . Writing the SET bit in Register B to a 1 inhibits anyupdate transfer and clears the UIP status bit.DV0, DV1, DV2These 3 bits are used to turn the oscillator on or off and to reset the countdown chain. A pattern of 010 is the only combination of bits that will turn the oscillator on and allow the RTC to keep time. A pattern of 11X will enable the oscillator but holds the countdown chain in reset. The next update will occur at 500ms after a pattern of 010 is written to DV0, DV1, and DV2.RS3, RS2, RS1, RS0These four rate–selection bits select one of the 13 taps on the 15–stage divider or disable the divideroutput. The tap selected can be used to generate an output square wave (SQW pin) and/or a periodicinterrupt. The user can do one of the following:1. Enable the interrupt with the PIE bit;2. Enable the SQW output pin with the SQWE bit;3. Enable both at the same time and the same rate;

Register B:

SETWhen the SET bit is a 0, the update transfer functions normally by advancing the counts once per second.When the SET bit is written to a 1, any update transfer is inhibited and the program can initialize the timeand calendar bytes without an update occurring in the midst of initializing. Read cycles can be executedin a similar manner. SET is a read/write bit that is not modified by RESET or internal functions of the

11

SET PIE AIE UIE SQWE DM 24/12 DSE

Page 113: Embedded System

DS12887.PIEThe periodic interrupt enable PIE bit is a read/write bit which allows the Periodic Interrupt Flag (PF) bitin Register C to drive the IRQ pin low. When the PIE bit is set to 1, periodic interrupts are generated bydriving the IRQ pin low at a rate specified by the RS3–RS0 bits of Register A. A 0 in the PIE bit blocksthe IRQ output from being driven by a periodic interrupt, but the Periodic Flag (PF) bit is still set at theperiodic rate. PIE is not modified by any internal DS12887 functions, but is cleared to 0 on RESET .AIEThe Alarm Interrupt Enable (AIE) bit is a read/write bit which, when set to a 1, permits the Alarm Flag(AF) bit in Register C to assert IRQ . An alarm interrupt occurs for each second that the three time bytesequal the three alarm bytes including a “don’t care” alarm code of binary 11XXXXXX. When the AIE bitis set to 0, the AF bit does not initiate the IRQ signal. The RESET pin clears AIE to 0. The internalfunctions of the DS12887 do not affect the AIE bit.UIEThe Update Ended Interrupt Enable (UIE) bit is a read/ write that enables the Update End Flag (UF) bit inRegister C to assert IRQ . The RESET pin going low or the SET bit going high clears to UIE bit.SQWEWhen the Square Wave Enable (SQWE) bit is set to a 1, a square wave signal at the frequency set by therate–selection bits RS3 through RS0 is driven out on a SQW pin. When the SQWE bit is set to z0, theSQW pin is held low; the state of SQWE is cleared by the RESET pin. SQWE is a read/write bit.DMThe Data Mode (DM) bit indicates whether time and calendar information is in binary or BCD format.The DM bit is set by the program to the appropriate format and can be read as required. This bit is not

11

Page 114: Embedded System

modified by internal functions or RESET . A 1 in DM signifies binary data while a 0 in DM specifiesBinary Coded Decimal (BCD) data.24/12The 24/12 control bit establishes the format of the hours byte. A 1 indicates the 24–hour mode and a 0indicates the 12–hour mode. This bit is read/write and is not affected by internal functions of RESET .DS1288711 of 19DSEThe Daylight Savings Enable (DSE) bit is a read/write bit which enables two special updates when DSE is set to 1. On the first Sunday in April the time increments from 1:59:59 AM to 3:00:00 AM. On the lastSunday in October when the time first reaches 1:59:59 AM

Hardware interfacing of RTC-DS12887 with at89s52:

11

Page 115: Embedded System

U 2 6

A T8 9 S 8 2 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9

A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 . 0 / T21P 1 . 1 / T2 -E X2P 1 . 23P 1 . 34P 1 . 4 / S S5P 1 . 5 / M O S I6P 1 . 6 / M I S O7P 1 . 7 / S C K8

P 2 . 0 / A 82 1

P 2 . 1 / A 92 2

P 2 . 2 / A 1 02 3

P 2 . 3 / A 1 12 4

P 2 . 4 / A 1 22 5

P 2 . 5 / A 1 32 6

P 2 . 6 / A 1 42 7

P 2 . 7 / A 1 52 8

P 3 . 0 / R XD1 0

P 3 . 1 / TXD1 1

P 3 . 2 / IN T01 2

P 3 . 3 / IN T11 3

P 3 . 4 / T01 4

P 3 . 5 / T11 5

P 3 . 6 / W R1 6

P 3 . 7 / R D1 7

P 0 . 0 / A D 03 9

P 0 . 1 / A D 13 8

P 0 . 2 / A D 23 7

P 0 . 3 / A D 33 6

P 0 . 4 / A D 43 5

P 0 . 5 / A D 53 4

P 0 . 6 / A D 63 3

P 0 . 7 / A D 73 2

A D 0 0

U 2 7

D S 1 2 8 8 7

I R Q1 9

S Q W2 3

VC

C24

GN

D12

A D 04

A D 15

A D 26

A D 37

A D 48

A D 59

A D 61 0

A D 71 1

A S1 4

D S1 7

M O T1

R S T1 8

R / W1 5

C S1 3

C 3 13 3 pF

C 3 23 3 pF

Y 6

C R Y S TA L

12

3

4

V C C V C C

A D 0 2A D 0 3

R 5 71 0 K

C 3 3

10uF

16V

V C C

A D 0 4A D 0 5

C 3 01 0 4

A D 0 1

A D 0 6A D 0 7

V C C

L C D 1C O N 1 6 _ 0

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

R 5 81k

V C C

Hardware interfacing of RTC (DS12887) with AT89s52 microcontroler

C code for Real Time Clock:

#include<at89s8252.h>#define LCDPRT P1#define RS P3_3#define EN P3_4void bcdconv(unsigned int mb);void delay(unsigned int i);void lcd_cmd(unsigned char a);void display(unsigned char b);

11

Page 116: Embedded System

void wait(void);void Init_lcd(void);void cursor_position(unsigned char c);

struct rtc{ unsigned char second; unsigned char sa; unsigned char minute; unsigned char ma; unsigned char hours; unsigned char ha; unsigned char dow; unsigned char dom; unsigned char month; unsigned char years; unsigned char ra; unsigned char rb; unsigned char rc; unsigned char rd; };xdata at 0x0000 struct rtc ds12887;void main(void){unsigned int x;unsigned char sec;unsigned char hr;unsigned char min;Init_lcd();

ds12887.ra=0x20;ds12887.rb=0x80;ds12887.second=0x00;ds12887.minute=0x00;ds12887.hours=0x00;ds12887.dom=0x19;ds12887.month=0x10;ds12887.years=0x06;ds12887.rb=0x00;

11

Page 117: Embedded System

while(1){ sec=ds12887.second;cursor_position(0x00);bcdconv(sec);cursor_position(0x02);display(':');min=ds12887.minute;cursor_position(0x03);bcdconv(min);cursor_position(0x05);display(':'); hr=ds12887.hours; cursor_position(0x06); bcdconv(hr);cursor_position(0x40);display('s');cursor_position(0x42);display(':');cursor_position(0x43);display('m');cursor_position(0x45);display(':');cursor_position(0x46);display('h');

}}

void bcdconv(unsigned int mb){unsigned char x;unsigned char y;x=mb&0x0f;x=x|0x30;y=mb&0xf0;y=y>>4;

11

Page 118: Embedded System

y=y|0x30;display(y);display(x);}}void lcd_cmd(unsigned char a) { wait (); LCDPRT=a; RS=0; EN=1; EN=0; } void display(unsigned char b) { wait (); LCDPRT=b; RS=1; EN=1; EN=0; } void wait(void) { unsigned int count=300; while(count!=0) { count--; } }

void Init_lcd(void) { lcd_cmd(0x3c); lcd_cmd(0x0c); lcd_cmd(0x06); lcd_cmd(0x01); }

11

Page 119: Embedded System

void clear_lcd(void) { lcd_cmd(0x01); }

void cursor_position(unsigned char c) { lcd_cmd(c+0x80); }

5) Interfacing of DAC - 0808

DAC08088-Bit D/A ConverterGeneral DescriptionThe DAC0808 is an 8-bit monolithic digital-to-analog converter(DAC) featuring a full scale output current settling timeof50 ns while dissipating only 33 mW with ±5V supplies.No reference current (IREF) trimming is required for most applications ince the full scale output current is typically ±1LSB of 255 IREF/256. Relative accuracies of better than±0.19% assure 8-bit monotonicity and linearity while zerolevel output current of less than 4 μA provides 8-bit zero accuracy or IREF2 mA. The power supply currents of theDAC0808 is independent of bit codes, and exhibits essentiallyconstant device characteristics over the entire supplyvoltage range.The DAC0808 will interface directly with popular TTL, DTL orCMOS logic levels, and is a direct replacement for the C1508/MC1408. For higher speed applic

Featuresn Relative accuracy: ±0.19% error maximumn Full scale current match: ±1 LSB typn Fast settling time: 150 ns typn Noninverting digital inputs are TTL and CMOScompatiblen High speed multiplying input slew rate: 8 mA/μsn Power supply voltage range: ±4.5V to ±18Vn Low power consumption: 33 mW @ ±5

11

Page 120: Embedded System

Hardware interfacing of DAC-0808 with At89s52

U 3

A T8 9 S 8 2 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9

A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 .0 / T21

P 1 .1 / T2 -E X2

P 1 .23

P 1 .34

P 1 .4 / S S5

P 1 .5 / M O S I6

P 1 .6 / M I S O7

P 1 .7 / S C K8

P 2 .0 / A 82 1

P 2 .1 / A 92 2

P 2 .2 / A 1 02 3

P 2 .3 / A 1 12 4

P 2 .4 / A 1 22 5

P 2 .5 / A 1 32 6

P 2 .6 / A 1 42 7

P 2 .7 / A 1 52 8

P 3 .0 / R XD1 0P 3 .1 / TXD1 1

P 3 .2 / I N T01 2

P 3 .3 / I N T11 3

P 3 .4 / T01 4

P 3 .5 / T11 5

P 3 .6 / W R1 6P 3 .7 / R D1 7

P 0 .0 / A D 03 9

P 0 .1 / A D 13 8

P 0 .2 / A D 23 7

P 0 .3 / A D 33 6

P 0 .4 / A D 43 5

P 0 .5 / A D 53 4

P 0 .6 / A D 63 3

P 0 .7 / A D 73 2

C 1 03 3 p F

C 1 13 3 p F

Y 3

8 M h z12

3

4

V C C V C C

J 1 9

C O N 2

12

R 31 0 K

C 1 2

1 0 u F /1 6 VV C C

C 1 51 0 4

A O U T

P O T1 5 K EC 2 51 0 4

U 1 6d a c 0 8 08

+V R E F1 4

-V R E F1 5

G N D2

A 71 2 A 61 1 A 51 0 A 4

9 A 38 A 27 A 16 A 05

VE

E3

VC

C13

C O M P1 6

Io4 -

+

U 2 0O P 0 7

3

26

74 8

1

1 0 V

-1 0 V

R 4 7 5 K

C 4 21 0 4

R 4 8 5 K

V C C

-1 0 V

C 4 31 0 4

1 0 V

R 4 55 KC 4 4

1 0 4

C code for digital to analog conversion

#include<at89S8252.h>

void main (void){ while(1) { P2=1; P2=2; P2=3; P2=4; P2=5; P2=6; P2=7; P2=8; P2=9; P2=10;

12

Page 121: Embedded System

P2=11; P2=12; P2=13; P2=14; P2=15; P2=14; P2=13; P2=12; P2=10; P2=9; P2=8; P2=7; P2=6; P2=5; P2=4; P2=3; P2=2; P2=1; P2=0; }

}

12

Page 122: Embedded System

6) Serial communication between At89s52 and PC

a) Serial Transmission

SPT RXD

SPT TXD

U 5

A T8 9 S 8 2 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9

A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 . 0 / T21

P 1 . 1 / T2 -E X2

P 1 . 23

P 1 . 34

P 1 . 4 / S S5

P 1 . 5 / M O S I6

P 1 . 6 / M IS O7

P 1 . 7 / S C K8

P 2 .0 / A 82 1

P 2 .1 / A 92 2

P 2 . 2 / A 1 02 3

P 2 . 3 / A 1 12 4

P 2 . 4 / A 1 22 5

P 2 . 5 / A 1 32 6

P 2 . 6 / A 1 42 7

P 2 . 7 / A 1 52 8

P 3 . 0 / R XD1 0P 3 . 1 / TXD1 1

P 3 . 2 / I N T01 2

P 3 . 3 / I N T11 3

P 3 . 4 / T01 4

P 3 . 5 / T11 5

P 3 . 6 / W R1 6P 3 . 7 / R D1 7

P 0 . 0 / A D 03 9

P 0 . 1 / A D 13 8

P 0 . 2 / A D 23 7

P 0 . 3 / A D 33 6

P 0 . 4 / A D 43 5

P 0 . 5 / A D 53 4

P 0 . 6 / A D 63 3

P 0 . 7 / A D 73 2

C 1 63 3 p F

C 1 73 3 p F

Y 4

C R Y S TA L

12

3

4

V C CV C C

R 41 0 K

C 1 81 0 u F 1 6 V

V C C

C 1 91 0 4

C 2 01 0 U F / 1 6 V

C 2 11 0 U F / 1 6 V

V C C

V C C

C 2 21 0 U F / 1 6 V

C 2 31 0 4

C 2 4 1 0 U F / 1 6 V

U 6

M A X2 3 2

C 1 +1

C 1 -3

C 2 +4

C 2 -5

VC

C16

GN

D15

V +2

V -6

R 1 O U T1 2

R 2 O U T9

T1 I N1 1

T2 I N1 0

R 1 I N1 3

R 2 I N8

T1 O U T1 4

T2 O U T7

J 7

S E R I A L P O R T O F P C

123

C- code for serial transmission(from Microcontroller to PC)

#include<at89s8252.h>void Init_SPT(void);void transmit_serial(unsigned char a);void delay(unsigned int i);void main(void){ Init_SPT(); while(1)

12

Page 123: Embedded System

{ delay(0XFFFF); transmit_serial('N'); delay(0XFFFF); transmit_serial('E'); delay(0XFFFF); transmit_serial('T'); delay(0XFFFF); transmit_serial('M'); delay(0XFFFF); transmit_serial('A'); delay(0XFFFF); transmit_serial('X'); delay(0XFFFF);

}

}void Init_SPT(void){

TMOD=0x20;

TH1=0xfd;

TR1=1;

SCON=0x40;

}void transmit_serial(unsigned char a){ SBUF=a; delay(500); TI=0;

}void delay(unsigned int i)

12

Page 124: Embedded System

{while(i!=0) { i--;} }

b)Serial Reception(From PC to microcontroller)

J 3 L C D

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

VC

C

NETMAX

R 5 4

5 6 E

VC

C

R S E N

R SE N

SPT TXD

SPT RXD

U 1 1

A T8 9 S 8 2 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9

A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 . 0 / T21

P 1 . 1 / T2 -E X2

P 1 . 23

P 1 . 34

P 1 . 4 / S S5

P 1 . 5 / M O S I6

P 1 . 6 / M I S O7

P 1 . 7 / S C K8

P 2 . 0 / A 82 1

P 2 . 1 / A 92 2

P 2 . 2 / A 1 02 3

P 2 . 3 / A 1 12 4

P 2 . 4 / A 1 22 5

P 2 . 5 / A 1 32 6

P 2 . 6 / A 1 42 7

P 2 . 7 / A 1 52 8

P 3 . 0 / R XD1 0P 3 . 1 / TXD1 1

P 3 . 2 / I N T01 2

P 3 . 3 / I N T11 3

P 3 . 4 / T01 4

P 3 . 5 / T11 5

P 3 . 6 / W R1 6P 3 . 7 / R D1 7

P 0 . 0 / A D 03 9 P 0 . 1 / A D 13 8 P 0 . 2 / A D 23 7 P 0 . 3 / A D 33 6 P 0 . 4 / A D 43 5 P 0 . 5 / A D 53 4 P 0 . 6 / A D 63 3 P 0 . 7 / A D 73 2

C 3 43 3 p F

C 3 53 3 p F

Y 9

C R Y S TA L

12

3

4

V C CV C C

R 81 0 K

C 4 91 0 u F 1 6 V

V C C

C 5 01 0 4

C 5 11 0 U F / 1 6 V

V C C

C 5 21 0 U F / 1 6 V

V C C

C 5 31 0 U F / 1 6 V

C 5 41 0 4

C 5 5 1 0 U F / 1 6 V

U 1 2

M A X2 3 2

C 1 +1

C 1 -3

C 2 +4

C 2 -5

VC

C16

GN

D15

V +2

V -6

R 1 O U T1 2

R 2 O U T9

T1 I N1 1

T2 I N1 0

R 1 I N1 3

R 2 I N8

T1 O U T1 4

T2 O U T7

J 8

S E R I A L P O R T O F P C

123

C- code for serial reception:#include <at89s8252.h>#define LCDPRT P1#define RS P3_3

12

Page 125: Embedded System

#define EN P3_4

void Init_SPT(void); unsigned char receive_serial(void); void delay(unsigned int i); void lcd_cmd(unsigned char a); void display(unsigned char b); void wait(void); void Init_lcd(void); void clear_lcd(void); void cursor_position(unsigned char d); void disp_hex(unsigned char digit); void disp_dec(unsigned int digit); code unsigned char lkup_tbl01[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

void main(void){ unsigned char e; Init_lcd(); Init_SPT(); while(1) { e=receive_serial(); cursor_position(0x00); display(e);

}

} void Init_SPT(void){

PCON=PCON&0x7F;

12

Page 126: Embedded System

TMOD=TMOD&0x0F;

TMOD=TMOD|0x20;

TH1=0xfd; SCON=0X50; TR1=1;

} void delay (unsigned int i) { while (i!=0) { i--; } } void lcd_cmd(unsigned char a) { wait(); LCDPRT=a; RS=0; EN=1; EN=0; } void display(unsigned char b) { wait (); LCDPRT=b; RS=1; EN=1; EN=0; } void wait(void) { unsigned int count=300; while(count!=0) {

12

Page 127: Embedded System

count--; }

}

void Init_lcd(void) { lcd_cmd(0x3c); lcd_cmd(0x0C); lcd_cmd(0x06); lcd_cmd(0x14); lcd_cmd(0x1C); lcd_cmd(0x01);

} void cursor_position(unsigned char d) { lcd_cmd(d+0x80); }

6) Interfacing of 8255 PPI chip82C55A FUNCTIONAL DESCRIPTION

The 82C55A is a programmable peripheral interface device designed for use in

Intel microcomputer systems.

Its function is that of a general purpose I/O component to interface peripheral

equipment to the microcomputer system bus. The functional configuration of the

82C55A is programmed by the system software so that normally no external logic

is necessary to interface peripheral devices or structures

12

Page 128: Embedded System

Pin Diagram

Data Bus BufferThis 3-state bidirectional 8-bit buffer is used to interface the 82C55A to the system

data bus. Data is transmitted or received by the buffer upon execution of input or

output instructions by the CPU. Control words and status information are also

transferred through the data bus buffer.

Read/Write and Control LogicThe function of this block is to manage all of the internal and external transfers of

both Data and Control or Status words. It accepts inputs from the CPU Address

and Control busses and in turn, issues commands to both of the Control Groups.

Ports A, B, and CThe 82C55A contains three 8-bit ports (A, B, and C). All can be configured in a

wide variety of functional characteristics by the system software but each has its

Port A:

12

Page 129: Embedded System

One 8-bit data output latch/buffer and one 8-bit input latch buffer. Both “pull-up''

and “pull down'' buses hold devices are present on Port A.

Port B:

One 8-bit data input/output latch/buffer. Only “pull-up'' bus hold devices are

present on Port B.

Port C: One 8-bit data output latch/buffer and one 8-bit data input buffer (no latch for

input). This port can be divided into two 4-bit ports under the mode control. Each

4-bit port contains a 4-bit latch and it can be used for the control signal outputs and

status signal inputs in conjunction with ports A and B. Only ``pull-up'' bus hold

devices are present

12

Page 130: Embedded System

Hardware interfacing of 8255 PPI with At89s52

U 7

A T8 9 S 8 2 5 2

R S T9

XTA L 21 8 XTA L 11 9

GN

D20

P S E N2 9

A L E / P R O G3 0

EA

/VP

P31

VC

C40

P 1 . 0 /T21

P 1 . 1 /T2 -E X2

P 1 . 23

P 1 . 34

P 1 . 4 /S S5

P 1 . 5 /M O S I6

P 1 . 6 /M I S O7

P 1 . 7 /S C K8

P 2 . 0 /A 82 1

P 2 . 1 /A 92 2

P 2 . 2 /A 1 02 3

P 2 . 3 /A 1 12 4

P 2 . 4 /A 1 22 5

P 2 . 5 /A 1 32 6

P 2 . 6 /A 1 42 7

P 2 . 7 /A 1 52 8

P 3 . 0 /R XD1 0P 3 . 1 /TXD1 1

P 3 . 2 / I N T01 2

P 3 . 3 / I N T11 3

P 3 . 4 /T01 4

P 3 . 5 /T11 5

P 3 . 6 /W R1 6P 3 . 7 /R D1 7

P 0 . 0 /A D 03 9

P 0 . 1 /A D 13 8

P 0 . 2 /A D 23 7

P 0 . 3 /A D 33 6

P 0 . 4 /A D 43 5

P 0 . 5 /A D 53 4

P 0 . 6 /A D 63 3

P 0 . 7 /A D 73 2

U 8

8 2 5 5

D 03 4

D 13 3

D 23 2

D 33 1

D 43 0

D 52 9

D 62 8

D 72 7

P A 04

P A 13

P A 22

P A 31

P A 44 0

P A 53 9

P A 63 8

P A 73 7

P B 01 8

P B 11 9

P B 22 0

P B 32 1

P B 42 2

P B 52 3

P B 62 4

P B 72 5

P C 01 4

P C 11 5

P C 21 6

P C 31 7

P C 41 3

P C 51 2

P C 61 1

P C 71 0

V C C2 6

G N D7

R D5

W R3 6

A 09 A 18

R E S E T3 5

C S6

U 97 4 H C 5 7 3

D 02

D 13

D 24

D 35

D 46

D 57

D 68

D 79

L E1 1

O E1

Q 01 9

Q 11 8

Q 21 7

Q 31 6

Q 41 5

Q 51 4

Q 61 3

Q 71 2

G N D1 0V C C2 0

V C C

C 2 63 3 p F

C 2 73 3 p F

Y 5

C R Y S TA L

12

3

4

V C C V C C

R 2 31 0 K

C 2 8

1 0 u F 1 6 V

R S T

V C C

C 2 91 0 4

V C C

C code to access 8255 ports:

#include<at89s8252.h>

struct PPI

{

unsigned char PA;

unsigned char PB;

unsigned char PC;

unsigned char CW;

};

13

Page 131: Embedded System

xdata at 0x0000 struct PPI P8255;

void main(void)

{

P2_7=0;

P1_2=0;

P1_2=1;

P1_2=0;

P8255.CW=0X83;

P8255.PA=0Xff;

}

Hardware Interrupts Programming

#include<at89s8252.h>

void en_int(void);

void delay(unsigned int i);

void main (void)

{

P1=0x00;

INT0=0;

en_int();

}

void en_int(void)

{

EA=1;

EX0=1;

}13

Page 132: Embedded System

void isr_intr (void) interrupt 0

{

if(INT0==0)

{

while(1)

{

P1_0=1;

delay(0xffff);

P1_0=0;

delay(0xffff);

}

}

}

void delay(unsigned int i)

{

while(i!=0)

{

i--;

}

}

I2C bassed serial RTC(DS1307):

I2C:- How I2C works?

This I2C tutorial shows you how the I2C protocol works at the physical bit level. It only discusses single master mode (a single controlling device) as this is the most common use for I2C in a small system.

13

Page 133: Embedded System

I²C (pronounced I-squared-C) created by Philips Semiconductors and commonly written as 'I2C' stands for Inter-Integrated Circuit and allows communication of data between I2C devices over two wires. It sends information serially using one line for data (SDA) and one for clock (SCL).

I²C Bus Interfacing

I²C bus (Inter-Integrated Circuit) is a bidirectional, half duplex, two-wire, synchoronous bus, originally designed for interconnection over short distances within a piece of equipment. The I2C bus uses two lines called Serial Clock Line (SCL) and Serial Data Lines (SDA). Both lines are pulled high via a resistor (Rpu) as shown in Figure below. The bus is defined by Philips, see more details.

Three speed modes are specified: Standard; 100kbps [Bits per Second], Fast mode; 400kbps, High speed mode 3.4Mbps. I2C, due to its two-wire nature (one clock, one data) can only communicate half-duplex. The maximum bus capacitance is 400pF, which sets the maximum number of devices on the bus and the maximum line length.

The interface uses 8 bit long bytes, MSB (Most Significant Bit) first, with each device having a unique address. Any device may be a Transmitter or Receiver, and a Master or Slave. The Slave is any device addressed by the Master. A system may have more than one Master, although only one may me active at any time.

Data and clock are sent from the Master: valid while the clock line is high. The link may have multiple Masters and Slaves on the bus, but only one Master may be active at any one time. Slaves may receive or transmit data to the master.

This is an example how to interface I²C with 8051. I use SDCC as C Compiler. My schematic is shown below. I set P2.6 as SCL and P2.7 as SDA.

Schematic: I²C Bus

Note: You can find Master mode soft I2C routines in the RTC project.

13

Page 134: Embedded System

Master and slave

The phillips I2C protocol defines the concept of master and slave devices. A master device is simply the device that is in charge of the bus at the present time and this device controls the clock and generates START and STOP signals. Slaves simply listen to the bus and act on controls and data that they are sent.

The master can send data to a slave or receive data from a slave - slaves do not transfer data between themselves.

Multi Master

Multi master operation is a more complex use of I2C that lets you have different controlling devices on the same bus. You only need to use this mode if you have more than one microcontroller on the bus (and you want either of them to be the bus master).

Multi master operation involves arbitration of the bus (where a master has to fight to get control of the bus) and clock synchronisation (each may a use a different clock e.g. because of separate crystal clocks for each micro).

Note: Multi master is not covered in this I2C tutorial as the more common use of I2C is to use a single bus master to control peripheral devices e.g. serial memory, ADC, RTC etc.

Data and Clock

The I2C interface uses two bi-directional lines meaning that any device could drive either line. In a single master system the master device drives the clock most of the time - the master is in charge of the clock but slaves can influence it to slow it down (See Slow Peripherals below).

The two wires must be driven as open collector/drain outputs and must be pulled high using one resistor each - this implements a 'wired AND function' - any device pulling the wire low causes all devices to see a low logic value - for high logic value all devices must stop driving the wire.

Note : If you use I2C you can not put any other (non I2C) devices on the bus as both lines are used as clock at some point (generation of START and STOP bits toggles the data line). So you can not do something clever such as keeping the clock line inactive and use the data line as a button press detector (to save pins).

13

Page 135: Embedded System

You will often will find devices that you realise are I2C compatible but they are labelled as using a '2 wire interface'. The manufacturer is avoiding paying royalties by not using the words 'I2C'!

There are two wires (three if you include ground!) :

: Signals definition SDA : Serial DataSCL : Serial Clock

I2C Tutorial : Typical SDA and SCL signals

Speed

Standard clock speeds are 100kHz and 10kHz but the standard lets you use clock speeds from zero to 100kHz and a fast mode is also available (400kHz - Fast-mode). An even higher speed (3.4MHz - High-speed mode) for more demanding applications - The mid range PIC won't be up this mode yet!

Note that the low-speed mode has been omitted (10kHz) as the standard now specifies the basic system operating from 0 to 100kHz.

Slow peripherals

A slow slave device may need to stop the bus while it gathers data or services an interrupt etc. It can do this while holding the clock line (SCL) low forcing the master into the wait state. The master must then wait until SCL is released before proceeding.

Data transfer sequence

A basic Master to slave read or write sequence for I2C follows the following order:

13

Page 136: Embedded System

: I2C basic command sequence.

1. Send the START bit (S). 2. Send the slave address (ADDR). 3. Send the Read(R)-1 / Write(W)-0 bit. 4. Wait for/Send an acknowledge bit (A). 5. Send/Receive the data byte (8 bits) (DATA). 6. Expect/Send acknowledge bit (A). 7. Send the STOP bit (P).

Note: You can use 7 bit or 10 bit addresses.

The sequence 5 and 6 can be repeated so that a multibyte block can be read or written.

Data Transfer from master to slaveI2C Tutorial : Instruction sequence data from master to slave

A master device sends the sequence S ADDR W and then waits for an acknowledge bit (A) from the slave which the slave will only generate if its internal address matches the value sent by the master. If this happens then the master sends DATA and waits for acknowledge (A) from the slave. The master completes the byte transfer by generating a stop bit (P) (or repeated start).

Data transfer from slave to masterI2C Tutorial : Instruction sequence data from slave to master

A similar process happens when a master reads from the slave but in this case, instead of W, R is sent. After the data is transmitted from the slave to the master the master sends the acknowledge (A). If instead the master does not want any more data it must send a not-acknowledge which indicates to the slave that it should release the bus. This lets the master send the STOP or repeated START signal.

Device addresses

Each device you use on the I2C bus must have a unique address. For some devices e.g. serial memory you can set the lower address bits using input pins on the device others have a fixed internal address setting e.g. a real time clock DS1307. You can put several memory devices on the same IC bus by using a different address for each.

13

Page 137: Embedded System

Note: The maximum number of devices is limited by the number of available addresses and by the total bus capacitance (maximum 400pF).General callThe general call address is a reserved address which when output by the bus master should address all devices which should respond with an acknowledge.Its value is 0000000 (7 bits) and written by the master 0000000W. If a device does not need data from the general call it does not need to respond to it. : Reserved addresses.

0000 000 1 START byte - for slow micros without I2C h/w0000 001 X CBUS address - a different bus protocol0000 010 X Reserved for different bus format0000 011 X Reserved for future purposes0000 1XX X Hs-mode master code1111 1XX X Reserved for future purposes1111 0XX X 10-bit slave addressing

Most of these are not that useful for PIC microcontrollers except perhaps the START byte and 10 bit addressing.

START (S) and STOP (P) bits

START (S) and STOP (P) bits are unique signals that can be generated on the bus but only by a bus master.

Reception of a START bit by an I2C slave device resets its internal bus logic. This can be done at any time so you can force a restart if anything goes wrong even in the middle of communication.

START and STOP bits are defined as rising or falling edges on the data line while the clock line is kept high.I2C Tutorial : text definition of START and STOP signals

START condition (S) SCL = 1, SDA falling edgeSTOP condition (P) SCL = 1, SDA rising edge

The following diagram shows the above information graphically - these are the signals you would see on the I2C bus.

I2C Tutorial : START (S) and STOP (P) bits.

13

Page 138: Embedded System

Note : In a single master system the only difference between a slave and a master is the master's ability to generate START and STOP bits. Both slave and master can control SDA and SCL.

Repeated START (Sr)

This seems like a confusing term at first as you ask yourself why bother with it as it is functionally identical to the sequence :

S ADDR (R/W) DATA A P

The only difference is that for a repeated start you can repeat the sequence starting from the stop bit (replacing the stop bit with another start bit).

S ADDR (R/W) DATA A Sr ADDR (R/W) DATA A P

and you can do this indefinitely.

Note: Reception of both S or Sr force any I2C device reset its internal bus logic so sending S or Sr is really resetting all the bus devices. This can be done at any time - it is a forced reset.

The main reason that the Sr bit exists is in a multi master configuration where the current bus master does not want to release its mastership. Using the repeated start keeps the bus busy so that no other master can grab the bus.

Because of this when used in a Single master configuration it is just a curiosity.

Data

All data blocks are composed of 8 bits. The initial block has 7 address bits followed by a direction bit (Read or Write). Following blocks have 8 data bits. Acknowledge bits are squeezed in between each block.

Each data byte is transmitted MSB first including the address byte.

To allow START and STOP bit generation by the master the data line (SDA) must not be changed while the clock (SCL) is high - it can only be changed when the clock is low.

13

Page 139: Embedded System

Acknowledge

The acknowledge bit (generated by the receiving device) indicates to the transmitter that the the data transfer was ok. Note that the clock pulse for the acknowledge bit is always created by the bus master.

The acknowledge data bit is generated by either the master or slave depending on the data direction. For the master writing to a slave (W) the acknowledge is generated by the slave. For the master receiving (R) data from a slave the master generates the acknowledge bit.I2C Tutorial : Definition of ACK bits

Acknowledge 0 voltsNot acknowledge High volts

ACK data master --> slaveIn this case the slave generates the acknowledge signal.

When a not-acknowledge is received by the bus master the transfer has failed and the master must generate a STOP or repeated START to abort the sequence.ACK data slave --> masterIn this case the master generates the acknowledge signal.

Normally the master will generate an acknowledge after it has received data but to indicate to the slave that no more data is required on the last byte transfer the master must generate a 'not-acknowledge'. This indicates to the slave that it should stop sending data. The master can then generate the STOP bit (or repeated START).

I2C Tutorial : Specifics for the 16F88Pin configurationTo use the I2C mode in the 16F88 the SDA and SCL pins must be initialised as inputs (TRIS bit = 1) so that an open drain effect is created. By setting them as inputs they are not driving the wires and an external pull up resistor will pull the signals high.

Slave modeThe 16F88 fully implements all slave functions except general call.

The general call function does not really matter as it is quite specialised commanding all devices on the bus to use some data.

A low output is generated by driving the signal line low and changing the pin direction to an output. A high output is generated by changing the pin direction to an input so that the external resistor pulls the signal high.In slave mode this action is done for you by the SSP module (the outputs of the register at SDA and SCL

are driven low automatically - regardless of the state of the register value).

13

Page 140: Embedded System

Hardware connection of I2C RTC and EEPROM

C- code for I2C RTC:

#include <AT89s8252.h>

#define RS P3_3

#define EN P3_4

#define LCD P1

//lcd configured

//i2c settings

#define SCL P3_614

Page 141: Embedded System

#define SDA P3_7

#define I2C_DELAY 0x0F

#define DS1307_ID 0xD0

#define SEC 0x00

#define MIN 0x01

#define HOUR 0x02

#define DATE 0x04

#define MONTH 0x05

#define YEAR 0x06

// I2c function

void I2C_delay(void);

void I2C_clock(void);

void I2C_start(void);

void I2C_stop(void);

// DS1307 funvtion

unsigned char DS1307_get(unsigned char addr);

void DS1307_settime(unsigned char hh , unsigned char mm, unsigned char ss);

void DS1307_setdate(unsigned char dd, unsigned char mm, unsigned char yy);

unsigned char I2C_read(void);

void I2C_write(unsigned char dat);

// lcd function

void lcd_cmd(unsigned char a);14

Page 142: Embedded System

void display(unsigned char b);

void wait(void);

void Init_lcd(void);

void cursor_position(unsigned char c);

void send2lcd(unsigned char value);

void hour_display(unsigned char value);

void display_string(unsigned char *sp);

void delay(unsigned int i);

// Strings

code unsigned char name1[]={"date$"};

code unsigned char name2[]={"time$"};

code unsigned char am[]={"AM$"};

code unsigned char pm[]={"PM$"};

/***************************** Main function *************************************/

void main(void)

{

unsigned char sec, min, hour, date, month, year;

Init_lcd();

cursor_position(0x00);

display_string(&name1);

cursor_position(0x40); 14

Page 143: Embedded System

display_string(&name2);

DS1307_settime(0x20,0x59,0x55); /* Set Time (hh:mm:ss) */

DS1307_setdate(0x26,0x03,0x08); /* Set Date (dd/mm/yy) */

while(1)

{

//hr(0x40);

/* Get Date & Time */

sec = DS1307_get(SEC);

min = DS1307_get(MIN);

hour = DS1307_get(HOUR);

date = DS1307_get(DATE);

month = DS1307_get(MONTH);

year = DS1307_get(YEAR);

/* Show Date in format dd/mm/yr */

cursor_position(0x06); /* Set LCD cursor at (1,6) */

send2lcd(date); /* Show date on LCD */

display('/');

send2lcd(month); /* Show month on LCD */14

Page 144: Embedded System

display('/');

send2lcd(year); /* Show year on LCD */

/* Show Time in format hr:min:sec */

cursor_position(0x45); /* Set LCD cursor at (2,6) */

hour_display(hour); /* Show hour on LCD */

//send2lcd(hour);

cursor_position(0x47);

display(':');

cursor_position(0x48);

send2lcd(min); /* Show min on LCD */

cursor_position(0x4a);

display(':');

cursor_position(0x4b);

send2lcd(sec); /* Show sec on LCD */

if(hour<=0x11)14

Page 145: Embedded System

{

cursor_position(0x4e);

display_string(&am);

}

if(hour>0x11)

{

cursor_position(0x4e);

display_string(&pm);

}

}

}

//i2c Function

void I2C_delay(void)

{

unsigned char i;

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

}

void I2C_clock(void)

{14

Page 146: Embedded System

I2C_delay();

SCL = 1; /* Start clock */

I2C_delay();

SCL = 0; /* Clear SCL */

}

void I2C_start(void)

{

SDA = 1; /* Set SDA */

SCL = 1; /* Set SCL */

SDA = 0; /* Clear SDA */

I2C_delay();

SCL = 0; /* Clear SCL */

}

void I2C_stop(void)

{

SCL = 0; /* Clear SCL */

SDA = 0; /* Clear SDA */

SCL = 1; /* Set SCL */

I2C_delay();

SDA = 1; /* Set SDA */

}

14

Page 147: Embedded System

void I2C_write(unsigned char dat)

{

unsigned char i;

bit data_bit;

for(i=0;i<8;i++) // For loop 8 time(send data 1 byte)

{

data_bit = dat & 0x80; // Filter MSB bit keep to data_bit

SDA = data_bit; // Send data_bit to SDA

I2C_clock(); // Call for send data to i2c bus

dat = dat<<1;

}

I2C_clock();

}

unsigned char I2C_read(void)

{

bit rd_bit;

unsigned char i, dat;

dat = 0x00;

for(i=0;i<8;i++) //For loop read data 1 byte

{

14

Page 148: Embedded System

SCL = 1;

rd_bit = SDA;

dat = dat<<1;

dat = dat | rd_bit; //Keep bit data in dat

SCL = 0;

}

return dat;

}

// DS1307 RTC Function

unsigned char DS1307_get(unsigned char addr)

{

unsigned char ret;

I2C_start(); /* Start i2c bus */

I2C_write(DS1307_ID); /* Connect to DS1307 */

I2C_write(addr); /* Request RAM address on DS1307 */

I2C_start(); /* Start i2c bus */

I2C_write(DS1307_ID+1); /* Connect to DS1307 for Read */

ret = I2C_read(); /* Receive data */14

Page 149: Embedded System

I2C_stop(); /* Stop i2c bus */

return ret;

}

void DS1307_settime(unsigned char hh, unsigned char mm, unsigned char ss)

{

I2C_start();

I2C_write(DS1307_ID); // connect to DS1307

I2C_write(0x00); //Request RAM address at 00H

I2C_write(ss); // Write sec on RAM address 00H

I2C_write(mm); // Write min on RAM address 01H

I2C_write(hh); // Write hour on RAM address 02H

I2C_stop();

}

void DS1307_setdate(unsigned char dd, unsigned char mm, unsigned char yy)

{

I2C_start();

I2C_write(DS1307_ID); // connect to DS1307

I2C_write(0x04); /* Request RAM address at 04H */

I2C_write(dd); /* Write date on RAM address 04H */14

Page 150: Embedded System

I2C_write(mm); /* Write month on RAM address 05H */

I2C_write(yy); /* Write year on RAM address 06H */

I2C_stop(); /* Stop i2c bus */

}

// LCD Function

void delay (unsigned int i)

{

while (i!=0)

{

i--;

}

}

void Init_lcd(void)

{

lcd_cmd(0x01);

lcd_cmd(0x0c);15

Page 151: Embedded System

lcd_cmd(0x38);

}

void lcd_cmd(unsigned char a)

{

delay(300);

LCD=a;

RS=0;

EN=1;

EN=0;

}

void display(unsigned char b)

{

delay(300);

LCD=b;

RS=1;

EN=1;

EN=0;

}

void cursor_position(unsigned char c)

{

lcd_cmd(c+0x80);

}

void display_string(unsigned char *sp)

15

Page 152: Embedded System

{

while(*sp!='$')

{

display(*sp);

sp=sp+1;

}

}

void send2lcd(unsigned char val )

{

unsigned char x;

unsigned char y;

x=val&0x0f;

x=x|0x30;

y=val&0xf0;

y=y>>4;

y=y|0x30;

display(y);

display(x);

}

15

Page 153: Embedded System

void hour_display(unsigned char value)

{

unsigned char buf = 0;

unsigned char x = 0;

unsigned char y = 0;

cursor_position(0x45);

if(value < 0x13)

{

buf = value & 0xF0; /* Filter for high byte */

buf = (buf>>4)|(0x30); /* Convert to ascii code */

display(buf); /* Show on LCD */

buf = value & 0x0F; /* Filter for low byte */

buf = buf | 0x30; /* Convert to ascii code */

display(buf); /* Show on LCD */

}

if(value ==0x13 ||value ==0x14||value ==0x15||value ==0x16||value ==0x17||

value ==0x18||value ==0x19||value ==0x22||value ==0x23)

15

Page 154: Embedded System

{

buf=value-0x12;

x=buf&0xf0;

x=x>>4;

x=x|0x30;

display(x);

y=buf&0x0f;

y=y|0x30;

display(y);

}

if(value==0x20)

{

buf=value-0x12;

x=buf&0xf0;

x=x>>4;

x=x|0x30;

display(x);

display('8');

}

if(value==0x21)15

Page 155: Embedded System

{

buf=value-0x12;

x=buf&0xf0;

x=x>>4;

x=x|0x30;

display(x);

display('9');

}

}

C-code To Test I2C EEPROM

#include <AT89s8252.h.h>

#define EN P3_4

#define RS P3_3

#define LCD P1

#define SDA P3_7 /* Set P2.7 = SDA */

#define SCL P3_6 /* Set P2.6 = SCL */

#define I2C_DELAY 0x0F /* For delay i2c bus */15

Page 156: Embedded System

#define EEPROMS_ID 0xA0 /* Microchip 24xx512 */

/***************************************************

* Prototype(s) *

***************************************************/

void I2C_delay(void);

void init();

void I2C_clock(void);

void I2C_start(void);

void I2C_write(unsigned char dat);

void I2C_stop(void);

unsigned char I2C_read(void);

void I2C_ack();

void I2C_noack();

unsigned char EEPROM_get(unsigned int addr);

void EEPROM_set(unsigned int addr, unsigned char val);

void delay(unsigned int i);

void lcd_cmd(unsigned char a);

void display(unsigned char b);

void wait(void);

void string (unsigned char *p);

void disp_dec(unsigned long int digit);

void Init_lcd(void);

code unsigned char lkup_tbl01[16]={'0','1','2','3','4','5','6','7','8','9'};

void cursor_position(unsigned char c);15

Page 157: Embedded System

unsigned char st1[]={ "Test EEPROM 24xx$"};

unsigned char st2[]={ "Waiting...RESULT$"};

unsigned char st3[]={ "SUCCEESS TEST $"};

unsigned char st4[]={ "FAIL! TEST $"};

void main(void)

{

unsigned char dat;

Init_lcd();

cursor_position(0x00);

string(&st1);

delay(0xffff);

delay(0xffff);

cursor_position(0x00);

string(&st2);

delay(0xffff);

delay(0xffff);

delay(0xffff);

EEPROM_set(15,38);

//EEPROM_set(0x0404,27); /* Write EEPROM at address 0x0000 */

delay(1000); /* Delay for 50 ms */

dat = EEPROM_get(15); /* Read data at address 0x0000 */

15

Page 158: Embedded System

if (dat==38)

{

cursor_position(0x00);

string(&st3);

}

else

{ cursor_position(0x00);

string(&st4);

}

lcd_cmd(0xCA);

disp_dec(dat);

}

void string (unsigned char *p)

{

while(*p!='$')

{

display(*p);

p++;15

Page 159: Embedded System

}

}

void EEPROM_set(unsigned int addr, unsigned char val)

{

I2C_start();

I2C_write(EEPROMS_ID); /* Connect to EEPROM */

I2C_write(addr&0xF0); /* Request RAM address (Hight byte) */

I2C_write(addr&0x0F); /* Request RAM address (Low byte) */

I2C_write(val); /* Write sec on RAM specified address */

I2C_stop(); /* Stop i2c bus */

}

unsigned char EEPROM_get(unsigned int addr)

{

unsigned char dat;

I2C_start(); /* Start i2c bus */

I2C_write(EEPROMS_ID); /* Connect to EEPROM */

I2C_write(addr&0xF0); /* Request RAM address (Hight byte) */

I2C_write(addr&0x0F); /* Request RAM address (Low byte) */

I2C_start(); /* Start i2c bus */

15

Page 160: Embedded System

I2C_write(EEPROMS_ID+1);/* Connect to EEPROM for Read */

dat = I2C_read(); /* Receive data */

I2C_stop(); /* Stop i2c bus */

return dat;

}

/***************************** i2c function *************************************/

void I2C_delay(void)

{

unsigned char i;

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

}

void I2C_clock(void)

{

I2C_delay();

16

Page 161: Embedded System

SCL = 1; /* Start clock */

I2C_delay();

SCL = 0; /* Clear SCL */

}

void I2C_start(void)

{

/* Clear SCL */

SDA = 1; /* Set SDA */

SCL = 1; /* Set SCL */

SDA = 0; /* Clear SDA */

I2C_delay();

SCL = 0; /* Clear SCL */

}

void I2C_stop(void)

{

16

Page 162: Embedded System

SCL = 0; /* Clear SCL */

SDA = 0; /* Clear SDA */

SCL = 1; /* Set SCL */

I2C_delay();

SDA = 1; /* Set SDA */

}

void I2C_write(unsigned char dat)

{

bit data_bit;

unsigned char i;

for(i=0;i<8;i++) /* For loop 8 time(send data 1 byte) */

{

data_bit = dat & 0x80; /* Filter MSB bit keep to data_bit */

SDA = data_bit; /* Send data_bit to SDA */

I2C_clock(); /* Call for send data to i2c bus */

dat = dat<<1;

}

16

Page 163: Embedded System

I2C_clock();

}

unsigned char I2C_read(void)

{

bit rd_bit;

unsigned char i, dat;

dat = 0x00;

for(i=0;i<8;i++) /* For loop read data 1 byte */

{

rd_bit = SDA; /* Keep for check acknowledge */

dat = dat<<1;

dat = dat | rd_bit; /* Keep bit data in dat */

I2C_clock(); /* Clear SCL */

}

return dat;

}

16

Page 164: Embedded System

void lcd_cmd(unsigned char a)

{

wait();

LCD=a;

RS=0;

EN=1;

EN=0;

}

void display(unsigned char b)

{

wait ();

LCD=b;

RS=1;

EN=1;

EN=0;

}

void wait(void)

{

unsigned int count=300;

while(count!=0)

{

count--;

}

}

16

Page 165: Embedded System

void Init_lcd(void)

{

lcd_cmd(0x3c);

lcd_cmd(0x0c);

lcd_cmd(0x06);

lcd_cmd(0x01);

}

void cursor_position(unsigned char c)

{

lcd_cmd(c+0x80);

}

void delay(unsigned int i)

{

while(i!=0)

{

i--;

}

}

void disp_dec(unsigned long int digit)

{

unsigned long int temp;16

Page 166: Embedded System

if(digit<10)

{

temp=digit;

display(lkup_tbl01[temp]);

}

if(digit>9 && digit<100)

{

temp=digit/10;

display(lkup_tbl01[temp]);

digit=digit-(temp*10);

temp=digit;

display(lkup_tbl01[temp]);

}

if(digit>99 && digit<1000)

{

temp=digit/100;

display(lkup_tbl01[temp]);

digit=digit-(temp*100);

temp=digit/10;

display(lkup_tbl01[temp]);

digit=digit-(temp*10);16

Page 167: Embedded System

temp=digit;

display(lkup_tbl01[temp]);

}

if(digit>999 && digit<10000)

{

temp=digit/1000;

display(lkup_tbl01[temp]);

digit=digit-(temp*1000);

temp=digit/100;

display(lkup_tbl01[temp]);

digit=digit-(temp*100);

temp=digit/10;

display(lkup_tbl01[temp]);

digit=digit-(temp*10);

temp=digit;

display(lkup_tbl01[temp]);

}

}

16

Page 168: Embedded System

AVR

Why the Atmel’s AVR Microcontroller?

Whether a particular requirement needs to be implemented using discrete ICs or PLDs or a microprocessor must be determined by the designer.However, many applications could be suitably implemented using microcontrollers, and a great many of them would benefit from using the AVR as outlined briefly below. We will discuss the AVR features in detail in later chapters, but at this point it may be useful to outline the salient features:

1) RISC architecture with mostly fixed length instructions,load-store memory access and 32 general-purpose registers.

2) A two-stage instructions pipeline that speeds upm execution.3) Majority of instructions take one clock cycle.4) Up to 10-Mhz clock operation.5) Wide variety of on-chip peripherals, including digital I/O,

ADC ,EEPROM,Timer,UART,RTC timer,pulse width modulator(PWM),etc.6) Internal program and data memory.7) In- system programmable.8) Available in 8-pin to 64-pin package size to suit wide variety of applications.9) Up to 12 times performance speedup over conventional CISC controllers.10) Wide operating voltage from 2.7 volt to 6 volt.11) A simple architecture offers a small learning curve to the uninitiated.

ATmega8515

Features of ATmega 8515• High-performance, Low-power AVR® 8-bit Microcontroller• RISC Architecture– 130 Powerful Instructions – Most Single Clock Cycle Execution– 32 x 8 General Purpose Working Registers– Fully Static Operation• Nonvolatile Program and Data Memories– 8K Bytes of In-System Self-programmable Flash

16

Page 169: Embedded System

Endurance: 10,000 Write/Erase Cycles– Optional Boot Code Section with Independent Lock bitsIn-System Programming by On-chip Boot ProgramTrue Read-While-Write Operation– 512 Bytes EEPROMEndurance: 100,000 Write/Erase Cycles– 512 Bytes Internal SRAM– Up to 64K Bytes Optional External Memory Space– Programming Lock for Software Security• Peripheral Features– One 8-bit Timer/Counter with Separate Prescaler and Compare Mode– One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and CaptureMode– Three PWM Channels– Programmable Serial USART– Master/Slave SPI Serial Interface– Programmable Watchdog Timer with Separate On-chip Oscillator– On-chip Analog Comparator• Special Microcontroller Features– Power-on Reset and Programmable Brown-out Detection– Internal Calibrated RC Oscillator– External and Internal Interrupt Sources– Three Sleep Modes: Idle, Power-down and Standby• I/O and Packages– 35 Programmable I/O Lines– 40-pin PDIP, 44-lead TQFP, 44-lead PLCC, and 44-pad QFN/MLF• Operating Voltages– 2.7 - 5.5V for ATmega8515L– 4.5 - 5.5V for ATmega8515• Speed Grades– 0 - 8 MHz for ATmega8515L– 0 - 16 MHz for ATmega8515

16

Page 170: Embedded System

Pin DescriptionsVCC- pin 40Digital supply voltage.GND – pin 20 RESET- pin 9 Reset input. A low level on this pin for longer than the minimum pulse length will generatea reset, even if the clock is not running. The minimum pulse length is given in Table18 on page 45. Shorter pulses are not guaranteed to generate a reset.XTAL1-pin 19 Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.XTAL2- pin 20 Output from the inverting Oscillator amplifier.

17

Page 171: Embedded System

Port A (PA7(32)..PA0(39) ) Port A is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port A output buffers have symmetrical drive characteristics with both high sinkand source capability. When pins PA0 to PA7 are used as inputs and are externallypulled low, they will source current if the internal pull-up resistors are activated. The PortA pins are tri-stated when a reset condition becomes active, even if the clock is notrunning.Port A also serves the functions of various special features of the ATmega8515 as listedBelow:Alternate Functions of Port A Port A has an alternate function as the address low byte and data lines for the ExternalMemory Interface.Port Pin Alternate FunctionPA7 AD7 (External memory interface address and data bit 7)PA6 AD6 (External memory interface address and data bit 6)PA5 AD5 (External memory interface address and data bit 5)PA4 AD4 (External memory interface address and data bit 4)PA3 AD3 (External memory interface address and data bit 3)PA2 AD2 (External memory interface address and data bit 2)PA1 AD1 (External memory interface address and data bit 1)PA0 AD0 (External memory interface address and data bit 0)

Port B (PB7(8)..PB0(1)) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port B output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port B pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port B pins are tri-stated when a resetcondition becomes active, even if the clock is not running.Port B also serves the functions of various special features of the ATmega8515 as listedBelow:Port B Pin Alternate FunctionsPB7- SCK (SPI Bus Serial Clock)PB6- MISO (SPI Bus Master Input/Slave Output)PB5 -MOSI (SPI Bus Master Output/Slave Input)

17

Page 172: Embedded System

PB4- SS (SPI Slave Select Input)PB3- AIN1 (Analog Comparator Negative Input)PB2- AIN0 (Analog Comparator Positive Input)PB1 -T1 (Timer/Counter1 External Counter Input)PB0T0- (Timer/Counter0 External Counter Input) OC0 (Timer/Counter0 Output Compare Match Output)

• SCK – Port B, Bit 7SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI isenabled as a Slave, this pin is configured as an input regardless of the setting of DDB7.When the SPI is enabled as a Master, the data direction of this pin is controlled byDDB7. When the pin is forced by the SPI to be an input, the pull-up can still be controlledby the PORTB7 bit.• MISO – Port B, Bit 6MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI isenabled as a Master, this pin is configured as an input regardless of the setting ofDDB6. When the SPI is enabled as a Slave, the data direction of this pin is controlled byDDB6. When the pin is forced by the SPI to be an input, the pull-up can still be controlledby the PORTB6 bit.

• MOSI – Port B, Bit 5MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI isenabled as a Slave, this pin is configured as an input regardless of the setting of DDB5.When the SPI is enabled as a Master, the data direction of this pin is controlled byDDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlledby the PORTB5 bit.• SS – Port B, Bit 4SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as aninput regardless of the setting of DDB4. As a Slave, the SPI is activated when this pin isdriven low. When the SPI is enabled as a Master, the data direction of this pin is controlledby DDB4. When the pin is forced by the SPI to be an input, the pull-up can still be

17

Page 173: Embedded System

controlled by the PORTB4 bit.• AIN1 – Port B, Bit 3AIN1, Analog Comparator Negative input. Configure the port pin as input with the internalpull-up switched off to avoid the digital port function from interfering with the functionof the Analog Comparator.• AIN0 – Port B, Bit 2AIN0, Analog Comparator Positive input. Configure the port pin as input with the internalpull-up switched off to avoid the digital port function from interfering with the function ofthe Analog Comparator.• T1 – Port B, Bit 1T1, Timer/Counter1 Counter Source.• T0/OC0 – Port B, Bit 0T0, Timer/Counter0 Counter Source.OC0, Output Compare Match output: The PB0 pin can serve as an external output forthe Timer/Counter0 Compare Match. The PB0 pin has to be configured as an output(DDB0 set (one)) to serve this function. The OC0 pin is also the output pin for the PWMmode timer function.

Port C (PC7(28)..PC0(21)) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port C pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port C pins are tri-stated when a resetcondition becomes active, even if the clock is not running.Port D (PD7(17)..PD0(10)) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port D output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port D pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port D pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

17

Page 174: Embedded System

Port D also serves the functions of various special features of the ATmega8515 as listedBelow:Port D Pin Alternate FunctionPD7- RD (Read Strobe to External Memory)PD6 -WR (Write Strobe to External Memory)PD5 -OC1A (Timer/Counter1 Output Compare A Match Output)PD4 -XCK (USART External Clock Input/Output)PD3- INT1 (External Interrupt 1 Input)PD2- INT0 (External Interrupt 0 Input)PD1 -TXD (USART Output Pin)PD0 -RXD (USART Input Pin)

• RD – Port D, Bit 7RD is the External Data memory read control strobe.• WR – Port D, Bit 6WR is the External Data memory write control strobe.• OC1A – Port D, Bit 5OC1A, Output Compare Match A output: The PD5 pin can serve as an external outputfor the Timer/Counter1 Output Compare A. The pin has to be configured as an output(DDD5 set (one)) to serve this function. The OC1A pin is also the output pin for thePWM mode timer function.• XCK – Port D, Bit 4XCK, USART External Clock. The Data Direction Register (DDD4) controls whether theclock is output (DDD4 set) or input (DDD4 cleared). The XCK pin is active only whenUSART operates in Synchronous mode.

• INT1 – Port D, Bit 3INT1, External Interrupt source 1: The PD3 pin can serve as an external interruptsource.• INT0/XCK1 – Port D, Bit 2INT0, External Interrupt Source 0: The PD2 pin can serve as an external interruptsource.XCK1, External Clock. The Data Direction Register (DDD2) controls whether the clock isoutput (DDD2 set) or input (DDD2 cleared).

17

Page 175: Embedded System

• TXD – Port D, Bit 1TXD, Transmit Data (Data output pin for USART). When the USART Transmitter isenabled, this pin is configured as an output regardless of the value of DDD1.• RXD – Port D, Bit 0RXD, Receive Data (Data input pin for USART). When the USART Receiver is enabledthis pin is configured as an input regardless of the value of DDD0. When USART forcesthis pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

Port E(PE2(29)..PE0(31)) Port E is an 3-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port E output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port E pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port E pins are tri-stated when a resetcondition becomes active, even if the clock is not running.Port E also serves the functions of various special features of the ATmega8515 as listedBelow:Port E Pin Alternate FunctionPE2-OC1B (Timer/Counter1 Output Compare B Match Output)PE1 -ALE (Address Latch Enable to External Memory)PE0-ICP (Timer/Counter1 Input Capture Pin) INT2 (External Interrupt 2 Input)

Input-output Ports registers:

All AVR ports have Read-modify-write functionality when used as genera I/O ports. Direction of separate port pin can be changed. Each pin buffer has symmetric capability to drive and sink source. Pin driver is strong enough to drive LED directly , but it is not recommended. All port pins have selectable pull-up resistors. All pins have protection diodes to both VCC and GND.

Each port consists of three registers DDRx, PORTx and PINx (where x means port letter). DDRx register selects direction of port pins. If logic one is written to DDRx then port is configured to be as output. Zero means that port is configured as input. If DDRx is written zero and PORTx is written logic “1” then port is configured as input with internal pull-up resistor. Otherwise if PORTx is written to zero, then port is configured as input but pins are set to tri-state and you might need to connect

17

Page 176: Embedded System

external pull-up resistors.

On chip peripheral description:

a) 8-bit Timer/Counter0 with PWMTimer/Counter0 is a general purpose, single channel, 8-bit Timer/Counter module. Themain features are:• Single Channel Counter• Clear Timer on Compare Match (Auto Reload)• Glitch-free, Phase Correct Pulse Width Modulator (PWM)• Frequency Generator• External Event Counter• 10-bit Clock Prescaler• Overflow and Compare Match Interrupt Sources (TOV0 and OCF0)

8-bit Timer/Counter Register Description

1)Timer/Counter Control Register – TCCR0 17

Page 177: Embedded System

7 6 5 4 3 2 1 0 FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00

• Bit 7 – FOC0: Force Output CompareThe FOC0 bit is only active when the WGM00 bit specifies a non-PWM mode. However,for ensuring compatibility with future devices, this bit must be set to zero when TCCR0 iswritten when operating in PWM mode. When writing a logical one to the FOC0 bit, animmediate Compare Match is forced on the waveform generation unit. The OC0 outputis changed according to its COM01:0 bits setting. Note that the FOC0 bit is implementedas a strobe. Therefore it is the value present in the COM01:0 bits that determines theeffect of the forced compare.A FOC0 strobe will not generate any interrupt, nor will it clear the timer in CTC modeusing OCR0 as TOP.The FOC0 bit is always read as zero.• Bit 6, 3 – WGM01:0: Waveform Generation ModeThese bits control the counting sequence of the counter, the source for the maximum(TOP) counter value, and what type of waveform generation to be used. Modes of operationsupported by the Timer/Counter unit are: Normal mode, Clear Timer on CompareMatch (CTC) mode, and two types of Pulse Width Modulation (PWM) modes.

Table 44. Waveform Generation Mode Bit Description(1)Mode WGM01 WGM00 Timer/Counter Mode of Operation TOP of counter

17

Page 178: Embedded System

0 0 0 Normal 0xFF Immediate MAX1 0 1 PWM, Phase Correct 0xFF TOP BOTTOM2 1 0 CTC OCR0 Immediate MAX3 1 1 Fast PWM 0xFF TOP MAX

Normal Mode The simplest mode of operation is the Normal mode (WGM01:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. TheTOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared.However, combined with the timer overflow interrupt that automatically clears the TOV0Flag, the timer resolution can be increased by software. There are no special cases toconsider in the Normal mode, a new counter value can be written anytime.The output compare unit can be used to generate interrupts at some given time. Usingthe output compare to generate waveforms in Normal mode is not recommended, sincethis will occupy too much of the CPU time.Clear Timer on CompareMatch (CTC) ModeIn Clear Timer on Compare or CTC mode (WGM01:0 = 2), the OCR0 Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT0) matches the OCR0. The OCR0 defines the top value for the counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events.For generating a waveform output in CTC mode, the OC0 output can be set to toggle its logical level on each Compare Match by setting the Compare Output mode bits to toggle mode (COM01:0 = 1). The OC0 value will not be visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0 is set to zero (0x00). The waveform frequency is

17

Page 179: Embedded System

defined by the following equation:

focn= fclk_i/o 2.N.(1+ocrn)The “N” variable represents the prescale factor (1, 8, 64, 256, or 1024).As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cyclethat the counter counts from MAX to 0x00.

Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM01:0 = 3) provides a highfrequency PWM waveform generation option. The fast PWM differs from the other PWMoption by its single-slope operation. The counter counts from BOTTOM to MAX thenrestarts from BOTTOM. In non-inverting Compare Output mode, the Output Compare(OC0) is cleared on the Compare Match between TCNT0 and OCR0, and set atBOTTOM. In inverting Compare Output mode, the output is set on Compare Match andcleared at BOTTOM. Due to the single-slope operation, the operating frequency of thefast PWM mode can be twice as high as the phase correct PWM mode that use dualslopeoperation. This high frequency makes the fast PWM mode well suited for powerregulation, rectification, and DAC applications. High frequency allows physically smallsized external components (coils, capacitors), and therefore reduces total system cost.In fast PWM mode, the counter is incremented until the counter value matches the MAXvalue. The counter is then cleared at the following timer clock cycle. The timing diagramfor the fast PWM mode is shown in Figure 39. The TCNT0 value is in the timing diagramshown as a histogram for illustrating the single-slope operation. The diagram includesnon-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0

17

Page 180: Embedded System

slopes represent Compare Matches between OCR0 and TCNT0.

The PWM frequency for the output can be calculated by the following equation: fOCnPWM=fclk_i/o N.256 The “N” variable represents the prescale factor (1, 8, 64, 256, or 1024).

Phase Correct PWM Mode The phase correct PWM mode (WGM01:0 = 1) provides a high resolution phase correctPWM waveform generation option. The phase correct PWM mode is based on a dualslopeoperation. The counter counts repeatedly from BOTTOM to MAX and then fromMAX to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC0)is cleared on the Compare Match between TCNT0 and OCR0 while upcounting, and seton the Compare Match while downcounting. In inverting Output Compare mode, theoperation is inverted. The dual-slope operation has lower maximum operation frequencythan single slope operation. However, due to the symmetric feature of the dual-slopePWM modes, these modes are preferred for motor control applications. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation:

fOCnPCPWM= fclk_i/0 N.510 Bit 5:4 – COM01:0: Compare Match Output ModeThese bits control the Output Compare pin (OC0) behavior. If one or both of theCOM01:0 bits are set, the OC0 output overrides the normal port functionality of the I/Opin it is connected to. However, note that the Data Direction Register (DDR) bit correspondingto the OC0 pin must be set in order to enable the output driver.When OC0 is connected to the pin, the function of the COM01:0 bits depends on theWGM01:0 bit setting. a)Compare Output Mode, non-PWM Mode

18

Page 181: Embedded System

COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Toggle OC0 on Compare Match. 1 0 Clear OC0 on Compare Match. 1 1 Set OC0 on Compare Match.

b) Compare Output Mode, Fast PWM Mode

COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Reserved 1 0 Clear OC0 on Compare Match, set OC0 at TOP. 1 1 Set OC0 on Compare Match, clear OC0 at TOP.

c) Compare Output Mode, Phase Correct PWM Mode

COM01 COM00 Description 0 0 Normal port operation, OC0 disconnected. 0 1 Reserved 1 0 Clear OC0 on Compare Match when up-counting. Set OC0 on Compare Match when downcounting 1 1 Set OC0 on Compare Match when up-counting. Clear OC0 on Compare Match when downcounting.

• Bit 2:0 – CS02:0: Clock Select

The three Clock Select bits select the clock source to be used by the Timer/Counter.CS02 CS01 CS00 Description0 0 0 No clock source (Timer/counter stopped).

18

Page 182: Embedded System

0 0 1 clkI/O/(No prescaling)0 1 0 clkI/O/8 (From prescaler)0 1 1 clkI/O/64 (From prescaler)1 0 0 clkI/O/256 (From prescaler)1 0 1 clkI/O/1024 (From prescaler)1 1 0 External clock source on T0 pin. Clock on falling . edge 1 1 1 External clock source on T0 pin. Clock on rising edge.

16-bit Timer/Counter1The 16-bit Timer/Counter unit allows accurate program execution timing (event management),wave generation, and signal timing measurement. The main features are:• True 16-bit Design (i.e., allows 16-bit PWM)• Two Independent Output Compare Units• Double Buffered Output Compare Registers• One Input Capture Unit• Input Capture Noise Canceler• Clear Timer on Compare Match (Auto Reload)• Glitch-free, Phase Correct Pulse Width Modulator (PWM)• Variable PWM Period• Frequency Generator• External Event Counter• Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)

16-bit Timer/Counter Register Description

a) Timer/Counter1 Control Register A – TCCR1A

7 6 5 4 3 2 1 0 COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10

Bit 7:6 – COM1A1:0: Compare Output Mode for Channel A• Bit 5:4 – COM1B1:0: Compare Output Mode for Channel BThe COM1A1:0 and COM1B1:0 control the Output Compare pins (OC1A and OC1B

18

Page 183: Embedded System

respectively) behavior. If one or both of the COM1A1:0 bits are written to one, the OC1Aoutput overrides the normal port functionality of the I/O pin it is connected to. If one orboth of the COM1B1:0 bit are written to one, the OC1B output overrides the normal portfunctionality of the I/O pin it is connected to. However, note that the Data Direction Register(DDR) bit corresponding to the OC1A or OC1B pin must be set in order to enablethe output driver.When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits isdependent of the WGM13:0 bits setting. Table 50 shows the COM1x1:0 bit functionalitywhen the WGM13:0 bits are set to a normal or a CTC mode (non-PWM).

Compare Output Mode, non-PWM

COM1A1/ COM1B0 / Description COM1A0/ COM1B1 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 Toggle OC1A/OC1B on Compare Match. 1 0 Clear OC1A/OC1B on Compare Match (Set output to low level). 1 1 Set OC1A/OC1B on Compare Match (Set output to high level).

18

Page 184: Embedded System

Compare Output Mode, Fast PWM

COM1A1/ COM1B0 / Description COM1A0/ COM1B1 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 WGM13:0 = 15: Toggle OC1A on Compare Match, OC1B disconnected (Normal port operation). For all other WGM1 setting, Normal port operation, OC1A/OC1B disconnected. 1 0 Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at TOP. 1 1 Set OC1A/OC1B on Compare Match, clear OC1A/OC1B at TOP.

Compare Output Mode, Phase Correct and Phase and Frequency Correct

18

Page 185: Embedded System

COM1A1/ COM1B0 / Description COM1A0/ COM1B1 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 WGM13:0 = 9 or 14: Toggle OC1A on Compare Match, OC1B disconnected (Normal port operation). For all other WGM1 setting, Normal port operation, OC1A/OC1B disconnected. 1 0 Clear OC1A/OC1B on Compare Match when up-counting. Set OC1A/OC1B on Compare Match when downcounting.

1 1 Set OC1A/OC1B on Compare Match when up-counting. Clear OC1A/OC1B on Compare Match when downcounting. • Bit 3 – FOC1A: Force Output Compare for Channel A• Bit 2 – FOC1B: Force Output Compare for Channel BThe FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWMmode. However, for ensuring compatibility with future devices, these bits must be set tozero when TCCR1A is written when operating in a PWM mode. When writing a logicalone to the FOC1A/FOC1B bit, an immediate Compare Match is forced on the waveformgeneration unit. The OC1A/OC1B output is changed according to its COM1x1:0 bits setting.Note that the FOC1A/FOC1B bits are implemented as strobes. Therefore it is thevalue present in the COM1x1:0 bits that determine the effect of the forced compare.

18

Page 186: Embedded System

A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in ClearTimer on Compare Match (CTC) mode using OCR1A as TOP.

• Bit 1:0 – WGM11:0: Waveform Generation ModeCombined with the WGM13:2 bits found in the TCCR1B Register, these bits control thecounting sequence of the counter, the source for maximum (TOP) counter value, andwhat type of waveform generation to be used, . Modes of operation supportedby the Timer/Counter unit are: Normal mode (counter), Clear Timer on CompareMatch (CTC) mode, and three types of Pulse Width Modulation (PWM) modes.

Waveform Generation Mode Bit Description

Mode WGM13 WGM1 2 WGM11 WGM10 Timer/Counter Mode of Operation TOP

0 0 0 0 0 Normal 0xFFFF 1 0 0 0 1 PWM,Phase Correct, 8-bit 0x00FF 2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF 3 0 0 1 1 PWM, Phase Correct, 10-bi 0x03FF 4 0 1 0 0 CTC OCR1A 5 0 1 0 1 Fast PWM, 8-bit 0x00FF 6 0 1 1 0 Fast PWM, 9-bit 0x01FF 7 0 1 1 1 Fast PWM, 10-bit 0x03FF 8 1 0 0 0 PWM, Phase and Frequency Correct ICR1

18

Page 187: Embedded System

9 1 0 0 1 PWM, Phase and Frequency Correct OCR1A 10 1 0 1 0 PWM, Phase Correct ICR1 11 1 0 1 1 PWM, Phase Correct OCR1A 12 1 1 0 0 CTC ICR1 13 1 1 0 1 Reserved – – –14 1 1 1 0 Fast PWM ICR1 15 1 1 1 1 Fast PWM OCR1A

b)Timer/Counter1 ControlRegister B – TCCR1B

7 6 5 4 3 2 1 0ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10

• Bit 7 – ICNC1: Input Capture Noise CancelerSetting this bit (to one) activates the Input Capture Noise Canceler. When the NoiseCanceler is activated, the input from the Input Capture Pin (ICP1) is filtered. The filterfunction requires four successive equal valued samples of the ICP1 pin for changing itsoutput. The Input Capture is therefore delayed by four Oscillator cycles when the noisecanceler is enabled.• Bit 6 – ICES1: Input Capture Edge SelectThis bit selects which edge on the Input Capture Pin (ICP1) that is used to trigger a captureevent. When the ICES1 bit is written to zero, a falling (negative) edge is used astrigger, and when the ICES1 bit is written to one, a rising (positive) edge will trigger thecapture.

18

Page 188: Embedded System

When a capture is triggered according to the ICES1 setting, the counter value is copiedinto the Input Capture Register (ICR1). The event will also set the Input Capture Flag(ICF1), and this can be used to cause an Input Capture Interrupt, if this interrupt isenabled.When the ICR1 is used as TOP value (see description of the WGM13:0 bits located inthe TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequentlythe Input Capture function is disabled.• Bit 5: Reserved BitThis bit is reserved for future use. For ensuring compatibility with future devices, this bitmust be written to zero when TCCR1B is written.• Bit 4:3 – WGM13:2: Waveform Generation ModeSee TCCR1A Register description.• Bit 2:0 – CS12:0: Clock SelectThe three Clock Select bits select the clock source to be used by the Timer/Counter,

Clock Select Bit Description

CS12 CS11 CS10 Description

0 0 0 No clock source (Timer/counter stopped). 0 0 1 clkI/O/1 (No prescaling) 0 1 0 clkI/O/8 (From prescaler) 0 1 1 clkI/O/64 (From prescaler) 1 0 0 clkI/O/256 (From prescaler) 1 0 1 clkI/O/1024 (From prescaler) 1 1 0 External clock source on T1 pin. Clock on falling edge. 1 1 1 External clock source on T1 pin. Clock on rising edge.

c)Output Compare Register 1 A18

Page 189: Embedded System

– OCR1AH and OCR1AL OCR1A[15:8] OCR1AH OCR1A[7:0] OCR1AL

d)Output Compare Register 1 B– OCR1BH and OCR1BLOCR1B[15:8] OCR1BHOCR1B[7:0] OCR1BL

The Output Compare Registers contain a 16-bit value that is continuously comparedwith the counter value (TCNT1). A match can be used to generate an output compareinterrupt, or to generate a waveform output on the OC1x pin.The Output Compare Registers are 16-bit in size. To ensure that both the high and lowbytes are written simultaneously when the CPU writes to these registers, the access isperformed using an 8-bit temporary High Byte Register (TEMP). This temporary registeris shared by all the other 16-bit registers

Analog Comparator:The Analog Comparator compares the input values on the positive pin AIN0 and negativepin AIN1. When the voltage on the positive pin AIN0 is higher than the voltage onthe negative pin AIN1, the Analog Comparator Output, ACO, is set. The comparator’soutput can be set to trigger the Timer/Counter1 Input Capture function. In addition, thecomparator can trigger a separate interrupt, exclusive to the Analog Comparator. Theuser can select Interrupt triggering on comparator output rise, fall or toggle.

Analog Comparator Controland Status Register – ACSR

18

Page 190: Embedded System

7 6 5 4 3 2 1 0ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0

• Bit 7 – ACD: Analog Comparator DisableWhen this bit is written a logic one, the power to the Analog Comparator is switched off.This bit can be set at any time to turn off the Analog Comparator. This will reduce powerconsumption in Active and Idle mode. When changing the ACD bit, the Analog ComparatorInterrupt must be disabled by clearing the ACIE bit in ACSR. Otherwise an interruptcan occur when the bit is changed.• Bit 6 – ACBG: Analog Comparator Bandgap SelectWhen this bit is set, a fixed bandgap reference voltage replaces the positive input to theAnalog Comparator. When this bit is cleared, AIN0 is applied to the positive input of theAnalog Comparator. See “Internal Voltage Reference” on page 49.• Bit 5 – ACO: Analog Comparator OutputThe output of the Analog Comparator is synchronized and then directly connected toACO. The synchronization introduces a delay of 1 - 2 clock cycles.• Bit 4 – ACI: Analog Comparator Interrupt FlagThis bit is set by hardware when a comparator output event triggers the interrupt modedefined by ACIS1 and ACIS0. The Analog Comparator Interrupt routine is executed ifthe ACIE bit is set and the I-bit in SREG is set. ACI is cleared by hardware when executingthe corresponding interrupt handling vector. Alternatively, ACI is cleared by writing

• Bit 3 – ACIE: Analog Comparator Interrupt EnableWhen the ACIE bit is written logic one and the I-bit in the Status Register is set, the AnalogComparator interrupt is activated. When written logic zero, the interrupt is disabled.• Bit 2 – ACIC: Analog Comparator Input Capture Enable

19

Page 191: Embedded System

When written logic one, this bit enables the Input Capture function in Timer/Counter1 tobe triggered by the Analog Comparator. The comparator output is in this case directlyconnected to the Input Capture front-end logic, making the comparator utilize the noisecanceler and edge select features of the Timer/Counter1 Input Capture interrupt. Whenwritten logic zero, no connection between the Analog Comparator and the Input Capturefunction exists. To make the comparator trigger the Timer/Counter1 Input Capture interrupt,the TICIE1 bit in the Timer Interrupt Mask Register (TIMSK) must be set.• Bits 1, 0 – ACIS1, ACIS0: Analog Comparator Interrupt Mode SelectThese bits determine which comparator events that trigger the Analog Comparator interrupt.The different settings are shown in Table 72.When changing the ACIS1/ACIS0 bits, the Analog Comparator interrupt must be disabled by clearing its Interrupt Enable bit in the ACSR Register. Otherwise an interruptcan occur when the bits are changed.. ACIS1/ACIS0 SettingsACIS1 ACIS0 Interrupt Mode0 0 Comparator Interrupt on Output Toggle0 1 Reserved1 0 Comparator Interrupt on Falling Output Edge1 1 Comparator Interrupt on Rising Output Edge

Hardware Interfacing & Programming

Tool used for AVR microcontroller programming :Compiler-winAVRHex code downloader-ISP programmerSimulator-AVR studio(pony prog)

Port programming

Port as output: C –code for blinking LED connected on PORTB

19

Page 192: Embedded System

#include<avr/io.h>#include<avr/iom8515.h>void delay(unsigned int i);void main(void){DDRB=0xff;while(1){PORTB=0x00;delay(0xffff);PORTB=(0xff);delay(0xFFFF);}}void delay(unsigned int i){while (i!=0){i--;}}

LCD interfacing: C code for LCD display

#include<avr/io.h>#include<avr/iom8515.h>

#define LCDPRT PORTB

void lcd_cmd(unsigned char a);void display(unsigned char b);void wait(void);void Init_lcd(void);void clear_lcd(void);void cursor_position(unsigned char c);void delay(unsigned int i) ;

19

Page 193: Embedded System

int main(void)

{DDRB=0xff,DDRC=0XFF;DDRD=0X1c;PORTD=20;Init_lcd();

cursor_position(0x00);display('h');cursor_position(0x01);display('e');cursor_position(0x02);display('l');cursor_position(0x03);display('l');cursor_position(0x04);display('o');

return 0;}void lcd_cmd(unsigned char a) { delay(2000); LCDPRT=a; cbi(PORTD,3); sbi(PORTD,4); cbi(PORTD,4); } void display(unsigned char b) { delay(2000); LCDPRT=b; sbi(PORTD,3);

19

Page 194: Embedded System

sbi(PORTD,4); cbi(PORTD,4); }

void wait(void) { unsigned int count=1000; while(count!=0) { count--; }

}

void Init_lcd(void) { lcd_cmd(0x3c); lcd_cmd(0x0c); lcd_cmd(0x01); } void clear_lcd(void) { lcd_cmd(0x01); }

void cursor_position(unsigned char c) { lcd_cmd(c+0x80); }void delay(unsigned int i) { while (i!=0) { i--;

19

Page 195: Embedded System

}}

ADC interfacing: C- code for adc monitoring

#include<avr/io.h>#include<avr/iom8515.h>#define LCDPRT PORTB unsigned char table[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

void disp_dec(unsigned int digit); unsigned char read_adc(void);void display_string(unsigned char *sp);void lcd_cmd(unsigned char a);void display(unsigned char b);void wait(void);void Init_lcd(void);void clear_lcd(void);void cursor_position(unsigned char c);void delay(unsigned int i) ; unsigned char n;

int main(void)

{unsigned char e;

DDRB=0XFF;DDRC=0x00;PORTC=0xff;DDRD=0X1c;PORTD=0x20;Init_lcd();

while(1) { e=read_adc();

19

Page 196: Embedded System

cursor_position(0x00); disp_dec(e); }return 0;} unsigned char read_adc(void) { unsigned char n; cbi(PORTD,2);

delay(0xffff); sbi(PORTD,2);

while(bit_is_set(PIND,5)) {

n=PINC; }

return n; }

void display_string(unsigned char *sp) { while(*sp!='$') {

display(*sp);

sp=sp+1; } }

void lcd_cmd(unsigned char a) {

19

Page 197: Embedded System

delay(2000); LCDPRT=a; cbi(PORTD,3); sbi(PORTD,4); cbi(PORTD,4); } void display(unsigned char b) { delay(2000); LCDPRT=b; sbi(PORTD,3); sbi(PORTD,4); cbi(PORTD,4); }

void wait(void) { unsigned int count=1000; while(count!=0) { count--; }

}

void Init_lcd(void) { lcd_cmd(0x3c); lcd_cmd(0x0c); lcd_cmd(0x01); } void clear_lcd(void) {

19

Page 198: Embedded System

lcd_cmd(0x01); }

void cursor_position(unsigned char c) { lcd_cmd(c+0x80); }void delay(unsigned int i) { while (i!=0) { i--;

}}void disp_dec(unsigned int digit) {unsigned int temp;

if(digit<100){temp=digit/10;display(table[temp]);temp=digit-temp*10;display(table[temp]);}

if(digit>99 && digit<1000){temp=digit/100;display(table[temp]);digit=digit-(temp*100);temp=digit/10;display(table[temp]);digit=digit-(temp*10);temp=digit;display(table[temp]);}

19

Page 199: Embedded System

DAC INTERFACING:

#include<avr/io.h>#include<avr/iom8515.h>void main (void){DDRC=OXFF; while(1) { PORTC=1; PORTC =2; PORTC =3; PORTC =4; PORTC =5; PORTC =6; PORTC =7; PORTC =8; PORTC =9; PORTC =10; PORTC =11; PORTC =12; PORTC =13; PORTC =14; PORTC =15; PORTC =14; PORTC =13; PORTC =12; PORTC =10; PORTC =9; PORTC =8; PORTC =7; PORTC =6; PORTC =5; PORTC =4; PORTC =3; PORTC =2; PORTC =1;

19

Page 200: Embedded System

PORTC =0; }}

Wave form generation using 8 bit timer (Timer 0): A) C code for square wave generation:

#include<avr/io.h>#include<avr/iom8515.h>int main(void){

while(1){ DDRB=0xff; TCCR0=0x99; TCNT0=0x00; OCR0=200;

}return 0;}

B) C- code for Fast-PWM generation:

#include<avr/io.h>#include<avr/iom8515.h>int main(void){while(1){ DDRB=0xff; TCCR0=0x6a; OCR0=100;

20

Page 201: Embedded System

}return 0;}

C) C- code for Phase correct PWM:

#include<avr/io.h>#include<avr/iom8515.h>int main(void){while(1){ DDRB=0xff; TCCR0=0x61; OCR0=100;

}return 0;}

Wave form generation using 16 bit Timer(Timer 1)A) C- code for square wave generation-CTC mode#include<avr/io.h>#include<avr/iom8515.h>int main(void){

while(1){ DDRD=0xff; TCCR1A=0x48; TCCR1B=0x09; TCNT1L=0x00; OCR1AL=0xFF; OCR1AH=0xff;

20

Page 202: Embedded System

}return 0;}

B) C- code for fast PWM

#include<avr/io.h>#include<avr/iom8515.h>int main(void){

while(1){ DDRD=0XFF; TCCR1A=0X81;// 8bit PWM top=0xff;255// TCCR1A=0X82; //9bit PWM top=0x01ff;511 //TCCR1A=0X83;//10 bit PWM top=0x3ff; 1023 TCCR1B=0X09; OCR1A=980;

C) C- code for Phase correct PWM

#include<avr/io.h>#include<avr/iom8515.h>int main(void){

while(1){ DDRD=0XFF; //TCCR1A=0X81;// 8bit Phase correct PWM top=0xff;255 //TCCR1A=0X82; //9bit Phase correct PWM top=0x01ff;511 TCCR1A=0X83;//10 Phase correct bit PWM top=0x3ff; 1023 TCCR1B=0X01; OCR1A=100; // change the value of OCRA register as per requirement

}return 0;}

20

Page 203: Embedded System

20