Download - Mpmc 11 Marks

Transcript
Page 1: Mpmc 11 Marks

MICROPROCESSORS AND MICROCONTROLLERS

11 MARKS QUESTIONS AND ANSWERS

UNIT-I

1.) Explain the Internal Architecture of 8085 Microprocessor

Control Unit

1

Page 2: Mpmc 11 Marks

Generates signals within uP to carry out the instruction, which has been decoded. In

reality causes certain connections between blocks of the uP to be opened or closed, so

that data goes where it is required, and so that ALU operations occur.

Arithmetic Logic Unit

The ALU performs the actual numerical and logic operation such as ‘add’, ‘subtract’,

‘AND’, ‘OR’, etc. Uses data from memory and from Accumulator to perform arithmetic.

Always stores result of operation in Accumulator.

Registers

The 8085/8080A-programming model includes six registers, one accumulator, and one

flag register, as shown in Figure. In addition, it has two 16-bit registers: the stack pointer

and the program counter. They are described briefly as follows.

The 8085/8080A has six general-purpose registers to store 8-bit data; these are identified

as B,C,D,E,H, and L as shown in the figure. They can be combined as register pairs - BC,

DE, and HL - to perform some 16-bit operations. The programmer can use these registers

to store or copy data into the registers by usingdata copy instructions.

Accumulator

The accumulator is an 8-bit register that is a part of arithmetic/logic unit (ALU). This

register is used to store 8-bit data and to perform arithmetic and logical operations. The

result of an operation is stored in the accumulator. The accumulator is also identified as

register A.

Flags

The ALU includes five flip-flops, which are set or reset after an operation according to

data conditions of the result in the accumulator and other registers. They are called

Zero(Z), Carry (CY), Sign (S), Parity (P), and Auxiliary Carry (AC) flags; they are listed

in the Table and their bit positions in the flag register are shown in the Figure below. The

most commonly used flags are Zero, Carry, and Sign. The microprocessor uses these

flags to test data conditions.

For example, after an addition of two numbers, if the sum in the accumulator id larger

than eight bits, the flip-flop uses to indicate a carry -- called the Carry flag (CY) – is set

to one. When an arithmetic operation results in zero, the flip-flop called the Zero(Z) flag

2

Page 3: Mpmc 11 Marks

is set to one. The first Figure shows an 8-bit register, called the flag register, adjacent to

the accumulator. However, it is not used as a register; five bit positions out of eight are

used to store the outputs of the five flip-flops. The flags are stored in the 8-bit register so

that the programmer can examine these flags (data conditions) by accessing the register

through an instruction.

These flags have critical importance in the decision-making process of the

microprocessor.

The conditions (set or reset) of the flags are tested through the software instructions. For

example, the instruction JC (Jump on Carry) is implemented to change the sequence of a

program when CY flag is set. The thorough understanding of flag is essential in writing

assembly language programs.

Program Counter (PC)

This 16-bit register deals with sequencing the execution of instructions. This register is a

memory pointer. Memory locations have 16-bit addresses, and that is why this is a 16-bit

register.

The microprocessor uses this register to sequence the execution of the instructions. The

function of the program counter is to point to the memory address from which the next

byte is to be fetched. When a byte (machine code) is being fetched, the program counter

is incremented by one to point to the next memory location

Stack Pointer (SP)

The stack pointer is also a 16-bit register used as a memory pointer. It points to a memory

location in R/W memory, called the stack. The beginning of the stack is defined by

loading 16-bit address in the stack pointer.

Instruction Register/Decoder

Temporary store for the current instruction of a program. Latest instruction sent here

from memory prior to execution. Decoder then takes instruction and ‘decodes’ or

interprets the instruction. Decoded instruction then passed to next stage.

Memory Address Register

Holds address, received from PC, of next program instruction. Feeds the address bus with

addresses of location of the program under execution.

3

Page 4: Mpmc 11 Marks

Control Generator

Generates signals within uP to carry out the instruction which has been decoded. In

reality causes certain connections between blocks of the uP to be opened or closed, so

that data goes where it is required, and so that ALU operations occur.

Register Selector

This block controls the use of the register stack in the example. Just a logic circuit which

switches between different registers in the set will receive instructions from Control Unit.

General Purpose Registers

uP requires extra registers for versatility. Can be used to store additional data during a

program. More complex processors may have a variety of differently named registers.

2. 8085 System Bus

Typical system uses a number of busses, collection of wires, which transmit binary

numbers, one bit per wire. A typical microprocessor communicates with memory and

other devices (input and output) using three busses: Address Bus, Data Bus and Control

Bus.

Address Bus

One wire for each bit, therefore 16 bits = 16 wires. Binary number carried alerts memory

to ‘open’ the designated box. Data (binary) can then be put in or taken out.The Address

Bus consists of 16 wires, therefore 16 bits. Its "width" is 16 bits. A 16 bit binary number

allows 216 different numbers, or 32000 different numbers, ie 0000000000000000 up to

1111111111111111. Because memory consists of boxes, each with a unique address, the

size of the address bus determines the size of memory, which can be used. To

communicate with memory the microprocessor sends an address on the address bus, eg

0000000000000011 (3 in decimal), to the memory. The memory the selects box number

3 for reading or writing data. Address bus is unidirectional, ie numbers only sent from

microprocessor to memory, not other way.

Data Bus

Data Bus carries ‘data’, in binary form, between μP and other external units, such as

memory. Typical size is 8 or 16 bits. Size determined by size of boxes in memory and μP

4

Page 5: Mpmc 11 Marks

size helps determine performance of μP. The Data Bus typically consists of 8 wires.

Therefore, 28 combinations of binary digits. Data bus used to transmit "data", ie

information, results of arithmetic, etc, between memory and the microprocessor. Bus is

bi-directional. Size of the data bus determines what arithmetic can be done. If only 8 bits

wide then largest number is 11111111 (255 in decimal). Therefore, larger number have to

be broken down into chunks of 255. This slows microprocessor. Data Bus also carries

instructions from memory to the microprocessor. Size of the bus therefore limits the

number of possible instructions to 256, each specified by a separate number.

Control Bus

Control Bus are various lines which have specific functions for coordinating and

controlling uP operations. Eg: Read/NotWrite line, single binary digit. Control whether

memory is being ‘written to’ (data stored in mem) or ‘read from’ (data taken out of mem)

1 = Read, 0 = Write. May also include clock line(s) for timing/synchronising, ‘interrupts’,

‘reset’ etc. Typically μP has 10 control lines. The Control Bus carries control signals

partly unidirectional, partly bi-directional.

Control signals are things like "read or write". This tells memory that we are either

reading from a location, specified on the address bus, or writing to a location specified.

Various other signals to control and coordinate the operation of the system. Modern day

microprocessors, like 80386, 80486 have much larger busses. Typically 16 or 32 bit

busses, which allow larger number of instructions, more memory location, and faster

arithmetic. Microcontrollers organized along same lines, except: because

microcontrollers have memory etc inside the chip, the busses may all be internal. In the

microprocessor the three busses are external to the chip (except for the internal data bus).

In case of external busses, the chip connects to the busses via buffers, which are simply

an electronic connection between external bus and the internal data bus.

2.)Explain the 8085 Pin description.

Properties

5

Page 6: Mpmc 11 Marks

Single + 5V Supply

4 Vectored Interrupts (One is Non Maskable)

Serial In/Serial Out Port

Decimal, Binary, and Double Precision Arithmetic

Direct Addressing Capability to 64K bytes of memory

The Intel 8085A is a new generation, complete 8 bit parallel central processing unit

(CPU). The 8085A uses a multiplexed data bus. The address is split between the 8bit

address bus and the 8bit data bus. Figures are at the end of the document.

Pin Description

The following describes the function of each pin:

A6 - A1s (Output 3 State)

Address Bus; The most significant 8 bits of the memory address or the 8 bits of the I/0

address,3 stated during Hold and Halt modes.

AD0 - 7 (Input/Output 3state)

Multiplexed Address/Data Bus; Lower 8 bits of the memory address (or I/0 address)

appear on the bus during the first clock cycle of a machine state. It then becomes the data

bus during the second and third clock cycles. 3 stated during Hold and Halt modes.

ALE (Output)

Address Latch Enable: It occurs during the first clock cycle of a machine state and

enables the address to get latched into the on chip latch of peripherals. The falling edge of

ALE is set to guarantee setup and hold times for the address information. ALE can also

be used to strobe the status information. ALE is never 3stated.

SO, S1 (Output)

Data Bus Status. Encoded status of the bus cycle:

S1 S0

O O HALT

0 1 WRITE

1 0 READ

1 1 FETCH

S1 can be used as an advanced R/W status.

RD (Output 3state)

6

Page 7: Mpmc 11 Marks

READ indicates the selected memory or 1/0 device is to be read and that the Data Bus is

available for the data transfer.

WR (Output 3state)

WRITE indicates the data on the Data Bus is to be written into the selected memory or

1/0 location. Data is set up at the trailing edge of WR. 3stated during Hold and Halt

modes.

READY (Input)

If Ready is high during a read or write cycle, it indicates that the memory or peripheral is

ready to send or receive data. If Ready is low, the CPU will wait for Ready to go high

before completing the read or write cycle.

HOLD (Input)

HOLD indicates that another Master is requesting the use of the Address and Data Buses.

The CPU, upon receiving the Hold request. will relinquish the use of buses as soon as the

completion of the current machine cycle. Internal processing can continue. The processor

can regain the buses only after the Hold is removed. When the Hold is acknowledged, the

Address, Data, RD, WR, and IO/M lines are 3stated.

HLDA (Output)

HOLD ACKNOWLEDGE indicates that the CPU has received the Hold request and that

it will relinquish the buses in the next clock cycle. HLDA goes low after the Hold request

is removed. The CPU takes the buses one half clock cycle after HLDA goes low.

INTR (Input)

INTERRUPT REQUEST is used as a general purpose interrupt. It is sampled only during

the next to the last clock cycle of the instruction. If it is active, the Program Counter (PC)

will be inhibited from incrementing and an INTA will be issued. During this cycle a

RESTART or CALL instruction can be inserted to jump to the interrupt service routine.

The INTR is enabled and disabled by software. It is disabled by Reset

and immediately after an interrupt is accepted.

INTA (Output)

INTERRUPT ACKNOWLEDGE is used instead of (and has the same timing as) RD

during the Instruction cycle after an INTR is accepted. It can be used to activate the 8259

Interrupt chip or some other interrupt port.

7

Page 8: Mpmc 11 Marks

RST 5.5

RST 6.5 - (Inputs)

RST 7.5

RESTART INTERRUPTS These three inputs have the same timing as I NTR except they

cause an internal RESTART to be automatically inserted.

RST 7.5 ~~ Highest Priority

RST 6.5

RST 5.5 o Lowest Priority

The priority of these interrupts is ordered as shown above. These interrupts have a higher

priority than the INTR.

TRAP (Input)

Trap interrupt is a nonmaskable restart interrupt. It is recognized at the same time as

INTR. It is unaffected by any mask or Interrupt Enable. It has the highest priority of any

interrupt.

RESET IN (Input)

Reset sets the Program Counter to zero and resets the Interrupt Enable and HLDA

flipflops. None of the other flags or registers (except the instruction register) are affected

The CPU is held in the reset condition as long as Reset is applied.

RESET OUT (Output)

Indicates CPlJ is being reset. Can be used as a system RESET. The signal is synchronized

to the processor clock.

X1, X2 (Input)

Crystal or R/C network connections to set the internal clock generator X1 can also be an

external clock input instead of a crystal. The input frequency is divided by 2 to give the

internal operating frequency.

CLK (Output)

Clock Output for use as a system clock when a crystal or R/ C network is used as an input

to the CPU. The period of CLK is twice the X1, X2 input period.

IO/M (Output)

IO/M indicates whether the Read/Write is to memory or l/O Tristated during Hold and

Halt modes.

8

Page 9: Mpmc 11 Marks

SID (Input)

Serial input data line The data on this line is loaded into accumulator bit 7 whenever a

RIM instruction is executed.

SOD (output)

Serial output data line. The output SOD is set or reset as specified by the SIM instruction.

Vcc

+5 volt supply.

Vss

Ground Reference.

9

Page 10: Mpmc 11 Marks

The salient features of 8085 μp are:

• It is a 8 bit microprocessor.

• It is manufactured with N-MOS technology.

10

Page 11: Mpmc 11 Marks

• It has 16-bit address bus and hence can address up to 216 = 65536 bytes (64KB)

memory locations through A0-A15.

• The first 8 lines of address bus and 8 lines of data bus are multiplexed AD0 – AD7.

• Data bus is a group of 8 lines D0 – D7.

• It supports external interrupt request.

• A 16 bit program counter (PC)

• A 16 bit stack pointer (SP)

• Six 8-bit general purpose register arranged in pairs: BC, DE, HL.

• It requires a signal +5V power supply and operates at 3.2 MHZ single phase clock.

• It is enclosed with 40 pins DIP (Dual in line package).

3.) Explain the Functional Description OF 8085.

The 8085A is a complete 8 bit parallel central processor. It requires a single +5 volt

supply. Its basic clock speed is 3 MHz thus improving on the present 8080's performance

with higher system speed. Also it is designed to fit into a minimum system of three IC's:

The CPU, a RAM/ IO, and a ROM or PROM/IO chip.

The 8085A uses a multiplexed Data Bus. The address is split between the higher 8bit

Address Bus and the lower 8bit Address/Data Bus. During the first cycle the address is

sent out. The lower 8bits are latched into the peripherals by the Address Latch Enable

(ALE). During the rest of the machine cycle the Data Bus is used for memory or l/O data.

The 8085A provides RD, WR, and lO/Memory signals for bus control. An Interrupt

Acknowledge signal (INTA) is also provided. Hold, Ready, and all Interrupts are

synchronized. The 8085A also provides serial input data (SID) and serial output data

(SOD) lines for simple serial interface.

In addition to these features, the 8085A has three maskable, restart interrupts and one

non-maskable trap interrupt. The 8085A provides RD, WR and IO/M signals for

Buscontrol.

Status Information

11

Page 12: Mpmc 11 Marks

Status information is directly available from the 8085A. ALE serves as a status strobe.

The status is partially encoded, and provides the user with advanced timing of the type of

bus transfer being done. IO/M cycle status signal is provided directly also. Decoded So,

S1 Carries the following status information:

HALT, WRITE, READ, FETCH

S1 can be interpreted as R/W in all bus transfers. In the 8085A the 8 LSB of address are

multiplexed with the data instead of status. The ALE line is used as a strobe to enter the

lower half of the address into the memory or peripheral address latch. This also frees

extra pins for expanded interrupt capability.

Interrupt and Serial l/O

The8085A has5 interrupt inputs: INTR, RST5.5, RST6.5, RST 7.5, and TRAP. INTR is

identical in function to the 8080 INT. Each of the three RESTART inputs, 5.5, 6.5. 7.5,

has a programmable mask. TRAP is also a RESTART interrupt except it is nonmaskable.

The three RESTART interrupts cause the internal execution of RST (saving the program

counter in the stack and branching to the RESTART address) if the interrupts are enabled

and if the interrupt mask is not set. The non-maskable TRAP causes the internal

execution of a RST independent of the state of the interrupt enable or masks. The

interrupts are arranged in a fixed priority that determines which interrupt is to be

recognized if more than one is pending as follows: TRAP highest priority, RST 7.5, RST

6.5, RST 5.5, INTR lowest priority This priority scheme does not take into account the

priority of a routine that was started by a higher priority interrupt. RST 5.5 can interrupt a

RST 7.5 routine if the interrupts were re-enabled before the end of the RST 7.5 routine.

The TRAP interrupt is useful for catastrophic errors such as power failure or bus error.

The TRAP input is recognized just as any other interrupt but has the highest priority. It is

not affected by any flag or mask. The TRAP input is both edge and level sensitive.

Basic System Timing

The 8085A has a multiplexed Data Bus. ALE is used as a strobe to sample the lower 8bits

of address on the Data Bus. Figure 2 shows an instruction fetch, memory read and l/ O

write cycle (OUT). Note that during the l/O write and read cycle that the l/O port address

is copied on both the upper and lower half of the address. As in the 8080, the READY

line is used to extend the read and write pulse lengths so that the 8085A can be used with

12

Page 13: Mpmc 11 Marks

slow memory. Hold causes the CPU to relingkuish the bus when it is through with it by

floating the Address and Data Buses.

System Interface

8085A family includes memory components, which are directly compatible to the 8085A

CPU. For example, a system consisting of the three chips, 8085A, 8156, and 8355 will

have the following features:

· 2K Bytes ROM

· 256 Bytes RAM

· 1 Timer/Counter

· 4 8bit l/O Ports

· 1 6bit l/O Port

· 4 Interrupt Levels

· Serial In/Serial Out Ports

In addition to standard l/O, the memory mapped I/O offers an efficient l/O addressing

technique. With this technique, an area of memory address space is assigned for l/O

address, thereby, using the memory address for I/O manipulation. The 8085A CPU can

also interface with the standard memory that does not have the multiplexed address/data

bus.

13

Page 14: Mpmc 11 Marks

4.) Explain the Addressing Modes of 8085.

The instructions MOV B, A or MVI A, 82H are to copy data from a source into a

destination. In these instructions the source can be a register, an input port, or an 8-bit

number (00H to FFH). Similarly, a destination can be a register or an output port. The

sources and destination are operands. The various formats for specifying operands are

called the ADDRESSING MODES. For 8085, they are:

1. Immediate addressing.

2. Register addressing.

3. Direct addressing.

4. Indirect addressing.

Immediate addressing

Data is present in the instruction. Load the immediate data to the destination provided.

Example: MVI R,data

14

Page 15: Mpmc 11 Marks

Register addressing

Data is provided through the registers.

Example: MOV Rd, Rs

Direct addressing

Used to accept data from outside devices to store in the accumulator or send the data

stored in the accumulator to the outside device. Accept the data from the port 00H and

store them into the accumulator or Send the data from the accumulator to the port 01H.

Example: IN 00H or OUT 01H

Indirect Addressing

This means that the Effective Address is calculated by the processor. And the

contents of the address (and the one following) is used to form a second address. The

second address is where the data is stored. Note that this requires several memory

accesses; two accesses to retrieve the 16-bit address and a further access (or accesses) to

retrieve the data which is to be loaded into the register.

5.) Classify Instruction Set of 8085.

An instruction is a binary pattern designed inside a microprocessor to perform a specific

function. The entire group of instructions, called the instruction set, determines what

functions the microprocessor can perform. These instructions can be classified into the

following five functional categories: data transfer (copy) operations, arithmetic

operations, logical operations, branching operations, and machine-control operations.

Data Transfer (Copy) Operations

This group of instructions copy data from a location called a source to another location

called a destination, without modifying the contents of the source. In technical manuals,

the term data transfer is used for this copying function. However, the term transfer is

misleading; it creates the impression that the contents of the source are destroyed when,

in fact, the contents are retained without any modification. The various types of data

transfer (copy) are listed below together with examples of each type:

15

Page 16: Mpmc 11 Marks

Arithmetic Operations

These instructions perform arithmetic operations such as addition, subtraction, increment,

and decrement.

Addition - Any 8-bit number, or the contents of a register or the contents of a memory

location can be added to the contents of the accumulator and the sum is stored in the

accumulator. No two other 8-bit registers can be added directly (e.g., the contents of

register B cannot be added directly to the contents of the register C). The instruction

DAD is an exception; it adds 16-bit data directly in register pairs.

Subtraction - Any 8-bit number, or the contents of a register, or the contents of a

memory location can be subtracted from the contents of the accumulator and the results

stored in the accumulator. The subtraction is performed in 2's compliment, and the results

if negative, are expressed in 2's complement. No two other registers can be subtracted

directly.

Increment/Decrement - The 8-bit contents of a register or a memory location can be

incremented or decrement by 1. Similarly, the 16-bit contents of a register pair (such as

BC) can be incremented or decrement by 1. These increment and decrement operations

differ from addition and subtraction in an important way; i.e., they can be performed in

any one of the registers or in a memory location.

Logical Operations

These instructions perform various logical operations with the contents of the

accumulator.

16

Page 17: Mpmc 11 Marks

AND, OR Exclusive-OR - Any 8-bit number, or the contents of a register, or of a

memory location can be logically ANDed, Ored, or Exclusive-ORed with the contents of

the accumulator. The results are stored in the accumulator.

Rotate- Each bit in the accumulator can be shifted either left or right to the next position.

Compare- Any 8-bit number, or the contents of a register, or a memory location can be

compared for equality, greater than, or less than, with the contents of the accumulator.

Complement - The contents of the accumulator can be complemented. All 0s are

replaced by 1s and all 1s are replaced by 0s.

Branching Operations

This group of instructions alters the sequence of program execution either conditionally

or unconditionally.

Jump - Conditional jumps are an important aspect of the decision-making process in the

programming. These instructions test for a certain conditions (e.g., Zero or Carry flag)

and alter the program sequence when the condition is met. In addition, the instruction set

includes an instruction called unconditional jump.

Call, Return, and Restart - These instructions change the sequence of a program either

by calling a subroutine or returning from a subroutine. The conditional Call and Return

instructions also can test condition flags.

Machine Control Operations

These instructions control machine functions such as Halt, Interrupt, or do nothing. The

microprocessor operations related to data manipulation can be summarized in four

functions:

1. copying data

2. performing arithmetic operations

3. performing logical operations

4. testing for a given condition and alerting the program sequence

Some important aspects of the instruction set are noted below:

1. In data transfer, the contents of the source are not destroyed; only the contents of the

destination are changed. The data copy instructions do not affect the flags.

17

Page 18: Mpmc 11 Marks

2. Arithmetic and Logical operations are performed with the contents of the accumulator,

and the results are stored in the accumulator (with some expectations). The flags are

affected according to the results.

3. Any register including the memory can be used for increment and decrement.

4. A program sequence can be changed either conditionally or by testing for a given data

condition.

Instruction Format

An instruction is a command to the microprocessor to perform a given task on a

specified data. Each instruction has two parts: one is task to be performed, called the

operation code (opcode), and the second is the data to be operated on, called the

operand. The operand (or data) can be specified in various ways. It may include 8-bit (or

16-bit ) data, an internal register, a memory location, or 8-bit (or 16-bit) address. In some

instructions, the operand is implicit.

Instruction word size

The 8085 instruction set is classified into the following three groups according to word

size:

1. One-word or 1-byte instructions

2. Two-word or 2-byte instructions

3. Three-word or 3-byte instructions

In the 8085, "byte" and "word" are synonymous because it is an 8-bit microprocessor.

However, instructions are commonly referred to in terms of bytes rather than words.

One-Byte Instructions

A 1-byte instruction includes the opcode and operand in the same byte. Operand(s) are

internal register and are coded into the instruction.

For example:

18

Page 19: Mpmc 11 Marks

These instructions are 1-byte instructions performing three different tasks. In the first

instruction, both operand registers are specified. In the second instruction, the operand B

is specified and the accumulator is assumed. Similarly, in the third instruction, the

accumulator is assumed to be the implicit operand. These instructions are stored in 8- bit

binary format in memory; each requires one memory location.

MOV rd, rs

rd <-- rs copies contents of rs into rd.

Coded as 01 ddd sss where ddd is a code for one of the 7 general registers which is the

destination of the data, sss is the code of the source register.

Example: MOV A,B

Coded as 01111000 = 78H = 170 octal (octal was used extensively in instruction design

of such processors).

ADD r

A <-- A + r

Two-Byte Instructions

In a two-byte instruction, the first byte specifies the operation code and the second byte

specifies the operand. Source operand is a data byte immediately following the opcode.

For example:

19

Page 20: Mpmc 11 Marks

Assume that the data byte is 32H. The assembly language instruction is written as

The instruction would require two memory locations to store in memory.

MVI r,data

r <-- data

Example: MVI A,30H coded as 3EH 30H as two contiguous bytes. This is an

example of immediate addressing.

ADI data

A <-- A + data

OUT port

0011 1110

DATA

where port is an 8-bit device address. (Port) <-- A. Since the byte is not the data but

points directly to where it is located this is called direct addressing.

Three-Byte Instructions

In a three-byte instruction, the first byte specifies the opcode, and the following two bytes

specify the 16-bit address. Note that the second byte is the low-order address and the

third byte is the high-order address.

opcode + data byte + data byte

For example:

20

Page 21: Mpmc 11 Marks

This instruction would require three memory locations to store in memory.

Three byte instructions - opcode + data byte + data byte

LXI rp, data16

rp is one of the pairs of registers BC, DE, HL used as 16-bit registers. The two data

bytes are 16-bit data in L H order of significance.

rp <-- data16

Example:

LXI H,0520H coded as 21H 20H 50H in three bytes. This is also immediate

addressing.

LDA addr

A <-- (addr) Addr is a 16-bit address in L H order. Example: LDA 2134H coded as

3AH 34H 21H. This is also an example of direct addressing.

6.) Explain the fetch end execute operation.

FETCH OPERATION:

The first byte of an instruction is its opcode. An instruction may be more than one byte

long. The other bytes are data of operand address. The program counter (PC) keeps the

memory address of the next instruction to be executed. In the beginning of a fetch cycle

the content of the program counter, which is the address of the memory location where

opcode is available, is sent to the memory. The memory places the opcode on the data

bus so as to transfer it to the microprocessor. The entire operation of fetching an opcode

takes three clock cycles.

EXECUTE OPERATION:

The opcode fetched from the memory goes to the instruction register (IR). From the

instruction register it goes to the decoder circuitry which decodes the instruction. After

21

Page 22: Mpmc 11 Marks

the instruction is decoded, execution begins. If the operand is in general purpose registers

execution is immediately performed.

The time taken for decoding and execution is one clock cycle. If an instruction contains

data or operand and address which are still in the memory, the microprocessor has to

perform some read operations to get the desired data. After receiving the data it performs

execute operation. A read cycle is similar to a fetch cycle. In case of a read cycle the

quantity received from the memory are data or operand address instead of an opcode. In

some instructions write operation is performed. In write cycle data are sent from the

microprocessor to the memory or an output device. Thus we see that in some cases an

execute cycle may involve one or more read or write cycles or both.

MACHINE CYCLE:

Machine cycle is defined as the time required completing the operation of accessing

either memory or I/O. In the 8085, the machine cycle may consist of three to six T states.

T-State:

T-State is defined as one sub-division of the operation performed in one clock period.

These sub-divisions are internal states synchronized with the system clock.

TIME DELAYS:

Counters are constructed using software instructions to keep track of the events. Since the

counting is performed at such high speed, only the last count can be observed. To observe

all the counts, there must be an appropriate time delay between counts.

Designing a delay is very simple. A register is loaded with a number, depending on the

delay required, and then the register is decremented until it reaches zero by setting up a

loop with a conditional JUMP instruction. The loop causes the delay, depending upon the

clock period of the system.

Single Register Delay:

A count is loaded in a register and the loop is executed until the count reaches zero. The

set of instructions necessary to set up a delay loop are:

LOOPMVI B, FF

DCR B

JNZ LOOP

22

Page 23: Mpmc 11 Marks

To calculate the time delay we must consider the T-states required for each instruction,

and for the number of times the instruction are executed in the loop. The clock frequency

of 8085 is 3MHZ.

Clock period T= 1/f = 1/3*106 = 0.33*10-6

Register B is loaded with FFH (25510) therefore the loop is repeated 255 times.

The time delay can be calculated as follows:

TL=(T*Loop T states*N10)

Where:

TL=Time Delay in loop

T= System Clock Period.

N10=Equivalent decimal number of Hexadecimal count loaded in the delay register.

DCR & JNZ forms a 0 loop with a total of 14 (4+10) T- states.

Therefore:

TL= (0.33*10-6*14*255)

TL=1.1781 *10-3

Eg:

Write an ALP to display FF and 00 alternatively with a

delay:

MVI A, FF

BACK PUSH PSW

STA 8FF1

CALL UPDDT

CALL DELAY

POP PSW

CMA

JMP BACK

HLT

23

Page 24: Mpmc 11 Marks

7.) Sample Programs using 8085

1.Write an Assembly Language Program to add 2- 16 bit

numbers:

LHLD 9501H

XCHG

LHLD 9503H

MVI C, 00

DAD D

JNC LOOP1

INR C

LOOP1 SHLD 9505H

MOV A, C

STA 9507H

HLT

2.Write an ALP to add n- 8 bit numbers: MVI D, 00

MVI C, 05

LXI H, 8030

MOV A, M

DCR C

AHEAD INX H

ADD M

JNC LOOP-1

INR D

24

Page 25: Mpmc 11 Marks

LOOP-1: DCR C

JNZ AHEAD

STA 8056

MOV A, D

STA 8051

HLT

3.Write an ALP to perform 32-bit addition:

LXI H, 8500

MOV C, M

INX H

LXI D, 8600

XRA A

LOOP-1: LDAX D

ADC M

MOV M, A

INX H

INX D

DCR C

JNZ LOOP-1

MVI A, 00

RAL

MOV M, A

RST 5

25

Page 26: Mpmc 11 Marks

4.Write an ALP to subtract 2-8 bit numbers:

LXI H, 8501

MOV A, M

INX H

SUB M

JNC LOOP-1

INR C

LOOP-1 INX H

MOV M, A

MOV A, C

INX H

MOV M, C

RST5

5.Write an ALP to ADD 2-BCD numbers: LXI H, 8A00

MVI D, 00

MOV A, M

INX H

ADD M

DAA

JNC LOOP-1

INR D

LOOP-1 STA 8A03

MOV A, D

STA 8A04

RST5

Write an ALP to SUBTRACT 2-16 BIT NUMBERS:

LHLD 8100

XCHG

LHLD 8102

26

Page 27: Mpmc 11 Marks

MOV A, E

SUB L

STA 8104

JNC LOOP

DCR D

LOOP MOV A, D

SUB H

STA 8105

RST5

Write an ALP to multiply 2-8bit numbers:

LXI H, 8A00

MOV B, M

XRA A

MOV C, A

INX H

AHEAD ADD M

JNC LOOP-1

INR C

LOOP-1 DCR C

JNZ AHEAD

INX H

MOV M, A

INX H

MOV M, C

RST5

5.Write an ALP to perform division of 1-8 bit number by

another 8-bit number:

LXI H, 8900H

MOV A, M

INX H

27

Page 28: Mpmc 11 Marks

MOV B, M

MVI C, FF

LOOP INR C

SUB B

JNC LOOP

ADD B

STA 8902H

MOV A, C

STA 8903H

HLT

6.Write an assembly program to add two numbers

Program

MVI D, 8BH

MVI C, 6FH

MOV A, C

1100 0011

1000 0101

0010 0000

ADD D

OUT PORT1

HLT

7.Write an assembly program to multiply a number by 8

Program

MVI A, 30H

RRC

RRC

RRC

OUT PORT1

HLT

28

Page 29: Mpmc 11 Marks

7.Write an assembly program to find greatest between two numbers

Program

MVI B, 30H

MVI C, 40H

MOV A, B

CMP C

JZ EQU

JC GRT

OUT PORT1

HLT

EQU: MVI A, 01H

OUT PORT1

HLT

GRT: MOV A, C

OUT PORT1

HLT

8.)Explain the memory interfacing with 8085

The memory is made up of semiconductor material used to store the programs and data. Three

types of memory is,

Process memory

Primary or main memory

Secondary memory

TYPICAL EPROM AND STATIC RAM:

A typical semiconductor memory IC will have n address pins, m data pins (or output

pins).

29

Page 30: Mpmc 11 Marks

Having two power supply pins (one for connecting required supply voltage (V and the

other for connecting ground).

The control signals needed for static RAM are chip select (chip enable), read control

(output enable) and write control (write enable).

The control signals needed for read operation in EPROM are chip select (chip enable)

and read control (output enable).

DECODER:

It is used to select the memory chip of processor during the execution of a program. No of IC's

used for decoder is,

2-4 decoder (74LS139)

3-8 decoder (74LS138)

30

Page 31: Mpmc 11 Marks

Table - Number of Address Pins and Data Pins in Memory ICs

31

Page 32: Mpmc 11 Marks

Fig - Block diagram and Truth table of 2-4 decoder

Fig - Block diagram and Truth table of 3-8 decoder

32

Page 33: Mpmc 11 Marks

UNIT –II

1.) Explain about interfacing and peripheral devices.

1. For data transfer from input device to processor the following operations are performed.

The input device will load the data to the port.

When the port receives a data, it sends message to the processor to read the data.

The processor will read the data from the port.

After a data have been read by the processor the input device will load the next data into

the port.

2. For data transfer from processor to output device the following operations are performed.

The processor will load the data to the port.

The port will send a message to the output device to read the data.

The output device will read the data from the port.

After the data have been read by the output device the processor can load the next data to

the port.

The various INTEL 110 port devices are 8212, 8155/8156, 8255, 8355 and 8755.

8212

The 8212 is a 24 pin IC.

It consists of eight number of D-type latches.

It has 8-input lines DI1 to DI8 and 8-output lines DO1 to DO8

The 8212 can be used as an input or output device

It has two selecting device DS1 (low) and DS2.

33

Page 34: Mpmc 11 Marks

Fig - Internal address of 8155

8155:

It has two numbers of 8-bit parallel I/O port (port-A and B)

One number of 6-bit parallel I/O port (port-C).

It has 14 bit timer (operating in 4 modes).

It has six internal addresses.

It has one chip select pin CS (low).

8156:

It has two numbers of 8-bit parallel I/O port (port-A and B)

One number of 6-bit parallel 1 port (port-C).

It has 14 bit timer (operating in 4 modes).

It has six internal addresses.

It has one chip select pin CS (low).

34

Page 35: Mpmc 11 Marks

Fig - Internal address of 8156

8255:

It has 3 numbers of 8-bit parallel I/O ports (port A, B and C).

Port-A can be programmed in mode-0 mode-1 or mode-2 as input or output port.

Port-B can be programmed in mode-1 and mode-2 as 1/Oport.

When ports A and B are in mode-0, the port-C can be used as I/O port.

One logic low chip select (CS) pin.

It requires four internal addresses

8355:

It has 2KB ROM.

It has two number of 8 bit port (A,B).

It has one CS(low).

It has four internal addresses.

8755:

It has 2Kb EPROM.

It has two number of 8 bit port (A,B).

It has one CS(low).

It has four internal addresses.

35

Page 36: Mpmc 11 Marks

Fig - Internal address of 8255

Fig - Internal address of 8355

Fig - Internal address of 8755

2.) DISCUSS ABOUT PROGRAMMABLE INTERRUPT CONTROLLER - INTEL 8259

FEATURES OF 8259:

1. It is programmed to work with either 8085 or 8086 processor.

2. It manage 8-interrupts according to the instructions written into its control registers.

3. In 8086 processor, it supplies the type number of the interrupt and the type number is

programmable. In 8085 processor, the interrupt vector address is programmable. The priorities of

the interrupts are programmable.

4. The interrupts can be masked or unmasked individually.

36

Page 37: Mpmc 11 Marks

5. The 8259s can be cascaded to accept a maximum of 64 interrupts.

FUNCTIONAL BLOCK DIAGRAM OF 8259:

It has eight functional blocks. They are,

1. Control logic

2. Read Write logic

3. Data bus buffer

4. Interrupt Request Register (IRR)

5. In-Service Register (ISR)

6. Interrupt Mask Register (IMR)

7. Priority Resolver (PR)

8. Cascade buffer.

The data bus and its buffer are used for the following activities.

1. The processor sends control word to data bus buffer through D0-D7.

2. The processor read status word from data bus buffer through D0-D7

3. From the data bus buffer the 8259 send type number (in case of 8086) or the call opcode

and address (in case of 8085) through D0-D7 to the processor.

The processor uses the RD (low), WR (low) and A0 to read or write 8259.

The 8259 is selected by CS (low).

The IRR has eight input lines (IR0-IR7) for interrupts. When these lines go high, the

request is stored in IRR. It registers a request only if the interrupt is unmasked.

37

Page 38: Mpmc 11 Marks

Normally IR0 has highest priority and IR7 has the lowest priority. The priorities of the

interrupt request input are also programmable.

First the 8259 should be programmed by sending Initialization Command Word (ICW)

and Operational Command Word (OCW). These command words will inform 8259 about

the following,

Type of interrupt signal (Level triggered / Edge triggered).

2. Type of processor (8085/8086).

3. Call address and its interval (4 or 8)

4. Masking of interrupts.

5. Priority of interrupts.

6. Type of end of interrupts.

The interrupt mask register (IMR) stores the masking bits of the interrupt lines to be

masked. The relevant information is send by the processor through OCW.

The in-service register keeps track of which interrupt is currently being serviced.

The priority resolver examines the interrupt request, mask and in-service registers and

determines whether INT signal should be sent to the processor or not.

The cascade buffer/comparator is used to expand the interrupts of 8259.

In cascade connection one 8259 will be directly interrupting 8086 and it is called master

8259.

To each interrupt request input of master 8259 (IR0-IR7), one slave 8259 can be

connected. The 8259s interrupting the master 8259 are called slave 8259s.

38

Page 39: Mpmc 11 Marks

Each 8259 has its own addresses so that each 8259 can be programmed independently by

sending command words and independently the status bytes can be read from it.

3.) DISCUSS ABOUT PERIPHERAL INTERFACING - PPI INTERFACING (8255)

Peripheral Interfacing is considered to be a main part of Microprocessor, as it is the only way to

interact with the external world. The interfacing happens with the ports of the Microprocessor.

The main IC's which are to be interfaced with 8085 are:

1. 8255 PPI

2. 8259 PIC

3. 8251 USART

4. 8279 Key board display controller

5. 8253 Timer/ Counter

6. A/D and D/A converter interfacing.

PROGRAMMABLE PERIPHERAL INTERFACE - INTEL 8255

Pins, Signals and internal block diagram of 8255:

It has 40 pins and requires a single +5V supply.

The INTEL 8255 is a device used to parallel data transfer between processor and slow

peripheral devices like ADC, DAC, keyboard, 7-segment display, LCD, etc.

The 8255 has three ports: Port-A, Port-B and Port-C.

Port-A can be programmed to work in any one of the three operating modes mode-0,

mode-1 and mode-2 as input or output port.

Port-B can be programmed to work either in mode-0 or mode-1 as input or output port.

Port-C (8-pins) has different assignments depending on the mode of port-A and port-B.

If port-A and B are programmed in mode-0, then the port-C can perform any one of the

following functions.

39

Page 40: Mpmc 11 Marks

As 8-bit parallel port in mode-0 for input or output.

As two numbers of 4-bit parallel ports in mode-0 for input or output.

The individual pins of port-C can be set or reset for various control applications.

If port-A is programmed in mode- 1/mode-2 and port-B is programmed in mode-1 then

some of the pins of port-C are used for handshake signals and the remaining pins can be

used as input/ output lines or individually set/reset for control applications.

The read/write control logic requires six control signals. These signals are given below.

1. RD (low): This control signal enables the read operation. When this signal is low, the

microprocessor reads data from a selected I/O port of the 8255A.

2. WR (low): This control signal enables the write operation. When this signal goes low, the

microprocessor writes into a selected I/O port or the control register.

3. RESET: This is an active high signal. It clears the control register and set all ports in the input

mode.

4. CS (low), A0 and A1: These are device select signals. They are,

Interfacing of 8255 with 8085 processor:

A simple schematic for interfacing the 8255 with 8085 processor is shown in fig.

PIN DESCRIPTION - INTEL 8255

40

Page 41: Mpmc 11 Marks

41

Page 42: Mpmc 11 Marks

Block diagram of 8255:

The internal block diagram of 8255 is shown in fig:

42

Page 43: Mpmc 11 Marks

The 8255 can be either memory mapped or I/O mapped in the system. In the schematic

shown in above is I/O mapped in the system.

Using a 3-to-8 decoder generates the chip select signals for I/O mapped devices.

The address lines A4, A5 and A6 are decoded to generate eight chip select signals (IOCS-

0 to IOCS-7) and in this, the chip select IOCS- 1 is used to select 8255.

The address line A7 and the control signal IO/M (low) are used as enable for the decoder.

The address line A0 of 8085 is connected to A0 of 8255 and A1 of 8085 is connected to

A1 of 8255 to provide the internal addresses.

The data lines D0-D7 are connected to D0-D7 of the processor to achieve parallel data

transfer.

The I/O addresses allotted to the internal devices of 8255 are listed in table.

43

Page 44: Mpmc 11 Marks

5.) DISCUSS ABOUT INTERFACING WITH INTEL 8251A (USART)

The 8251A is a programmable serial communication interface chip designed for

synchronous and asynchronous serial data communication.

It supports the serial transmission of data.

It is packed in a 28 pin DIP.

It is packed in a 28 pin DIP.

44

Page 45: Mpmc 11 Marks

Read/Write control logic:

The Read/Write Control logic interfaces the 8251A with CPU, determines the functions

of the 8251A according to the control word written into its control register.

It monitors the data flow.

This section has three registers and they are control register, status register and data

buffer.

The active low signals RD, WR, CS and C/D(Low) are used for read/write operations

with these three registers.

45

Page 46: Mpmc 11 Marks

When C/D(low) is high, the control register is selected for writing control word or

reading status word.

When C/D(low) is low, the data buffer is selected for read/write operation.

When the reset is high, it forces 8251A into the idle mode.

The clock input is necessary for 8251A for communication with CPU and this clock does

not control either the serial transmission or the reception rate.

Transmitter section:

The transmitter section accepts parallel data from CPU and converts them into serial data.

The transmitter section is double buffered, i.e., it has a buffer register to hold an 8-bit

parallel data and another register called output register to convert the parallel data into

serial bits.

When output register is empty, the data is transferred from buffer to output register. Now

the processor can again load another data in buffer register.

If buffer register is empty, then TxRDY is goes to high.

If output register is empty then TxEMPTY goes to high.

The clock signal, TxC (low) controls the rate at which the bits are transmitted by the

USART.

The clock frequency can be 1,16 or 64 times the baud rate.

Receiver Section:

The receiver section accepts serial data and convert them into parallel data

46

Page 47: Mpmc 11 Marks

The receiver section is double buffered, i.e., it has an input register to receive serial data

and convert to parallel, and a buffer register to hold the parallel data.

When the RxD line goes low, the control logic assumes it as a START bit, waits for half

a bit time and samples the line again.

If the line is still low, then the input register accepts the following bits, forms a character

and loads it into the buffer register.

The CPU reads the parallel data from the buffer register.

When the input register loads a parallel data to buffer register, the RxRDY line goes high.

The clock signal RxC (low) controls the rate at which bits are received by the USART.

During asynchronous mode, the signal SYNDET/BRKDET will indicate the break in the

data transmission.

During synchronous mode, the signal SYNDET/BRKDET will indicate the reception of

synchronous character.

MODEM Control:

The MODEM control unit allows to interface a MODEM to 8251A and to establish data

communication through MODEM over telephone lines.

This unit takes care of handshake signals for MODEM interface.

The 825 1A can be either memory mapped or I/O mapped in the system.

8251A in I/O mapped in the system is shown in the figure.

Using a 3-to-8 decoder generates the chip select signals for I/O mapped devices.

The address lines A4, A5 and A6 are decoded to generate eight chip select signals (IOCS-

0 to IOCS-7) and in this, the chip select signal IOCS-2 is used to select 8251A.

47

Page 48: Mpmc 11 Marks

The address line A7 and the control signal IO / M(low) are used as enable for decoder.

The address line A0 of 8085 is connected to C/D(low) of 8251A to provide the internal

addresses.

The data lines D0 - D7 are connected to D0 - D7 of the processor to achieve parallel data

transfer.

The RESET and clock signals are supplied by the processor. Here the processor clock is

directly connected to 8251A. This clock controls the parallel data transfer between the

processor and 8251A.

The output clock signal of 8085 is divided by suitable clock dividers like programmable

timer 8254 and then used as clock for serial transmission and reception.

The TTL logic levels of the serial data lines and the control signals necessary for serial

transmission and reception are converted to RS232 logic levels using MAX232 and then

terminated on a standard 9-pin D-.type connector.

In 8251A the transmission and reception baud rates can be different or same.

The device which requires serial communication with processor can be connected to this

9-pin D-type connector using 9-core cable

The signals TxEMPTY, TxRDY and RxRDY can be used as interrupt signals to initiate

interrupt driven data transfer scheme between processor and 8251 A.

I/O addresses of 8251A interfaced to 8085 is,

48

Page 49: Mpmc 11 Marks

49

Page 50: Mpmc 11 Marks

6. Architechture of 8086 / Functional Block diagram of 8086

8086 has two blocks Bus Interfacing Unit(BIU) and Execution Unit(EU).

The BIU performs all bus operations such as instruction fetching, reading and writing

operands for memory and calculating the addresses of the memory operands. The

instruction bytes are transferred to the instruction queue.

EU executes instructions from the instruction system byte queue.

Both units operate asynchronously to give the 8086 an overlapping instruction fetch and

execution mechanism which is called as Pipelining. This results in efficient use of the

system bus and system performance.

BIU contains Instruction queue, Segment registers, Instruction pointer, Address adder.

EU contains Control circuitry, Instruction decoder, ALU, Pointer and Index register,Flag

register.

50

Page 51: Mpmc 11 Marks

Explanation of Architechture of 8086

BUS INTERFACE UNIT:

It provides a full 16 bit bidirectional data bus and 20 bit address bus.

The bus interface unit is responsible for performing all external bus operations.

Specifically it has the following functions:

Instruction fetch, Instruction queuing, Operand fetch and storage, Address relocation and

Bus control.

The BIU uses a mechanism known as an instruction stream queue to implement a

pipeline architecture.

51

Page 52: Mpmc 11 Marks

This queue permits prefetch of up to six bytes of instruction code. When ever the queue

of the BIU is not full, it has room for at least two more bytes and at the same time the EU

is not requesting it to read or write operands from memory, the BIU is free to look ahead

in the program by prefetching the next sequential instruction.

These prefetching instructions are held in its FIFO queue. With its 16 bit data bus, the

BIU fetches two instruction bytes in a single memory cycle.

After a byte is loaded at the input end of the queue, it automatically shifts up through the

FIFO to the empty location nearest the output.

The EU accesses the queue from the output end. It reads one instruction byte after the

other from the output of the queue. If the queue is full and the EU is not requesting access

to operand in memory.

These intervals of no bus activity, which may occur between bus cycles are known as Idle

state.

If the BIU is already in the process of fetching an instruction when the EU request it to

read or write operands from memory or I/O, the BIU first completes the instruction fetch

bus cycle before initiating the operand read / write cycle.

The BIU also contains a dedicated adder which is used to generate the 20bit physical

address that is output on the address bus. This address is formed by adding an appended

16 bit segment address and a 16 bit offset address.

For example: The physical address of the next instruction to be fetched is formed by

combining the current contents of the code segment CS register and the current contents

of the instruction pointer IP register.

The BIU is also responsible for generating bus control signals such as those for memory

read or write and I/O read or write.

EXECUTION UNIT

The Execution unit is responsible for decoding and executing all instructions.

52

Page 53: Mpmc 11 Marks

The EU extracts instructions from the top of the queue in the BIU, decodes them,

generates operands if necessary, passes them to the BIU and requests it to perform the

read or write bys cycles to memory or I/O and perform the operation specified by the

instruction on the operands.

During the execution of the instruction, the EU tests the status and control flags and

updates them based on the results of executing the instruction.

If the queue is empty, the EU waits for the next instruction byte to be fetched and shifted

to top of the queue.

When the EU executes a branch or jump instruction, it transfers control to a location

corresponding to another set of sequential instructions.

Whenever this happens, the BIU automatically resets the queue and then begins to fetch

instructions from this new location to refill the queue.

General purpose registers

The 8086 microprocessor has a total of fourteen registers that are accessible to the programmer.

It is divided into four groups. They are:

Four General purpose registers

Four Index/Pointer registers

Four Segment registers

Two Other registers

General purpose registers :

Accumulator register consists of two 8-bit registers AL and AH, which can be combined

together and used as a 16-bit register AX. AL in this case contains the loworder byte of the word,

53

Page 54: Mpmc 11 Marks

and AH contains the high-order byte. Accumulator can be used for I/O operations and string

manipulation.

Base register consists of two 8-bit registers BL and BH, which can be combined together and

used as a 16-bit register BX. BL in this case contains the low-order byte of the word, and BH

contains the high-order byte. BX register usually contains a data pointer used for based, based

indexed or register indirect addressing.

Count register consists of two 8-bit registers CL and CH, which can be combined together and

used as a 16-bit register CX. When combined, CL register contains the loworder byte of the

word, and CH contains the high-order byte. Count register can be used in Loop, shift/rotate

instructions and as a counter in string manipulation

Data register consists of two 8-bit registers DL and DH, which can be combined together and

used as a 16-bit register DX. When combined, DL register contains the low order byte of the

word, and DH contains the high-order byte. Data register can be used as a port number in I/O

operations. In integer 32-bit multiply and divide instruction the DX register contains high-order

word of the initial or resulting number.

7.)Features of 80286 80286: Intel introduced 80286 in 1982.• With 16-bit internal and external data bus.• 24-bit address bus (224 = 16 megabyte)• virtual memory: a way of fooling the microprocessor into thinking that it has access to unlimitedmemory by swapping data between disk storage and RAM.• Real mode (faster operation with maximum of 1 Mbytes of memory) vs. Protected modeprotecting the operating system for accidental or deliberate destruction of the user. Protectedmode is slower but can use 16 Mbytes of memory.

interrupts:

Definition: The meaning of ‘interrupts’ is to break the sequence of operation.While the cpu is

executing a program,on ‘interrupt’ breaks the normal sequence of execution of instructions,

diverts its execution to some other program called Interrupt Service Routine (ISR).After

executing ISR , the control is transferred back again to the main program.Interrupt processing is

an alternative to polling.

54

Page 55: Mpmc 11 Marks

Need for Interrupt: Interrupts are particularly useful when interfacing I/O devices, that provide

or require data at relatively low data transfer rate.

Types of Interrupts: There are two types of Interrupts in 8086. They are:

(i)Hardware Interrupts and

(ii)Software Interrupts

(i) Hardware Interrupts (External Interrupts). The Intel microprocessors support hardware

interrupts through:

Two pins that allow interrupt requests, INTR and NMI

One pin that acknowledges, INTA, the interrupt requested on INTR.

INTR and NMI

INTR is a maskable hardware interrupt. The interrupt can be enabled/disabled using

STI/CLI instructions or using more complicated method of updating the FLAGS register

with the help of the POPF instruction.

When an interrupt occurs, the processor stores FLAGS register into stack, disables further

interrupts, fetches from the bus one byte representing interrupt type, and jumps to

interrupt processing routine address of which is stored in location 4 * <interrupt type>.

Interrupt processing routine should return with the IRET instruction.

NMI is a non-maskable interrupt. Interrupt is processed in the same way as the INTR

interrupt. Interrupt type of the NMI is 2, i.e. the address of the NMI processing routine is

stored in location 0008h. This interrupt has higher priority than the maskable interrupt.

– Ex: NMI, INTR.

(ii) Software Interrupts (Internal Interrupts and Instructions) .Software interrupts can be

caused by:

INT instruction - breakpoint interrupt. This is a type 3 interrupt.

INT <interrupt number> instruction - any one interrupt from available 256 interrupts.

INTO instruction - interrupt on overflow

55

Page 56: Mpmc 11 Marks

Single-step interrupt - generated if the TF flag is set. This is a type 1 interrupt. When the

CPU processes this interrupt it clears TF flag before calling the interrupt processing

routine.

Processor exceptions: Divide Error (Type 0), Unused Opcode (type 6) and Escape opcode

(type 7).

Software interrupt processing is the same as for the hardware interrupts.

- Ex: INT n (Software Instructions)

Control is provided through:

o IF and TF flag bits

o IRET and IRETD

Performance of Hardware Interrupts

NMI : Non maskable interrupts - TYPE 2 Interrupt

INTR : Interrupt request - Between 20H and FFH

Interrupt Priority Structure

Performance of Software Interrupts

56

Page 57: Mpmc 11 Marks

1. It decrements SP by 2 and pushes the flag register on the stack. 2. Disables INTR by clearing the IF. 3. It resets the TF in the flag Register. 5. It decrements SP by 2 and pushes CS on the stack. 6. It decrements SP by 2 and pushes IP on the stack. 6. Fetch the ISR address from the interrupt vector table.

8.Minimum and Maximum mode configuration of 8086:

Maximum Mode 8086 System

In the maximum mode, the 8086 is operated by strapping the MN/MX pin to ground.

In this mode, the processor derives the status signal S2, S1, S0. Another chip called bus

controller derives the control signal using this status information .

In the maximum mode, there may be more than one microprocessor in the system

configuration.

The components in the system are same as in the minimum mode system.

The basic function of the bus controller chip IC8288, is to derive control signals like RD

and WR ( for memory and I/O devices), DEN, DT/R, ALE etc. using the information by

the processor on the status lines.

The bus controller chip has input lines S2, S1, S0 and CLK. These inputs to 8288 are

driven by CPU.

It derives the outputs ALE, DEN, DT/R, MRDC, MWTC, AMWC, IORC, IOWC and

AIOWC. The AEN, IOB and CEN pins are specially useful for multiprocessor systems.

57

Page 58: Mpmc 11 Marks

AEN and IOB are generally grounded. CEN pin is usually tied to +5V. The significance

of the MCE/PDEN output depends upon the status of the IOB pin.

If IOB is grounded, it acts as master cascade enable to control cascade 8259A, else it acts

as peripheral data enable used in the multiple bus configurations.

INTA pin used to issue two interrupt acknowledge pulses to the interrupt controller or to

an interrupting device.

IORC, IOWC are I/O read command and I/O write command signals respectively.

These signals enable an IO interface to read or write the data from or to the address port.

The MRDC, MWTC are memory read command and memory write command signals

respectively and may be used as memory read or write signals.

All these command signals instructs the memory to accept or send data from or to the

bus.

For both of these write command signals, the advanced signals namely AIOWC and

AMWTC are available.

58

Page 59: Mpmc 11 Marks

Here the only difference between in timing diagram between minimum mode and

maximum mode is the status signals used and the available control and advanced

command signals.

R0, S1, S2 are set at the beginning of bus cycle.8288 bus controller will output a pulse as

on the ALE and apply a required signal to its DT / R pin during T1.

In T2, 8288 will set DEN=1 thus enabling transceivers, and for an input it will activate

MRDC or IORC. These signals are activated until T4. For an output, the AMWC or

AIOWC is activated from T2 to T4 and MWTC or IOWC is activated from T3 to T4.

The status bit S0 to S2 remains active until T3 and become passive during T3 and T4.

If reader input is not activated before T3, wait state will be inserted between T3 and T4.

Minimum Mode 8086 System

In a minimum mode 8086 system, the microprocessor 8086 is operated in minimum

mode by strapping its MN/MX pin to logic 1.

In this mode, all the control signals are given out by the microprocessor chip itself.There

is a single microprocessor in the minimum mode system.

The remaining components in the system are latches, transreceivers, clock generator,

memory and I/O devices. Some type of chip selection logic may be required for selecting

memory or I/O devices, depending upon the address map of the system.

Latches are generally buffered output D-type flip-flops like 74LS373 or 8282. They are

used for separating the valid address from the multiplexed address/data signals and are

controlled by the ALE signal generated by 8086.

Transreceivers are the bidirectional buffers and some times they are called as data

amplifiers. They are required to separate the valid data from the time multiplexed

address/data signals.

They are controlled by two signals namely, DEN and DT/R.

The DEN signal indicates the direction of data, i.e. from or to the processor. The system

contains memory for the monitor and users program storage.

59

Page 60: Mpmc 11 Marks

Usually, EPROM are used for monitor storage, while RAM for users program storage. A

system may contain I/O devices.

RQ/GT Timings in Maximum Mode

The request/grant response sequence contains a series of three pulses. The request/grant

pins are checked at each rising pulse of clock input.

When a request is detected and if the condition for HOLD request are satisfied, the

processor issues a grant pulse over the RQ/GT pin immediately during T4 (current) or T1

(next) state.

When the requesting master receives this pulse, it accepts the control of the bus, it sends a

release pulse to the processor using RQ/GT pin.

Maximum Mode Interface

When the 8086 is set for the maximum-mode configuration, it provides signals for

implementing a multiprocessor / coprocessor system environment.

By multiprocessor environment we mean that one microprocessor exists in the system

and that each processor is executing its own program.

Usually in this type of system environment, there are some system resources that are

common to all processors.They are called as global resources. There are also other

resources that are assigned to specific processors. These are known as local or private

resources.

60

Page 61: Mpmc 11 Marks

Coprocessor also means that there is a second processor in the system. In this two

processor does not access the bus at the same time. One passes the control of the system

bus to the other and then may suspend its operation.

In the maximum-mode 8086 system, facilities are provided for implementing allocation

of global resources and passing bus control to other microprocessor or coprocessor.

9.Addressing Modes of 8086

Definition: An instruction acts on any number of operands.The way an instruction accesses its

operands is called its Addressing modes.

Operands may be of three types :

o Implicit

o Explicit

61

Page 62: Mpmc 11 Marks

o Both Implicit and Explicit.

Implicit operands mean that the instruction by definition has some specific operands. The

programmers do NOT select these operands.

Example: Implicit operands

XLAT ; automatically takes AL and BX as operands AAM ; it operates on the contents of AX.

Explicit operands mean the instruction operates on the operands specified by the programmer.

Example: Explicit operands

MOV AX, BX; it takes AX and BX as operands XCHG SI, DI; it takes SI and DI as operands

Implicit and explicit operands

Example: Implicit/Explicit operands

MUL BX; automatically multiply BX explicitly times AX

The location of an operand value in memory space is called the Effective Address (EA)

We can classify the addressing modes of 8086 into four groups:

Immediate addressing

Register addressing

Memory addressing

I/O port addressing

The first three Addresssing modes are clearly explained.

Immediate addressing mode & Register addressing mode

Immediate Addressing Mode

62

Page 63: Mpmc 11 Marks

In this addressing mode, the operand is stored as part of the instruction. The immediate operand,

which is stored along with the instruction, resides in the code segment -- not in the data segment.

This addressing mode is also faster to execute an instruction because the operand is read with the

instruction from memory. Here are some examples:

Example: Immediate Operands

MOV AL, 20 ; move the constant 20 into register AL ADD AX, 5 ; add constant 5 to register EAX MOV DX, offset msg ; move the address of message to register DX

Register addressing mode

In this addressing mode, the operands may be:

reg16: 16-bit general registers: AX, BX, CX, DX, SI, DI, SP or BP.

reg8 : 8-bit general registers: AH, BH, CH, DH, AL, BL, CL, or DL.

Sreg : segment registers: CS, DS, ES, or SS. There is an exception: CS cannot be a

destination.

For register addressing modes, there is no need to compute the effective address. The operand is

in a register and to get the operand there is no memory access involved.

Example: Register Operands

MOV AX, BX ; mov reg16, reg16 ADD AX, SI ; add reg16, reg16 MOV DS, AX ; mov Sreg, reg16

Some rules in register addressing modes:

1. You may not specify CS as the destination operand.

Example: mov CS, 02h –> wrong

2. Only one of the operands can be a segment register. You cannot move data from one segment

register to another with a single mov instruction. To copy the value of cs to ds, you would have

to use some sequence like:

63

Page 64: Mpmc 11 Marks

mov ds,cs -> wrong

mov ax, cs

mov ds, ax -> the way we do it

You should never use the segment registers as data registers to hold arbitrary values. They

should only contain segment addresses.

Memory Addressing Modes

Memory (RAM) is the main component of a computer to store temporary data and machine

instructions. In a program, programmers many times need to read from and write into memory

locations.

There are different forms of memory addressing modes

1. Direct Addressing

2. Register indirect addressing

3. Based addressing

4. Indexed addressing

5. Based indexed addressing

6. Based indexed with displacement

Direct Addressing Mode

The instruction mov al,ds:[8088h] loads the AL register with a copy of the byte at memory

location 8088h. Likewise, the instruction mov ds:[1234h],dl stores the value in the dl register to

memory location 1234h. By default, all displacement-only values provide offsets into the data

segment. If you want to provide an offset into a different segment, you must use a segment

override prefix before your address. For example, to access location 1234h in the extra segment

(es) you would use an instruction of the form mov ax,es:[1234h]. Likewise, to access this

location in the code segment you would use the instruction mov ax, cs:[1234h]. The ds: prefix in

the previous examples is not a segment override.

64

Page 65: Mpmc 11 Marks

The instruction mov al,ds:[8088h] is same as mov al, [8088h]. If not mentioned DS register is

taken by default.

Register Indirect Addressing Mode

The 80x86 CPUs let you access memory indirectly through a register using the register indirect

addressing modes. There are four forms of this addressing mode on the 8086, best demonstrated

by the following instructions:

mov al, [bx]

mov al, [bp]

mov al, [si]

mov al, [di]

Code Example

MOV BX, 100H

MOV AL, [BX]

65

Page 66: Mpmc 11 Marks

The [bx], [si], and [di] modes use the ds segment by default. The [bp] addressing mode uses the

stack segment (ss) by default. You can use the segment override prefix symbols if you wish to

access data in different segments. The following instructions demonstrate the use of these

overrides:

mov al, cs:[bx]

mov al, ds:[bp]

mov al, ss:[si]

mov al, es:[di]

Intel refers to [bx] and [bp] as base addressing modes and bx and bp as base registers (in fact, bp

stands for base pointer). Intel refers to the [si] and [di] addressing modes as indexed addressing

modes (si stands for source index, di stands for destination index). However, these addressing

modes are functionally equivalent. This text will call these forms register indirect modes to be

consistent.

Based Addressing Mode and Indexed Addressing Modes

Based Addressing Mode

8-bit or 16-bit instruction operand is added to the contents of a base register (BX or BP), the

resulting value is a pointer to location where data resides.

Mov al, [bx],[si]

Mov bl , [bp],[di]

Mov cl , [bp],[di]

Code Example

If bx=1000h

si=0880h

Mov AL, [1000+880]

Mov AL,[1880]

Indexed Addressing Modes

66

Page 67: Mpmc 11 Marks

The indexed addressing modes use the following syntax:

mov al, [bx+disp]

mov al, [bp+disp]

mov al, [si+disp]

mov al, [di+disp]

Code Example

MOV BX, 100H

MOV AL, [BX + 15]

MOV AL, [BX + 16]

If bx contains 1000h, then the instruction mov cl, [bx+20h] will load cl from memory location

ds:1020h. Likewise, if bp contains 2020h, mov dh, [bp+1000h] will load dh from location

ss:3020. The offsets generated by these addressing modes are the sum of the constant and the

specified register. The addressing modes involving bx, si, and di all use the data segment, the

[bp+disp] addressing mode uses the stack segment by default. As with the register indirect

addressing modes, you can use the segment override prefixes to specify a different segment:

mov al, ss:[bx+disp]

mov al, es:[bp+disp]

mov al, cs:[si+disp]

mov al, ss:[di+disp]

Based Indexed Addressing Modes & Based Indexed Plus Displacement Addressing Mode

Based Indexed Addressing Modes

The based indexed addressing modes are simply combinations of the register indirect addressing

modes. These addressing modes form the offset by adding together a base register (bx or bp) and

an index register (si or di). The allowable forms for these addressing modes are:

mov al, [bx+si]

mov al, [bx+di]

67

Page 68: Mpmc 11 Marks

mov al, [bp+si]

mov al, [bp+di]

Code Example

MOV BX, 100H

MOV SI, 200H

MOV AL, [BX + SI]

INC BX

INC SI

Suppose that bx contains 1000h and si contains 880h. Then the instruction mov al,[bx][si] would

load al from location DS:1880h. Likewise, if bp contains 1598h and di contains 1004, mov ax,

[bp+di] will load the 16 bits in ax from locations SS:259C and SS:259D. The addressing modes

that do not involve bp use the data segment by default. Those that have bp as an operand use the

stack segment by default.

Based Indexed Plus Displacement Addressing Mode

These addressing modes are a slight modification of the base/indexed addressing modes with the

addition of an eight bit or sixteen bit constant. The following are some examples of these

addressing modes

68

Page 69: Mpmc 11 Marks

mov al, disp[bx][si]

mov al, disp[bx+di]

mov al, [bp+si+disp]

mov al, [bp][di][disp]

Code Example

MOV BX, 100H

MOV SI, 200H

MOV AL, [BX + SI +100H]

INC BX

INC SI

69

Page 70: Mpmc 11 Marks

UNIT- III

1)DISCUSS THE INTERNAL ARCHITECTURE OF 8051 MICROCONTROLLER.

A struggle has been going on between MCU manufacturers for quite a long time, each of them

trying to best respond to the ever-increasing demands of the market. Every couple of days there

is a brand new chip available, working at higher frequency, with more memory or with better

A/D converters. And yet, a closer look to their interior reveals the same or at least very similar

structural design referred to as “8051 compatibility”. What is it all about? The story began in the

80’s when Intel introduced their microcontroller family MCS 8051 to the market. Although this

family had quite limited capabilities by today’s notions, it quickly captivated the world and

became the standard for what is today understood as ‘microcontroller’. The most significant

cause for such a success can be found in the cleverly chosen configuration which can satisfy a

diversity of needs, yet allowing for continuous upgrades (in form of new controllers). In a brief

period of time, a decent amount of software has been developed for 8051, making further

changes of the hardware core simply uneconomical. Consequently, there is a variety of MCUs

available today, basically just the upgraded 8051 models. What exactly makes this

microcontroller so special and universal that it is still manufactured by all the major companies,

just under a different label?

As can be seen on the image above, there is nothing particularly remarkable about MCU 8051:

4 kilobytes of ROM is neither too little nor too much.

70

Page 71: Mpmc 11 Marks

128 bytes of RAM (SFR registers included) can satisfy the basic needs, but is not really

astounding.

4 ports totaling 32 I/O lines, are usually sufficient for connecting to the environs and are by

no means luxury. Obviously, 8051 configuration is intended to satisfy the needs of programmers

developing the controlling devices and instruments. This is one part of its key to success: there is

nothing missing, yet there is no lavishness; it is meant for the average user. The other clue can be

found in the organization of RAM, Central Processor Unit (CPU), and ports - all of which

maximally utilize the available resources and allow further upgrades.

2.DISCUSS ABOUT SFR S IN DETAIL

The 8051 is a flexible microcontroller with a relatively large number of modes of operations.

Your program may inspect and/or change the operating mode of the 8051 by manipulating the

values of the 8051's Special Function Registers (SFRs).

SFRs are accessed as if they were normal Internal RAM. The only difference is that Internal

RAM is from address 00h through 7Fh whereas SFR registers exist in the address range of 80h

through FFh.

Each SFR has an address (80h through FFh) and a name. The following chart provides a

graphical presentation of the 8051's SFRs, their names, and their address.

As you can see, although the address range of 80h through FFh offer 128 possible addresses,

there are only 21 SFRs in a standard 8051. All other addresses in the SFR range (80h through

FFh) are considered invalid. Writing to or reading from these registers may produce undefined

values or behavior.

Programming Tip: It is recommended that you not read or write to SFR addresses that

have not been assigned to an SFR. Doing so may provoke undefined behavior and may

cause your program to be incompatible with other 8051-derivatives that use the given

SFR for some other purpose.

SFR Types As mentioned in the chart itself, the SFRs that have a blue background are SFRs

related to the I/O ports. The 8051 has four I/O ports of 8 bits, for a total of 32 I/O lines. Whether

a given I/O line is high or low and the value read from the line are controlled by the SFRs in

green.

71

Page 72: Mpmc 11 Marks

The SFRs with yellow backgrouns are SFRs which in some way control the operation or the

configuration of some aspect of the 8051. For example, TCON controls the timers, SCON

controls the serial port.

The remaining SFRs, with green backgrounds, are "other SFRs." These SFRs can be thought of

as auxillary SFRs in the sense that they don't directly configure the 8051 but obviously the 8051

cannot operate without them. For example, once the serial port has been configured using

SCON, the program may read or write to the serial port using the SBUF register.

Programming Tip: The SFRs whose names appear in red in the chart above are SFRs

that may be accessed via bit operations (i.e., using the SETB and CLR instructions). The

other SFRs cannot be accessed using bit operations. As you can see, all SFRs that whose

addresses are divisible by 8 can be accessed with bit operations.

SFR Descriptions

This section will endeavor to quickly overview each of the standard SFRs found in the above

SFR chart map. It is not the intention of this section to fully explain the functionality of each

SFR--this information will be covered in separate chapters of the tutorial. This section is to just

give you a general idea of what each SFR does.

P0 (Port 0, Address 80h, Bit-Addressable): This is input/output port 0. Each bit of this SFR

corresponds to one of the pins on the microcontroller. For example, bit 0 of port 0 is pin P0.0, bit

7 is pin P0.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding

I/O pin whereas a value of 0 will bring it to a low level.

Programming Tip: While the 8051 has four I/O port (P0, P1, P2, and P3), if your

hardware uses external RAM or external code memory (i.e., your program is stored in an

external ROM or EPROM chip or if you are using external RAM chips) you may not use

P0 or P2. This is because the 8051 uses ports P0 and P2 to address the external memory.

Thus if you are using external RAM or code memory you may only use ports P1 and P3

for your own use.

SP (Stack Pointer, Address 81h): This is the stack pointer of the microcontroller. This SFR

indicates where the next value to be taken from the stack will be read from in Internal RAM. If

you push a value onto the stack, the value will be written to the address of SP + 1. That is to say,

if SP holds the value 07h, a PUSH instruction will push the value onto the stack at address 08h.

72

Page 73: Mpmc 11 Marks

This SFR is modified by all instructions which modify the stack, such as PUSH, POP, LCALL,

RET, RETI, and whenever interrupts are provoked by the microcontroller.

Programming Tip: The SP SFR, on startup, is initialized to 07h. This means the stack

will start at 08h and start expanding upward in internal RAM. Since alternate register

banks 1, 2, and 3 as well as the user bit variables occupy internal RAM from addresses

08h through 2Fh, it is necessary to initialize SP in your program to some other value if

you will be using the alternate register banks and/or bit memory. It's not a bad idea to

initialize SP to 2Fh as the first instruction of every one of your programs unless you are

100% sure you will not be using the register banks and bit variables.

DPL/DPH (Data Pointer Low/High, Addresses 82h/83h): The SFRs DPL and DPH work

together to represent a 16-bit value called the Data Pointer. The data pointer is used in operations

regarding external RAM and some instructions involving code memory. Since it is an unsigned

two-byte integer value, it can represent values from 0000h to FFFFh (0 through 65,535 decimal).

Programming Tip: DPTR is really DPH and DPL taken together as a 16-bit value. In

reality, you almost always have to deal with DPTR one byte at a time. For example, to

push DPTR onto the stack you must first push DPL and then DPH. You can't simply

plush DPTR onto the stack. Additionally, there is an instruction to "increment DPTR."

When you execute this instruction, the two bytes are operated upon as a 16-bit value.

However, there is no instruction that decrements DPTR. If you wish to decrement the

value of DPTR, you must write your own code to do so.

PCON (Power Control, Addresses 87h): The Power Control SFR is used to control the 8051's

power control modes. Certain operation modes of the 8051 allow the 8051 to go into a type of

"sleep" mode which requires much less power. These modes of operation are controlled through

PCON. Additionally, one of the bits in PCON is used to double the effective baud rate of the

8051's serial port.

TCON (Timer Control, Addresses 88h, Bit-Addressable): The Timer Control SFR is used to

configure and modify the way in which the 8051's two timers operate. This SFR controls

whether each of the two timers is running or stopped and contains a flag to indicate that each

timer has overflowed. Additionally, some non-timer related bits are located in the TCON SFR.

These bits are used to configure the way in which the external interrupts are activated and also

contain the external interrupt flags which are set when an external interrupt has occured.

73

Page 74: Mpmc 11 Marks

TMOD (Timer Mode, Addresses 89h): The Timer Mode SFR is used to configure the mode of

operation of each of the two timers. Using this SFR your program may configure each timer to

be a 16-bit timer, an 8-bit autoreload timer, a 13-bit timer, or two separate timers. Additionally,

you may configure the timers to only count when an external pin is activated or to count "events"

that are indicated on an external pin.

TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Ch): These two SFRs, taken together,

represent timer 0. Their exact behavior depends on how the timer is configured in the TMOD

SFR; however, these timers always count up. What is configurable is how and when they

increment in value.

TL1/TH1 (Timer 1 Low/High, Addresses 8Bh/8Dh): These two SFRs, taken together,

represent timer 1. Their exact behavior depends on how the timer is configured in the TMOD

SFR; however, these timers always count up. What is configurable is how and when they

increment in value.

P1 (Port 1, Address 90h, Bit-Addressable): This is input/output port 1. Each bit of this SFR

corresponds to one of the pins on the microcontroller. For example, bit 0 of port 1 is pin P1.0, bit

7 is pin P1.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding

I/O pin whereas a value of 0 will bring it to a low level.

SCON (Serial Control, Addresses 98h, Bit-Addressable): The Serial Control SFR is used to

configure the behavior of the 8051's on-board serial port. This SFR controls the baud rate of the

serial port, whether the serial port is activated to receive data, and also contains flags that are set

when a byte is successfully sent or received.

Programming Tip: To use the 8051's on-board serial port, it is generally necessary to

initialize the following SFRs: SCON, TCON, and TMOD. This is because SCON

controls the serial port. However, in most cases the program will wish to use one of the

timers to establish the serial port's baud rate. In this case, it is necessary to configure

timer 1 by initializing TCON and TMOD.

SBUF (Serial Control, Addresses 99h): The Serial Buffer SFR is used to send and receive data

via the on-board serial port. Any value written to SBUF will be sent out the serial port's TXD

pin. Likewise, any value which the 8051 receives via the serial port's RXD pin will be delivered

74

Page 75: Mpmc 11 Marks

to the user program via SBUF. In other words, SBUF serves as the output port when written to

and as an input port when read from.

P2 (Port 2, Address A0h, Bit-Addressable): This is input/output port 2. Each bit of this SFR

corresponds to one of the pins on the microcontroller. For example, bit 0 of port 2 is pin P2.0, bit

7 is pin P2.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding

I/O pin whereas a value of 0 will bring it to a low level.

Programming Tip: While the 8051 has four I/O port (P0, P1, P2, and P3), if your

hardware uses external RAM or external code memory (i.e., your program is stored in an

external ROM or EPROM chip or if you are using external RAM chips) you may not use

P0 or P2. This is because the 8051 uses ports P0 and P2 to address the external memory.

Thus if you are using external RAM or code memory you may only use ports P1 and P3

for your own use.

IE (Interrupt Enable, Addresses A8h): The Interrupt Enable SFR is used to enable and disable

specific interrupts. The low 7 bits of the SFR are used to enable/disable the specific interrupts,

where as the highest bit is used to enable or disable ALL interrupts. Thus, if the high bit of IE is

0 all interrupts are disabled regardless of whether an individual interrupt is enabled by setting a

lower bit.

P3 (Port 3, Address B0h, Bit-Addressable): This is input/output port 3. Each bit of this SFR

corresponds to one of the pins on the microcontroller. For example, bit 0 of port 3 is pin P3.0, bit

7 is pin P3.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding

I/O pin whereas a value of 0 will bring it to a low level.

IP (Interrupt Priority, Addresses B8h, Bit-Addressable): The Interrupt Priority SFR is used

to specify the relative priority of each interrupt. On the 8051, an interrupt may either be of low

(0) priority or high (1) priority. An interrupt may only interrupt interrupts of lower priority. For

example, if we configure the 8051 so that all interrupts are of low priority except the serial

interrupt, the serial interrupt will always be able to interrupt the system, even if another interrupt

is currently executing. However, if a serial interrupt is executing no other interrupt will be able to

interrupt the serial interrupt routine since the serial interrupt routine has the highest priority.

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

used to store a number of important bits that are set and cleared by 8051 instructions. The PSW

75

Page 76: Mpmc 11 Marks

SFR contains the carry flag, the auxiliary carry flag, the overflow flag, and the parity flag.

Additionally, the PSW register contains the register bank select flags which are used to select

which of the "R" register banks are currently selected.

Programming Tip: If you write an interrupt handler routine, it is a very good idea to

always save the PSW SFR on the stack and restore it when your interrupt is complete.

Many 8051 instructions modify the bits of PSW. If your interrupt routine does not

guarantee that PSW is the same upon exit as it was upon entry, your program is bound to

behave rather erradically and unpredictably--and it will be tricky to debug since the

behavior will tend not to make any sense.

ACC (Accumulator, Addresses E0h, Bit-Addressable): The Accumulator is one of the most-

used SFRs on the 8051 since it is involved in so many instructions. The Accumulator resides as

an SFR at E0h, which means the instruction MOV A,#20h is really the same as MOV

E0h,#20h. However, it is a good idea to use the first method since it only requires two bytes

whereas the second option requires three bytes.

B (B Register, Addresses F0h, Bit-Addressable): The "B" register is used in two instructions:

the multiply and divide operations. The B register is also commonly used by programmers as an

auxiliary register to temporarily store values.

Other SFRs

The chart above is a summary of all the SFRs that exist in a standard 8051. All derivative

microcontrollers of the 8051 must support these basic SFRs in order to maintain compatability

with the underlying MSCS51 standard.

A common practice when semiconductor firms wish to develop a new 8051 derivative is to add

additional SFRs to support new functions that exist in the new chip.

For example, the Dallas Semiconductor DS80C320 is upwards compatible with the 8051. This

means that any program that runs on a standard 8051 should run without modification on the

DS80C320. This means that all the SFRs defined above also apply to the Dallas component.

However, since the DS80C320 provides many new features that the standard 8051 does not,

there must be some way to control and configure these new features. This is accomplished by

adding additional SFRs to those listed here. For example, since the DS80C320 supports two

76

Page 77: Mpmc 11 Marks

serial ports (as opposed to just one on the 8051), the SFRs SBUF2 and SCON2 have been added.

In addition to all the SFRs listed above, the DS80C320 also recognizes these two new SFRs as

valid and uses their values to determine the mode of operation of the secondary serial port.

Obviously, these new SFRs have been assigned to SFR addresses that were unused in the

original 8051. In this manner, new 8051 derivative chips may be developed which will run

existing 8051 programs.

Programming Tip: If you write a program that utilizes new SFRs that are specific to a

given derivative chip and not included in the above SFR list, your program will not run

properly on a standard 8051 where that SFR does not exist. Thus, only use non-standard

SFRs if you are sure that your program wil only have to run on that specific

microcontroller. Likewise, if you write code that uses non-standard SFRs and

subsequently share it with a third-party, be sure to let that party know that your code is

using non-standard SFRs to save them the headache of realizing that due to strange

behavior at run-time.

3.) DISCUSS THE BASIC REGISTERS OF 8051.

The Accumulator

If you’ve worked with any other assembly languages you will be familiar with the concept of an

Accumulator register.

The Accumulator, as it’s name suggests, is used as a general register to accumulate the results of

a large number of instructions. It can hold an 8-bit (1-byte) value and is the most versatile

register the 8051 has due to the shear number of instructions that make use of the accumulator.

More than half of the 8051’s 255 instructions manipulate or use the accumulator in some way.

For example, if you want to add the number 10 and 20, the resulting 30 will be stored in the

Accumulator. Once you have a value in the Accumulator you may continue processing the value

or you may store it in another register or in memory.

The "R" registers

The "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7.

These registers are used as auxillary registers in many operations. To continue with the above

example, perhaps you are adding 10 and 20. The original number 10 may be stored in the

77

Page 78: Mpmc 11 Marks

Accumulator whereas the value 20 may be stored in, say, register R4. To process the addition

you would execute the command:

ADD A,R4

After executing this instruction the Accumulator will contain the value 30.

You may think of the "R" registers as very important auxillary, or "helper", registers. The

Accumulator alone would not be very useful if it were not for these "R" registers.

The "R" registers are also used to temporarily store values. For example, let’s say you want to

add the values in R1 and R2 together and then subtract the values of R3 and R4. One way to do

this would be:

MOV A,R3 ;Move the value of R3 into the accumulator ADD A,R4 ;Add the value of

R4 MOV R5,A ;Store the resulting value temporarily in R5 MOV A,R1 ;Move the value

of R1 into the accumulator ADD A,R2 ;Add the value of R2 SUBB A,R5 ;Subtract the

value of R5 (which now contains R3 + R4)

As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this isn’t the

most efficient way to calculate (R1+R2) - (R3 +R4) but it does illustrate the use of the "R"

registers as a way to store values temporarily.

The "B" Register

The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte)

value.

The "B" register is only used by two 8051 instructions: MUL AB and DIV AB. Thus, if you

want to quickly and easily multiply or divide A by another number, you may store the other

number in "B" and make use of these two instructions.

Aside from the MUL and DIV instructions, the "B" register is often used as yet another temporary storage register much like a ninth "R" register.

4.)DISCUSS ABOUT THE ADDRESSING MODES OF 8051.

An "addressing mode" refers to how you are addressing a given memory location. In summary,

the addressing modes are as follows, with an example of each:

Immediate Addressing MOV A,#20h

Direct Addressing MOV A,30h

78

Page 79: Mpmc 11 Marks

Indirect Addressing MOV A,@R0

External Direct MOVX A,@DPTR

Code Indirect MOVC A,@A+DPTR

Each of these addressing modes provides important flexibility.

Immediate Addressing

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

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

will be stored in memory.

For example, the instruction:

MOV A,#20h

This instruction uses Immediate Addressing because the Accumulator will be loaded with the

value that immediately follows; in this case 20 (hexidecimal).

Immediate addressing is very fast since the value to be loaded is included in the instruction.

However, since the value to be loaded is fixed at compile-time it is not very flexible.

Direct Addressing

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

retrieving it from another memory location. For example:

MOV A,30h

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

the Accumulator.

Direct addressing is generally fast since, although the value to be loaded isn’t included in the

instruction, it is quickly accessable since it is stored in the 8051’s Internal RAM. It is also much

more flexible than Immediate Addressing since the value to be loaded is whatever is found at the

given address--which may be variable.

Also, it is important to note that when using direct addressing any instruction which refers to an

address between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an

79

Page 80: Mpmc 11 Marks

address between 80h and FFh is referring to the SFR control registers that control the 8051

microcontroller itself.

The obvious question that may arise is, "If direct addressing an address from 80h through FFh

refers to SFRs, how can I access the upper 128 bytes of Internal RAM that are available on the

8052?" The answer is: You can’t access them using direct addressing. As stated, if you directly

refer to an address of 80h through FFh you will be referring to an SFR. However, you may

access the 8052’s upper 128 bytes of RAM by using the next addressing mode, "indirect

addressing."

Indirect Addressing

Indirect addressing is a very powerful addressing mode which in many cases provides an

exceptional level of flexibility. Indirect addressing is also the only way to access the extra 128

bytes of Internal RAM found on an 8052.

Indirect addressing appears as follows:

MOV A,@R0

This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load

the accumulator with the value from Internal RAM which is found at the address indicated by

R0.

For example, let’s say R0 holds the value 40h and Internal RAM address 40h holds the value

67h. When the above instruction is executed the 8051 will check the value of R0. Since R0 holds

40h the 8051 will get the value out of Internal RAM address 40h (which holds 67h) and store it

in the Accumulator. Thus, the Accumulator ends up holding 67h.

Indirect addressing always refers to Internal RAM; it never refers to an SFR. Thus, in a prior

example we mentioned that SFR 99h can be used to write a value to the serial port. Thus one

may think that the following would be a valid solution to write the value ‘1’ to the serial port:

MOV R0,#99h ;Load the address of the serial port MOV @R0,#01h ;Send 01 to the

serial port -- WRONG!!

This is not valid. Since indirect addressing always refers to Internal RAM these two instructions

would write the value 01h to Internal RAM address 99h on an 8052. On an 8051 these two

80

Page 81: Mpmc 11 Marks

instructions would produce an undefined result since the 8051 only has 128 bytes of Internal

RAM.

External Direct

External Memory is accessed using a suite of instructions which use what I call "External Direct"

addressing. I call it this because it appears to be direct addressing, but it is used to access external

memory rather than internal memory.

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

MOVX A,@DPTR MOVX @DPTR,A

As you can see, both commands utilize DPTR. In these instructions, DPTR must first be loaded

with the address of external memory that you wish to read or write. Once DPTR holds the correct

external memory address, the first command will move the contents of that external memory

address into the Accumulator. The second command will do the opposite: it will allow you to

write the value of the Accumulator to the external memory address pointed to by DPTR.

External Indirect

External memory can also be accessed using a form of indirect addressing which I call External

Indirect addressing. This form of addressing is usually only used in relatively small projects that

have a very small amount of external RAM. An example of this addressing mode is:

MOVX @R0,A

Once again, the value of R0 is first read and the value of the Accumulator is written to that

address in External RAM. Since the value of @R0 can only be 00h through FFh the project

would effectively be limited to 256 bytes of External RAM. There are relatively simple

hardware/software tricks that can be implemented to access more than 256 bytes of memory

using External Indirect addressing; however, it is usually easier to use External Direct addressing

if your project has more than 256 bytes of External RAM.

5.)EXPLAIN ABOUT THE INTERRUPTS IN 8051

An interrupt is a special feature which allows the 8051 to provide the illusion of "multi-tasking,"

although in reality the 8051 is only doing one thing at a time. The word "interrupt" can often be

subsituted with the word "event."

81

Page 82: Mpmc 11 Marks

An interrupt is triggered whenever a corresponding event occurs. When the event occurs, the

8051 temporarily puts "on hold" the normal execution of the program and executes a special

section of code referred to as an interrupt handler. The interrupt handler performs whatever

special functions are required to handle the event and then returns control to the 8051 at which

point program execution continues as if it had never been interrupted.

The topic of interrupts is somewhat tricky and very important. For that reason, an entire chapter

will be dedicated to the topic. For now, suffice it to say that Interrupts can cause program flow to

change.

Interrupts

As the name implies, an interrupt is some event which interrupts normal program execution.

As stated earlier, program flow is always sequential, being altered only by those instructions

which expressly cause program flow to deviate in some way. However, interrupts give us a

mechanism to "put on hold" the normal program flow, execute a subroutine, and then resume

normal program flow as if we had never left it. This subroutine, called an interrupt handler, is

only executed when a certain event (interrupt) occurs. The event may be one of the timers

"overflowing," receiving a character via the serial port, transmitting a character via the serial

port, or one of two "external events." The 8051 may be configured so that when any of these

events occur the main program is temporarily suspended and control passed to a special section

of code which presumably would execute some function related to the event that occured. Once

complete, control would be returned to the original program. The main program never even

knows it was interrupted.

The ability to interrupt normal program execution when certain events occur makes it much

easier and much more efficient to handle certain conditions. If it were not for interrupts we

would have to manually check in our main program whether the timers had overflown, whether

we had received another character via the serial port, or if some external event had occured.

Besides making the main program ugly and hard to read, such a situation would make our

program inefficient since we’d be burning precious "instruction cycles" checking for events that

usually don’t happen.

82

Page 83: Mpmc 11 Marks

For example, let’s say we have a large 16k program executing many subroutines performing

many tasks. Let’s also suppose that we want our program to automatically toggle the P3.0 port

every time timer 0 overflows. The code to do this isn’t too difficult:

JNB TF0,SKIP_TOGGLE CPL P3.0 CLR TF0 SKIP_TOGGLE: ...

Since the TF0 flag is set whenever timer 0 overflows, the above code will toggle P3.0 every time

timer 0 overflows. This accomplishes what we want, but is inefficient. The JNB instruction

consumes 2 instruction cycles to determine that the flag is not set and jump over the unnecessary

code. In the event that timer 0 overflows, the CPL and CLR instruction require 2 instruction

cycles to execute. To make the math easy, let’s say the rest of the code in the program requires

98 instruction cycles. Thus, in total, our code consumes 100 instruction cycles (98 instruction

cycles plus the 2 that are executed every iteration to determine whether or not timer 0 has

overflowed). If we’re in 16-bit timer mode, timer 0 will overflow every 65,536 machine cycles.

In that time we would have performed 655 JNB tests for a total of 1310 instruction cycles, plus

another 2 instruction cycles to perform the code. So to achieve our goal we’ve spent 1312

instruction cycles. So 2.002% of our time is being spent just checking when to toggle P3.0. And

our code is ugly because we have to make that check every iteration of our main program loop.

Luckily, this isn’t necessary. Interrupts let us forget about checking for the condition. The

microcontroller itself will check for the condition automatically and when the condition is met

will jump to a subroutine (called an interrupt handler), execute the code, then return. In this case,

our subroutine would be nothing more than:

CPL P3.0 RETI

First, you’ll notice the CLR TF0 command has disappeared. That’s because when the 8051

executes our "timer 0 interrupt routine," it automatically clears the TF0 flag. You’ll also notice

that instead of a normal RET instruction we have a RETI instruction. The RETI instruction does

the same thing as a RET instruction, but tells the 8051 that an interrupt routine has finished. You

must always end your interrupt handlers with RETI.

Thus, every 65536 instruction cycles we execute the CPL instruction and the RETI instruction.

Those two instructions together require 3 instruction cycles, and we’ve accomplished the same

goal as the first example that required 1312 instruction cycles. As far as the toggling of P3.0

goes, our code is 437 times more efficient! Not to mention it’s much easier to read and

83

Page 84: Mpmc 11 Marks

understand because we don’t have to remember to always check for the timer 0 flag in our main

program. We just setup the interrupt and forget about it, secure in the knowledge that the 8051

will execute our code whenever it’s necessary.

The same idea applies to receiving data via the serial port. One way to do it is to continuously

check the status of the RI flag in an endless loop. Or we could check the RI flag as part of a

larger program loop. However, in the latter case we run the risk of missing characters--what

happens if a character is received right after we do the check, the rest of our program executes,

and before we even check RI a second character has come in. We will lose the first character.

With interrupts, the 8051 will put the main program "on hold" and call our special routine to

handle the reception of a character. Thus, we neither have to put an ugly check in our main code

nor will we lose characters.

6.)WHAT IS SERIAL COMMUNICATION

One of the 8051’s many powerful features is it’s integrated UART, otherwise known as a serial

port. The fact that the 8051 has an integrated serial port means that you may very easily read and

write values to the serial port. If it were not for the integrated serial port, writing a byte to a serial

line would be a rather tedious process requring turning on and off one of the I/O lines in rapid

succession to properly "clock out" each individual bit, including start bits, stop bits, and parity

bits.

However, we do not have to do this. Instead, we simply need to configure the serial port’s

operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a

value to the serial port or read the same SFR to read a value from the serial port. The 8051 will

automatically let us know when it has finished sending the character we wrote and will also let

us know whenever it has received a byte so that we can process it. We do not have to worry

about transmission at the bit level--which saves us quite a bit of coding and processing time.

Setting the Serial Port Mode

The first thing we must do when using the 8051’s integrated serial port is, obviously, configure

it. This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how

the baud rate will be determined.

84

Page 85: Mpmc 11 Marks

First, let’s present the "Serial Control" (SCON) SFR and define what each bit of the SFR

represents:

Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:

(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.

The SCON SFR allows us to configure the Serial Port. Thus, we’ll go through each bit and

review it’s function.

The first four bits (bits 4 through 7) are configuration bits.

Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The four

modes are defined in the chart immediately above. As you can see, selecting the Serial Mode

selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also determines how the

baud rate will be calculated. In modes 0 and 2 the baud rate is fixed based on the oscillator’s

frequency. In modes 1 and 3 the baud rate is variable based on how often Timer 1 overflows.

We’ll talk more about the various Serial Modes in a moment.

85

Page 86: Mpmc 11 Marks

The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a byte

has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the program know

that a byte has been received and that it needs to be processed. However, when SM2 is set the

"RI" flag will only be triggered if the 9th bit received was a "1". That is to say, if SM2 is set and

a byte is received whose 9th bit is clear, the RI flag will never be set. This can be useful in

certain advanced serial applications. For now it is safe to say that you will almost always want to

clear this bit so that the flag is set upon reception of any character.

The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to receive

data via the serial port, set this bit. You will almost always want to set this bit.

The last four bits (bits 0 through 3) are operational bits. They are used when actually sending and

receiving data--they are not used to configure the serial port.

The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are transmitted.

The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken from TB8. If TB8

is set and a value is written to the serial port, the data’s bits will be written to the serial line

followed by a "set" ninth bit. If TB8 is clear the ninth bit will be "clear."

The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8, but on

the reception side. When a byte is received in modes 2 or 3, a total of nine bits are received. In

this case, the first eight bits received are the data of the serial byte received and the value of the

ninth bit received will be placed in RB8.

TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain

amount of time will pass before the individual bits of the byte are "clocked out" the serial port. If

the program were to write another byte to the serial port before the first byte was completely

output, the data being sent would be garbled. Thus, the 8051 lets the program know that it has

"clocked out" the last byte by setting the TI bit. When the TI bit is set, the program may assume

that the serial port is "free" and ready to send the next byte.

Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, but it indicates

that a byte has been received. That is to say, whenever the 8051 has received a complete byte it

will trigger the RI bit to let the program know that it needs to read the value quickly, before

another byte is read.

86

Page 87: Mpmc 11 Marks

Setting the Serial Port Baud Rate

Once the Serial Port Mode has been configured, as explained above, the program must configure

the serial port’s baud rate. This only applies to Serial Port modes 1 and 3. The Baud Rate is

determined based on the oscillator’s frequency when in mode 0 and 2. In mode 0, the baud rate is

always the oscillator frequency divided by 12. This means if you’re crystal is 11.059Mhz, mode

0 baud rate will always be 921,583 baud. In mode 2 the baud rate is always the oscillator

frequency divided by 64, so a 11.059Mhz crystal speed will yield a baud rate of 172,797.

In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The more

frequently timer 1 overflows, the higher the baud rate. There are many ways one can cause timer

1 to overflow at a rate that determines a baud rate, but the most common method is to put timer 1

in 8-bit auto-reload mode (timer mode 2) and set a reload value (TH1) that causes Timer 1 to

overflow at a frequency appropriate to generate a baud rate.

To determine the value that must be placed in TH1 to generate a given baud rate, we may use the

following equation (assuming PCON.7 is clear).

TH1 = 256 - ((Crystal / 384) / Baud)

If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:

TH1 = 256 - ((Crystal / 192) / Baud)

For example, if we have an 11.059Mhz crystal and we want to configure the serial port to 19,200

baud we try plugging it in the first equation:

TH1 = 256 - ((Crystal / 384) / Baud) TH1 = 256 - ((11059000 / 384) / 19200 ) TH1 = 256

- ((28,799) / 19200) TH1 = 256 - 1.5 = 254.5

As you can see, to obtain 19,200 baud on a 11.059Mhz crystal we’d have to set TH1 to 254.5. If

we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we will have achieved

28,800 baud. Thus we’re stuck...

But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD). When we do

this we double the baud rate and utilize the second equation mentioned above. Thus we have:

TH1 = 256 - ((Crystal / 192) / Baud) TH1 = 256 - ((11059000 / 192) / 19200) TH1 = 256 -

((57699) / 19200) TH1 = 256 - 3 = 253

Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud with an

11.059MHz crystal we must:

87

Page 88: Mpmc 11 Marks

1. Configure Serial Port mode 1 or 3. 2. Configure Timer 1 to timer mode 2 (8-bit auto-

reload). 3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud. 4. Set

PCON.7 (SMOD) to double the baud rate.

Writing to the Serial Port

Once the Serial Port has been propertly configured as explained above, the serial port is ready to

be used to send data and receive data. If you thought that configuring the serial port was simple,

using the serial port will be a breeze.

To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR. For

example, if you wanted to send the letter "A" to the serial port, it could be accomplished as easily

as:

MOV SBUF,#’A’

Upon execution of the above instruction the 8051 will begin transmitting the character via the

serial port. Obviously transmission is not instantaneous--it takes a measureable amount of time to

transmit. And since the 8051 does not have a serial output buffer we need to be sure that a

character is completely transmitted before we try to transmit the next character.

The 8051 lets us know when it is done transmitting a character by setting the TI bit in SCON.

When this bit is set we know that the last character has been transmitted and that we may send

the next character, if any. Consider the following code segment:

CLR TI ;Be sure the bit is initially clear MOV SBUF,#’A’ ;Send the letter ‘A’ to the

serial port JNB TI,$ ;Pause until the TI bit is set.

The above three instructions will successfully transmit a character and wait for the TI bit to be

set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$, in most

assemblers, means "the same address of the current instruction." Thus the 8051 will pause on the

JNB instruction until the TI bit is set by the 8051 upon successful transmission of the character.

Reading the Serial Port

Reading data received by the serial port is equally easy. To read a byte from the serial port one

just needs to read the value stored in the SBUF (99h) SFR after the 8051 has automatically set

the RI flag in SCON.

88

Page 89: Mpmc 11 Marks

For example, if your program wants to wait for a character to be received and subsequently read

it into the Accumulator, the following code segment may be used:

JNB RI,$ ;Wait for the 8051 to set the RI flag MOV A,SBUF ;Read the character from

the serial port

The first line of the above code segment waits for the 8051 to set the RI flag; again, the 8051 sets

the RI flag automatically when it receives a character via the serial port. So as long as the bit is

not set the program repeats the "JNB" instruction continuously.

Once the RI bit is set upon character reception the above condition automatically fails and

program flow falls through to the "MOV" instruction which reads the value.

89

Page 90: Mpmc 11 Marks

PIC Microcontrollers

Introduction to PIC Microcontrollers

PIC stands for Peripheral Interface Controller given by Microchip Technology to identify its single-chip microcontrollers. These devices have been very successful in 8-bit microcontrollers. The main reason is that Microchip Technology has continuously upgraded the device architecture and added needed peripherals to the microcontroller to suit customers' requirements..

The architectures of various PIC microcontrollers can be divided as follows.

Low - end PIC Architectures :

Microchip PIC microcontrollers are available in various types. When PIC microcontroller MCU was first available from General Instruments in early 1980's, the microcontroller consisted of a simple processor executing 12-bit wide instructions with basic I/O functions. These devices are known as low-end architectures. They have limited program memory and are meant for applications requiring simple interface functions and small program & data memories. Some of the low-end device numbers are

12C5XX 16C5X 16C505

Mid range PIC Architectures

Mid range PIC architectures are built by upgrading low-end architectures with more number of peripherals, more number of registers and more data/program memory. Some of the mid-range devices are

16C6X 16C7X 16F87X

Program memory type is indicated by an alphabet. C = EPROM

90

Page 91: Mpmc 11 Marks

F = Flash RC = Mask ROM

Popularity of the PIC microcontrollers is due to the following factors.

1. Speed: Harvard Architecture, RISC architecture, 1 instruction cycle = 4 clock cycles. 2. Instruction set simplicity: The instruction set consists of just 35 instructions (as opposed

to 111 instructions for 8051). 3. Power-on-reset and brown-out reset. Brown-out-reset means when the power supply goes

below a specified voltage (say 4V), it causes PIC to reset; hence malfunction is avoided. A watch dog timer (user programmable) resets the processor if the software/program ever malfunctions and deviates from its normal operation.

4. PIC microcontroller has four optional clock sources. o Low power crystal o Mid range crystalo High range crystalo RC oscillator (low cost).

5. Programmable timers and on-chip ADC.6. Up to 12 independent interrupt sources.7. Powerful output pin control (25 mA (max.) current sourcing capability per pin.)8. EPROM/OTP/ROM/Flash memory option.9. I/O port expansion capability. 10. Free assembler and simulator support from Microchip at www.microchip.com

CPU Architecture: The CPU uses Harvard architecture with separate Program and Variable (data) memory interface. This facilitates instruction fetch and the operation on data/accessing of variables simultaneously.

Fig : CPU Architecture of PIC microcontroller PIC Memory Organisation:

PIC microcontroller has 13 bits of program memory address. Hence it can address up to 8k of program memory. The program counter is 13-bit. PIC 16C6X or 16C7X program memory is 2k or 4k. While addressing 2k of program memory, only 11- bits are required. Hence two most significant bits of the program counter are ignored. Similarly, while addressing 4k of memory, 12 bits are required. Hence the MSb of the program counter is ignored.

91

Page 92: Mpmc 11 Marks

Fig : Program Memory map

The program memory map of PIC16C74A is shown in Fig 16.2. On reset, the program counter is cleared and the program starts at 00H. Here a 'goto' instruction is required that takes the processor to the mainline program.

When a peripheral interrupt, that is enabled, is received, the processor goes to 004H. A suitable branching to the interrupt service routine (ISR) is written at 004H.

Data memory (Register Files): Data Memory is also known as Register File. Register File consists of two components.

1. General purpose register file (same as RAM). 2. Special purpose register file (similar to SFR in 8051).

92

Page 93: Mpmc 11 Marks

Fig : Data Memory map

The special purpose register file consists of input/output ports and control registers. Addressing from 00H to FFH requires 8 bits of address. However, the instructions that use direct addressing modes in PIC to address these register files use 7 bits of instruction only. Therefore the register bank select (RP0) bit in the STATUS register is used to select one of the register banks.

In indirect addressing FSR register is used as a pointer to anywhere from 00H to FFH in the data memory.

Basic Architecture of PIC Microcontrollers Specifications of some popular PIC microcontrollers are as follows: Device Program

Memory (14bits)

Data RAM (bytes)

I/O Pins

ADC Timers 8/16 bits

CCP (PWM)

USART SPI / I2C

16C74A 4K EPROM 192 33 8 bits x 8 channels

2/1 2 USART SPI / I2C

16F877 8K Flash 368 (RAM) 256 (EEPROM)

33 10 bits x 8 channels

2/1 2 USART SPI / I2C

Device Interrupt Sources

Instruction Set

16C74A 12 35 16F877 15 35

PIC Microcontroller Clock

Most of the PIC microcontrollers can operate upto 20MHz. One instructions cycle (machine cycle) consists of four clock cycles.

Fig : Relation between instruction cycles and clock cycles for PIC microcontrollers

Instructions that do not require modification of program counter content get executed in one instruction cycle.

Although the architectures of various midrange 8 - bit PIC microcontroller are not the same, the variation is mostly interns of addition of memory and peripherals. We will discuss here the

93

Page 94: Mpmc 11 Marks

architecture of a standard mid-range PIC microcontroller, 16C74A. Unless mentioned otherwise, the information given here is for a PIC 16C74A microcontroller Chip. Architecture of PIC16C74A

Fig : Basic Architecture of PIC 16C74A

The basic architecture of PIC16C74A is shown in fig 17.2. The architecture consists of Program memory, file registers and RAM, ALU and CPU registers. It should be noted that the program Counter is 13 - bit and the program memory is organised as 14 - bit word. Hence the program Memory capacity is 8k x 14 bit. Each instruction of PIC 16C74A is 14 - bit long. The various CPU registers are discussed here.

CPU registers (registers commonly used by the CPU)

W, the working register, is used by many instructions as the source of an operand. This is similar to accumulator in 8051. It may also serve as the destination for the result of the instruction execution. It is an 8 - bit register.

94

Page 95: Mpmc 11 Marks

Fig : W register STATUS Register

The STATUS register is a 8-bit register that stores the status of the processor. This also stores carry, zero and digit carry bits.

STATUS - address 03H, 83H

Fig : STATUS register

C = Carry bit DC = Digit carry (same as auxiliary carry) Z = Zero bit NOT_TO and NOT_PD - Used in conjunction with PIC's sleep mode RP0- Register bank select bit used in conjunction with direct addressing mode.

FSR Register

(File Selection Register, address = 04H, 84H) FSR is an 8-bit register used as data memory address pointer. This is used in indirect addressing mode.

INDF Register

(INDirect through FSR, address = 00H, 80H) INDF is not a physical register. Accessing INDF access is the location pointed to by FSR in indirect addressing mode.

PCL Register

(Program Counter Low Byte, address = 02H, 82H) PCL is actually the lower 8-bits of the 13-bit program counter. This is a both readable and writable register.

PCLATH Register

(Program Counter Latch, address = 0AH, 8AH) PCLATH is a 8-bit register which can be used to decide the upper 5bits of the program counter. PCLATH is not the upper 5bits of the program counter. PCLATH can be read from or written to without affecting the program counter. The upper 3bits of PCLATH remain zero and they serve no purpose. When PCL is written to, the lower 5bits of PCLATH are automatically loaded to the upper 5bits of the program counter, as shown in the figure.

95

Page 96: Mpmc 11 Marks

Fig : Schematic of how PCL is loaded from PCLATH

Program Counter Stack

An independent 8-level stack is used for the program counter. As the program counter is 13bit, the stack is organized as 8x13bit registers. When an interrupt occurs, the program counter is pushed onto the stack. When the interrupt is being serviced, other interrupts remain disabled. Hence, other 7 registers of the stack can be used for subroutine calls within an interrupt service routine or within the mainline program.

Register File Map

96

Page 97: Mpmc 11 Marks

Fig : Register File Map

97

Page 98: Mpmc 11 Marks

It can be noted that some of the special purpose registers are available both in Bank-0 and Bank-1. These registers have the same value in both banks. Changing the register content in one bank automatically changes its content in the other bank.

Port Structure and Pin Configuration of PIC 16C74A

As mentioned earlier, there is a large variety of PIC microcontrollers. However, the midrange architectures are widely used. Our discussion will mainly confine to PIC16C74A whose architecture has most of the required features of a mid-range PIC microcontroller. Study of any other mid-range PIC microcontroller will not cause much variation from the basic architecture of PIC 16C74A ..

PIC 16C74A has 5 I/O Ports. Each port is a bidirectional I/O port. In addition, they have the following alternate functions.

In addition to I/O pins, there is a Master clear pin (MCLR) which is equivalent to reset in 8051. However, unlike 8051, MCLR should be pulled low to reset the micro controller. Since PIC16C74Ahas inherent power-on reset, no special connection is required with MCLR pin to reset the micro controller on power-on.

There are two VDD pins and two VSS pins. There are two pins (OSC1 and OSC2) for connecting the crystal oscillator/ RC oscillator. Hence the total number of pins with a 16C74A is 33+7=40. This IC is commonly available in a dual-in-pin (DIP) package.

98

Page 99: Mpmc 11 Marks

Fig : Pin configuration of PIC 16C74A

Instruction Set of PIC Microcontroller Guidelines from Microchip Technology

For writing assembly language program Microchip Technology has suggested the following guidelines.

1. Write instruction mnemonics in lower case. (e.g., movwf) 2. Write the special register names, RAM variable names and bit names in upper case. (e.g.,

PCL, RP0, etc.) 3. Write instructions and subroutine labels in mixed case. (e.g., Mainline, LoopTime)

Instruction Set:

The instruction set for PIC16C74A consists of only 35 instructions. Some of these instructions are byte oriented instructions and some are bit oriented instructions.

The byte oriented instructions that require two parameters (For example, movf f, F(W)) expect the f to be replaced by the name of a special purpose register (e.g., PORTA) or the name of a RAM variable (e.g., NUM1), which serves as the source of the operand. 'f' stands for file register. The F(W) parameter is the destination of the result of the operation. It should be replaced by:

F, if the destination is to be the source register. W, if the destination is to be the working register (i.e., Accumulator or W register).

99

Page 100: Mpmc 11 Marks

The bit oriented instructions also expect parameters (e.g., btfsc f, b). Here 'f' is to be replaced by the name of a special purpose register or the name of a RAM variable. The 'b' parameter is to be replaced by a bit number ranging from 0 to 7.

For example:

Z equ 2 btfsc STATUS, Z

Z has been equated to 2. Here, the instruction will test the Z bit of the STATUS register and will skip the next instruction if Z bit is clear.

The literal instructions require an operand having a known value (e.g., 0AH) or a label that represents a known value.

For example:

NUM equ 0AH ; Assigns 0AH to the label NUM ( a constant ) movlw NUM ; will move 0AH to the W register.

Every instruction fits in a single 14-bit word. In addition, every instruction also executes in a single cycle, unless it changes the content of the Program Counter. These features are due to the fact that PIC micro controller has been designed on the principles of RISC (Reduced Instruction Set Computer) architecture.

Instruction set:

Mnemonics Description Instruction

Cycles bcf f, b Clear bit b of register f 1 bsf f, b Set bit b of register f 1 clrw Clear working register W 1 clrf f Clear f 1 movlw k Move literal 'k' to W 1 movwf f Move W to f 1 movf f, F(W) Move f to F or W 1 swapf f, F(W) Swap nibbles of f, putting result in F or W 1 andlw k And literal value into W 1 andwf f, F(W) And W with F and put the result in W or F 1 andwf f, F(W) And W with F and put the result in W or F 1 iorlw k inclusive-OR literal value into W 1 iorwf f, F(W) inclusive-OR W with f and put the result in F or W 1 xorlw k Exclusive-OR literal value into W 1 xorwf f, F(W) Exclusive-OR W with f and put the result in F or W 1 addlw k Add the literal value to W and store the result in W 1

100

Page 101: Mpmc 11 Marks

addwf f, F(W) Add W to f and store the result in F or W 1

sublw k Subtract the literal value from W and store the result in W

1

subwf f, F(W) Subtract f from W and store the result in F or W 1

rlf f, F(W) Copy f into F or W; rotate F or W left through the carry bit

1

rrf f, F(W) Copy f into F or W; rotate F or W right through the carry bit

1

btfsc f, b Test 'b' bit of the register f and skip the next instruction if bit is clear

1 / 2

btfss f, b Test 'b' bit of the register f and skip the next instruction if bit is set

1 / 2

decfsz f, F(W) Decrement f and copy the result to F or W; skip the next instruction if the result is zero

1 / 2

incfcz f, F(W) Increment f and copy the result to F or W; skip the next instruction if the result is zero

1 / 2

goto label Go to the instruction with the label "label" 2

call label Go to the subroutine "label", push the Program Counter in the stack

2

retrun Return from the subroutine, POP the Program Counter from the stack

2

retlw k Retrun from the subroutine, POP the Program Counter from the stack; put k in W

2

retie Return from Interrupt Service Routine and re-enable interrupt

2

clrwdt Clear Watch Dog Timer 1 sleep Go into sleep/ stand by mode 1 nop No operation 1

Encoding of instruction:

As has been discussed, each instruction is of 14-bit long. These 14-bits contain both op-code and the operand. Some examples of instruction encoding are shown here.

Example-1:

bcf f, b Clear 'b' bit of register 'f'

Operands: 0 ≤ f ≤ 127 0 ≤ b ≤ 7

Encoding:

101

Page 102: Mpmc 11 Marks

The instruction is executed in one instruction cycle, i.e., 4 clock cycles. The activities in various clock cycles are as follows.

Example-2:

goto K Go to label 'k' instruction

Operand: 0 ≤ K ≤ 2047 (11-bit address is specified) Operation: K PC <10:0>

PCLATH <4:3> PC <12:11> Encoding:

Since this instruction requires modification of program Counter, it takes two instruction cycles for execution.

Q-Cycle activities are shown as follows.

102

Page 103: Mpmc 11 Marks

I/O Port Configuration I/O ports of PIC16C74A:

PIC16C74A has five I/O ports. Port-B, Port-C and Port-D have 8 pins each. Port-A and Port-E have 6 and 3 pins respectively. Each port has bidirectional digital I/O capability. In addition, these I/O ports are multiplexed with alternate functions for the peripheral devices on the microcontroller. In general, when a peripheral is enabled, that pin may not be used as a general purpose I/O pin. Each port latch has a corresponding TRIS (Tri-state Enable) register for configuring the port either as an input or as an output. The port pins are designated by the alphabet R, followed by the respective port (viz. A, B, C, D or E) and the pin number. For example, Port-A pins are named as RA0, RA1, etc.

Port-A

Port-A pins RA0-RA3 and RA5 are similar. These pins function (alternate function) as analog inputs to the analog-to-digital converter.

Fig : RA0-RA3 and RA5 pin of Port-A

The structure of Port-A pins RA0-RA3 and RA5 is shown in the figure. TRISA register decides whether the port-pin is configured as an input or as an output (digital) pin. Setting a TRISA register bit puts the corresponding output driver in high impedance mode. In this mode, the pin can be used as a digital or analog input. Clearing a bit in the TRISA register puts the contents of

103

Page 104: Mpmc 11 Marks

the data latch on the selected pins, i.e., the pin functions as a digital output. Pins RA0-RA and RA5 have current sourcing capability of 25mA.

The alternate function of RA4 pin is Timer-0 clock input (T0CKI). RA4 pin is an open drain pin and hence requires external pull-up when configured as output pin. It is shown in the following figure.

Fig : RA4 pin Configuration Configuration of Port-A pins Example : Set RA0-RA3 as outputs and RA4 - RA5 as inputs. bcf STATUS, RP0 ; Select Bank-0 clrf PORTA ; Clears the data latch bsf STATUS, RP0 ; Select Bank-1

movlw 30H ; W 03H ( data direction ) movwf TRISA ; Set RA0-RA3 as outputs, RA4-RA5 as inputs

Port-B

Port-B is an 8-bit bidirectional I/O port. The data direction in Port-B is controlled by TRISB register. Setting a bit in TRISB register puts the corresponding output in high impedance input mode. When a bit in TRISB is made zero, the corresponding pin in Port-B outputs the content of the latch (output mode).

Each port pin has a weak internal pull-up that can be enabled by clearing bit of OPTION register (bit-7). When a pin is configured in the output mode, the weak pull-up is automatically turned off. Internal pull-up is used so that we can directly drive a device from the pins.

104

Page 105: Mpmc 11 Marks

Fig : Pins RB0-RB3 of Port-B

Configuration of Port-B pins Example : Set RB0-RB3 as outputs, RB4-RB5 as inputs, RB7 as output.

bcf STATUS, RP0 clrf PORTB bsf STATUS, RP0 movlw 70H movwf TRISB

Timer modules in PIC MicrocontrollerOverview of Timer Modules :

PIC 16C74A has three modules, viz., Timer-0, Timer-1 and Timer-2. Timer-0 and Timer-2 are 8-bit timers. Timer-1 is a 16-bit timer. Each timer module can generate an interrupt on timer overflow.

Timer-0 Overview:

The timer-0 module is a simple 8-bit UP counter. The clock source can be either the internal clock (fosc /4) or an external clock. When the clock source is external, the Timer-0 module can be

105

Page 106: Mpmc 11 Marks

programmed to increment on either the rising or falling clock edge. Timer-0 module has a programmable pre-scaler option. This pre-scaler can be assigned either to Timer-0 or the Watch dog timer, but not to both.

The Timer-0 Counter sets a flag T0IF (Timer-0 Interrupt Flag) when it overflows and can cause an interrupt at that time if that interrupt source has been enabled, (T0IE = 1), i.e., timer-0 interrupt enable bit = 1.

OPTION Register Configuration : Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock source. The following OPTION register configuration is for clock source = fosc /4 and no Watchdog timer.

Timer-0 use without pre-scalar

Internal clock source of f osc /4. (External clock source, if selected, can be applied at RA4/TOCKI input at PORTA).

The following diagram shows the timer use without the prescaler.

Fig : Timer - 0 operation without prescaler

Timer-0 use with pre-scalar:

106

Page 107: Mpmc 11 Marks

The pre-scalar can be used either with the Timer-0 module or with the Watchdog timer. The pre-scalar is available for Timer-0 if the pre-scalar assignment bit PSA in the OPTION register is 0. Pre-scalar is a programmable divide by n counter that divides the available clock by a pre-specified number before applying to the Timer-0 counter.

Fig : Timer - 0 with prescaler

Timer - 1 Module

Timer 1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) which are readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments from 0000H to FFFFH and rolls over to 0000H. The TMR1 interrupt, if enabled, is generated on overflow, which sets the interrupt flag bit TMR1IF (bit-0 of PIR1 register). This interrupt can be enabled/disabled by setting/clearing TMR1 interrupt enable bit TMR1IE (bit-0 of the PIE1 register).

The operating and control modes of Timer1 are determined by the special purpose register T1CON.

Various bits of T1CON register are given as follows:-

107

Page 108: Mpmc 11 Marks

Fig : T1CON Register

TMR1 ON : Timer1 ON bit 0 = stops Timer 1; 1 = Enables Timer 1 TMR1CS : Timer 1 Clock source Select Bit 1 = External Clock (RCO/T1OSO/T1CKI)

0 = Internal Clock ( ) : Timer 1 External Clock Input Synchronization Bit (Valid if TMR1CS = 1) 1 - Do not synchronize 0 - Synchronize

T1OSCEN: Oscillator enable control bit 1 = Oscillator is enabled 0 = Oscillator is shut off

Timer 1 Input Clock Prescaler

Select bits Prescaler Value T1CKPS1 T1CKPS0

1 1 1:8 1 0 1:4 0 1 1:2 0 0 1:1

Fig : Operation of Timer 1

108

Page 109: Mpmc 11 Marks

Timer 1 can operate in one of the two modes

As a timer (TMR1CS = 0). In the timer mode, Timer 1 increments in every instruction

cycle. The timer 1 clock source is . Since the internal clock is selected, the timer is always synchronized and there is no further need of synchronization.

As a counter (TMR1CS = 1). In the counter mode, external clock input from the pin RCO/T1CKI is selected.

Reading and writing Timer 1

Reading TMR1H and TMR1L from Timer 1, when it is running from an external clock source, have to be done with care. Reading TMR1H or TMR1L for independent 8 - bit values does not pose any problem. When the 16-bit value of the Timer is required, the high byte (TMR1H) is read first followed by the low byte (THR1lL). It should be ensured that TMR1L does not overflow (that is goes from FFH to 00H) since THR1H was read. This condition is verified by reading TMR1H once again and comparing with previous value of TMR1H.

Example Program Reading 16bit of free running Timer 1

movf TMR1H ; read high byte movwf TMPH ; store in TMPH movf TMR1L ; read low byte movwf TMPL ; store in TMPL movf TMR1H, W ; read high byte in W subwf TMPH, W ; subtract 1 st read with 2 nd read btfsc STATUS, Z ; and check for equality goto next ;; if the high bytes differ, then there is an overflow ; read the high byte again followed by the low byte movf TMR1H, W ; read high byte movwf TMPH movf TMR1L, W ; read low byte movwf TMPL next : nop

109

Page 110: Mpmc 11 Marks

Timer 2 Overview

Fig : Schematic diagram showing operation of Timer 2

Timer 2 is an 8 - bit timer with a pre-scaler and a post-scaler. It can be used as the PWM time base for PWM mode of capture compare PWM (CCP) modules. The TMR2 register is readable and writable and is cleared on device reset.

The input clock ( ) has a pre-scaler option of 1:1, 1:4 or 1:16 which is selected by bit 0 and bit 1 of T2CON register respectively.

The Timer 2 module has an 8bit period register (PR2). Timer-2 increments from 00H until it is equal to PR2 and then resets to 00H on the next clock cycle. PR2 is a readable and writable register. PR2 is initailised to FFH on reset.

The output of TMR2 goes through a 4bit post-scaler (1:1, 1:2, to 1:16) to generate a TMR2 interrupt by setting TMR2IF.

110

Page 111: Mpmc 11 Marks

Fig : The T2CON Register

Interrupt Logic in PIC 16C74A

PIC 16C74A microcontroller has one vectored interrupt location (i.e., 0004H) but has 12 interrupt sources. There is no interrupt priority. Only one interrupt is served at a time. However interrupts can be masked. The interrupt logic is shown below :

Fig : Schematic diagram showing the interrupt logic for PIC

111

Page 112: Mpmc 11 Marks

CCP Modules Capture / Compare /PWM (CCP) Modules:

PIC16C74A has two CCP Modules. Each CCP module contains a 16 bit register (two 8-bit registers) and can operate in one of the three modes, viz., 16-bit capture, 16-bit compare, or up to 10-bit Pulse Width Modulation (PWM). The details of the two modules (CCP1 and CCp2) are given as follows.

CCP1 Module:

CCP1 Module consists of two 8-bit registers, viz., CCPR1L (low byte) and CCPR1H (high byte). The CCP1CON register controls the operation of CCP1 Module.

CCP2 Module:

CCP2 Module consists of two 8 bit registers, viz., CCPR2L (Low byte) and CCPR2H (high byte). The CCP1CON register controls the operation of CCP2 Module.

Both CCP1 and CCP2 modules are identical in operation with the exception of the operation of special event trigger.

The following table shows the timer resources for the CCP Mode.

CCP Mode Timer Used Capture

Compare

PWM

Timer 1

Timer 1

Timer 2 CCP1CON Register (Address 17H )

CCP2CON Register is exactly similar to CCP1CON register. CCP2CON Register address is 1DH. CCP1CON controls CCP module1 where as CCP2CON controls CCP Module2.

Bit 5-4: CCP1X CCP1Y: PWM least significant bits. These bits are of no use in Capture mode. In PWM Mode, these bits are the two Lsbs of the PWM duty cycle. The eight Msbs are found in CCPR1L. Thus the PWM mode operates in 10-bit mode.

112

Page 113: Mpmc 11 Marks

CCP1X CCP1Y: PWM least significant bits. These bits are of no use in Capture mode. In PWM Mode, these bits are the two Lsbs of the PWM duty cycle. The eight Msbs are found in CCPR1L. Thus the PWM mode operates in 10-bit mode. Bit 3-0:CCP1M3:CCP1MO (CCP1 Mode select bits) 0000=Capture/Compare/PWM Mode off 0100=Capture mode, every falling edge 0101=Capture mode, every rising edge0110=Capture mode, every 4 th rising edge 0111=Capture mode, every 16 th rising edge 1000=Compare mode, set output on match (CCP1IF bit is set) 1001=Compare mode, clear output on match (CCP1IF bit is set) 1010=Compare mode, generate software interrupt on match (CCP1IF bit is set, CCP1 pin unaffected) 1011=Compare mode, trigger special event (CCP1IF bit is set;CCP1 resets Tmr1; CCP2 resets TMR1 and starts A/D conversion if A/D module is Enabled) 11XX=PWM mode.

Capture Mode (CCP1):

Capture Mode captures the 16-bit value of TMR1 into CCPR1H:CCPR1L register pair in response to an event occurring on RC2/CCP1 pin. Capture Mode for CCP2 is exactly similar to that of CCP1.

An event on RC2/CCP1 pin is defined as follows:

Every falling edge Every rising edge. Every 4 th rising edge. Every 16 th rising edge.

As mentioned earlier, this event is decided by bit 3-0 of CCP1CON register.

Schematic diagram for capture mode of operation

Fig : Capture operation

113

Page 114: Mpmc 11 Marks

Required condition for capture mode:

1. RC2/CCP1 pin should be configured as an input by setting TRISC (bit 2). 2. Timer 1 should be operated from the internal clock (fosc/4), i.e., timer mode or in

synchronized counter mode.

Compare Mode (CCP1)

Compare mode for CCP2 is similar to that of CCP1, except that in special event trigger mode, CCP1 resets TMR1 only, whereas CCP2 resets TMR1 and starts A/D conversion if A/D module is enabled.

In compare mode, the 16-bit CCPR1 register value is compared against TMR1 register pair (TMR1H and TMR1L) value. When a match occurs, the RC2/CCP1 pin is driven high or driven low or remains unchanged as decided by CCP1CON<3:0> bits.

Fig : Compare Operation Required conditions for compare mode

1. RC2/CCP1 pin must be configured as an output by clearing TRISC<2> bit.2. Timer-1 should be operated in timer mode (i.e., internal clock source of fosc/4) or in

synchronized counter mode.

In software interrupt mode, CCP1IF bit is set but CCP1 pin in unaffected. As shown in the figure, in special event trigger mode, both CCP1 and CCP2 intiates an A/D conversion. PWM mode (CCP1) Both CCP1 and CCP2 have similar operation in PWM mode. Here we will discuss PWM with respect to CCP1.In PWM mode, the CCP1 pin produces upto a 10-bit resolution Pulse Width Modulation (PWM) output. RC2/CCP1 pin should be configured in the uotput mode by clearing TRISC<2> bit.The schematic block diagram of CCP1 module in PWM mode is shown in the figure.

114

Page 115: Mpmc 11 Marks

Fig : PWM Operation It can be noted that PR2 (Period Register, 8 bit) decides the PWM period where CCPR1L (8-bits) and CCP1CON <5:4> (2-bits) decide the PWM duty cycle. When TMR2 equals PR2, the SR latch is set and RC2/CCP1 pin is pulled high. In the same time, TMR2 is cleared and the duty cycle value available in CCPR1L is latched to CCPR1H. CCPR1H, CCP1CON <5:4> decide the duty cycle and when this 10-bit ewquals the TMR2+2 prescaler or Q-bits, the SR latch is set and RC2/CCP1 pin is driven low.

A PWM output as shown has a time period. The time for which the output stays high is called duty cycle.

PWM Period

The PWM period is specified by writing to PR2 register. The PWM period can be calculated using the following formula:

115

Page 116: Mpmc 11 Marks

PWM period = [( PR 2) + 1] × 4 × T osc × (TMR2 prescale value) PWM frequency = 1/ PWM period

When TMR2 is equal to PR2, the following events occur on the next increment cycle.

TMR2 is cleared the CCP1 pin is set (if PWM duty cycle is 0 The PWM duty cycle is latched from CCPR1L into CCPR1H

PWM duty cycle

The PWM duty cycle is specified by writing to the CCPR1L register and to CCP1CON < 5 : 4 >

bits. Up to 10-bit resolution is available where CCPR1L contains the eight MSBs and CCP1CON < 5 : 4 > contains the two LSB's. The 10-bit value is represented by CCPR1L : CCP1CON < 5 : 4 >.

The PWM duty cycle is given by PWM duty cycle = (CCPR1L : CCP1CON < 5 : 4 > ). T osc . (TMR2 prescale value) To understand the 10-bit counter configuration from Timer-2, let us first see the counting mechanism of Timer-2, as shown in Fig 22.4.

Fig : Counting mechanism in Timer - 2 If the prescaler is 1, the 10-bit counter is configured as follows

Fig : Prescaler set to divide by one If the prescaler is 4, the 10-bit counter is configured as follows.

Fig : Prescaler programed to divide by four If the prescaler is 16, the 10-bit counter is realized as follows.

Fig : Prescaler programed to divide by 16

116

Page 117: Mpmc 11 Marks

Although CCPR1L and CCP1CON < 5 : 4 > can be written to at anytime, the duty cycle value is not latched into CCPR1H until a match between PR2 and TMR2 occurs. In PWM mode, CCPR1H is a read-only register.

The CCPR1H register and a 2-bit internal latch are used to double buffer the PWM duty cycle. This double buffering is essential for glitchless PWM operation. When the CCPR1H and 2-bit latch match TMR2 concatenated with an internal 2-bit Q clock or 2-bits of prescaler, the CCP1 pin is cleared. Maximum PWM resolution (bits) for a given PWM frequency can be calculated as

If the PWM duty cycle is longer than the PWM period, then the CCP1 pin will not be cleared.

PWM Period and duty cycle calculation

Example:

Desired PWM frequency = 78.125 kHz f osc = 20MHzTMR2 Prescalar = 1

Find the maximum resolution of duty cycle that can be used with a 78.124 kHz frequency and 20 MHz oscillator.

256 = 2PWM Resolution

At most, an 8-bit resolution duty cycle can be obtained from a 78.125 kHz frequency and 20 MHz oscillatorie, 0 CCPR1L : CCP1CON <5 : 4> ≤ 255 .

Any value greater than 255 will result in a 100 % duty cycle. The following table gives the PWM frequency fPWM if fosc = 20MHz

117

Page 118: Mpmc 11 Marks

Duty cycle resolution 10-Bit counter scale PR2 value Prescaler 1 Prescaler 4 Prescaler 16

10 bit 1024 255 19.53 KHz 4.88 kHz 1.22 kHz

≈ 10 bit 1000 249 20kHz 5kHz 1.25kHz

8 bit 256 63 78.125kHz 19.53kHz 4.88kHz

6 bit 64 15 312.5kHz 78.125kHz 19.53kHz

ADC Module An analog-to-digital converter (ADC) converts an analog signal into an equivalent digital number. PIC 16C74A has an inbuilt ADC with the following features -

8-bit conversion 8 analog input channels An analog multiplexer A sample and hold circuit for signal on the selected input channel Alternative clock sources for carrying out conversion Adjustable sampling rate Choice of an internal or external reference voltage Interrupt to microcontroller on end of conversion

Port A and Port E pins are used for analog inputs/reference voltage for ADC. In A/D conversion, the input analog voltage is digitized and an equivalent digital output is generated as shown in the figure.

Fig : Digital output versus analog input

118

Page 119: Mpmc 11 Marks

Port-A pins (Alternate functions)

RA0/AN0 - can be used as analog input-0 RA1/AN1 - can be used as analog input-1 RA2/AN2 - can be used as analog input-2 RA3/AN3/Vref - can be used as analog input-3 or analog reference voltage RA4/TOCKI - clock input to Timer-0 RA5/ /AN4 - can be used for analog input 4 or slave select for the synchronized serial port.

Port-E pins (Alternate functions)

RE0/ /AN5 - can be used as analog input-5

RE1/ /AN6 - can be used as analog input-6

RE2/ /AN7 - can be used as analog input-7

PIC microcontroller has internal sample and hold circuit. The input signal should be stable across the capacitor before the conversion is initiated.

Fig : Sample and Hold Circuit

After waiting for the sampling time, a conversion can be initiated. The ADC Circuit will open the sampling switch and carry out the conversion of the input voltage as it was at the moment of opening of the switch. Upon completion of the conversion, the sampling switch is again closed and VHold once again tracks VSource.

Using the A/D Converter

Registers ADCON1, TRISA, and TRISE must be initialized to select the reference voltage and input channels. The first step selects the ADC clock from among the four choices (fosc/2, fosc/8, fosc/32, and RC). The constraint for selcting clock frequency is that the ADC clock period must be 1.6micro seconds or greater.

The A/D module has 3registers. These registers are:-

A/D result register (ADRES) A/D control register 0 (ADCON 0)

119

Page 120: Mpmc 11 Marks

A/D control register 1 (ADCON 1)

The ADCON0 register, which is shown below, controls the operation of A/D module.

Fig : ADCON0 register

Bit 7-6 - A/D Clock select bits ADCS1:ADCS0

00 = fosc/2 01 = fosc/8 10 = fosc/32 11 = fRC- clock derived from an internal RC oscillator

Bit 5-3 - A/D Channel Select CHS2:CHS0

000 - Channel 0 - AN0 001 - Channel 1 - AN1 010 - Channel 2 - AN2 011 - Channel 3 - AN3 100 - Channel 4 - AN4 101 - Channel 5 - AN5 110 - Channel 6 - AN6 111 - Channel 7 - AN7

Bit 2 - A/D conversion status bit

GO / if A/D Converter is enabled (ie. ADON = 1) then

If GO / = 1, A/D conversion is in progress (setting this bit starts A/D conversion)

If GO / = 0, A/D conversion is not in progress (This bit is automatically cleared by hardware when A/D conversion is complete)

Bit1 - Unimplemented Bit 0 - ADON: A/D On bit

1. A/D Converter module is ON 2. A/D Converter module is OFF

120

Page 121: Mpmc 11 Marks

ADCON1 Register

This register specifies the analog inputs

Fig : ADCON1 register

PCFG2:PCFG0 RA0 RA1 RA2 RA5 RA3 RE0 RE1 RE2 VREF

000 A A A A A A A A VDD

001 A A A A VREF A A A RA3

010 A A A A A D D D VDD

011 A A A A VREF D D D RA3

100 A A D D A D D D VDD

101 A A D D VREF D D D RA3

11X D D D D D D D D -Fig : PCFG2:PCFG0 = A/D Port configuration control bits

A = Analog inputD = Digital I/O

Fig : Schematic diagram of A/D convertor analog inputs and reference voltage Steps for A/D conversion

1. Configure A/D module Configure analog inputs/voltage reference and digital I/O (ADCON1) Select A/D Channel (ADCON0) Select A/D Conversion Clock (ADCON0)

121

Page 122: Mpmc 11 Marks

Turn on A/D Module (ADCON0) 2. Configure A/D Interrupt (Optional)

Clear ADIF bit in PIR1 register Set ADIE bit in PIE1 register Set GIE bit

3. Wait for required acquisition time

4. Start Conversion - set GO/ bit (ADCON0)

5. Wait for A/D conversion to complete, by either polling GO/ bit or by waiting for the A/D interrupt

6. Read A/D result registers (ADRES). Clear ADIF if required.

Example Program A/D conversion with interrupt

org 000H goto Mainline org 020H bsf STATUS, RP0 ; Select Bank 1 clrf ADCON 1 ; Configure A/D inputs bsf PIE1, ADIE ; Enable A/D interrupt bcf STATUS, RP0 ; Select Bank 0 movlw 081H ; Select fosc/32, channel 0, A/D on movwf ADCON0 bcf PIR1, ADIF bsf INTCON, PEIE ; Enable peripheral and global interrupt bits bsf INTCON, GIE ; interrupt bits ; Ensure that the required sampling time of the selected input channel has been elapsed. ; Then conversion may be started. ; bsf ADCON0, GO ; Start A/D conversion.

; ADIF bit will be set and GO/ ; bit is cleared upon completion of A/D conversion.

Interrupt Service Routine

Org 004H Movf ADRES, W ; Result of A/D conversion in W

Consideration of Sampling Time When a channel is selected (writing to ADCON0), the switch 'SW' in Fig 23.8 is closed, changing CHOLD to VSource . When A/D conversion is started (setting Go bit in ADCON0), SW is opened. The time from the closure of 'SW' till the voltage across CHOLD (Vo) reaches VSource is the minimum sampling time Ts . The actual sampling time can be higher

122

Page 123: Mpmc 11 Marks

than Ts .The graph between Ts and source resistance RSource is shown in Fig 23.7.+

Fig : Relation between sampling time and source resistance

Fig : Sampling circuit in the PIC µC

Rss is the resistance of the sampling switch 'SW' and CHold is the charge holding capacitance. CHold

is nearly 50pF. RSource is the impedance of the external analog source Vsource. Once the switch 'SW' is closed, the capacitor Chold takes some time to charge up. This time it is called the sampling time (Ts). This time varies linearly with RSource as shown. The recommended value of impedance of the external analog source, Vsource, is less than 10kΩ. The circuit in Fig 23.8 is a first order RC circuit. When SW is closed, Vo varies as shown in Fig 23.9.

Fig AA

From Fig AA,

Ts = 5 = 5 ( Rsource + Rss) CHOLD = 5 Rss CHOLD + 5 Rsource CHOLD

123

Page 124: Mpmc 11 Marks

Hence sampling time Ts varies linearly with RSource as shown in Fig 23.7.

124

Page 125: Mpmc 11 Marks

Synchronous Serial Port (SSP) Module: Most of mid range PIC microcontrollers include a Synchronous Serial Port (SSP) Module. The discussion in this section is relevant to PIC16C74A only. SSP Module section can be configured in either of the following two modes.

Serial Peripheral Interface (SPI) Inter Integrated Circuit (I2C)

Either of these modes can be used to interconnect two or more PIC chips to each other using a minimal number of wires for communication. Alternatively, either can be used to connect a PIC microcontroller to a peripheral chip. When I 2C mode is selected, the peripheral chip must also have an I 2C interface. On the other hand, the SPI mode provides the clock and serial data lines for direct connection to shift registers. This leads to increased I/O interface capability and an arbitrary number of I/O devices can be connected to a PIC microcontroller. SPI can also achieve data rate significantly higher than I2C. Both the communication methods are synchronous, i.e., the data transfer is synchronized with an explicit clock signal.

Two special purpose registers control the synchronous serial port (SSP) operations. These registers are:

SSPCON (Synchronous Serial Port Control Register), Address: 14H SSPSTAT(Synchronous Serial Port status Register), Address: 94H

Serial Peripheral Interface (SPI) Port-C three pins, viz., RC5/SDO, RC4/SDI and RC3/SCK/SCL are mainly used for SPI mode. In addition, one Port-A pin, viz., RA5/ /AN4 is used for slave select. The schematic block diagram of SPI is shown in the figure

125

Page 126: Mpmc 11 Marks

Fig : Schematic diagram under SPI Mode The SPI port requires RC3/SCK pin to be an output that generates the clock signal used by the external shift registers. When SPI is configured in the slave mode, RC3/SCK pin works as the input for the clock.

When a byte is written to SSPBUF register, it is shifted out of RC5/SDO pin in synchronous with the emitted clock pulses on RC3/SCK pin. The MSB of SSPBUF is the first bit to appear on RC5/SDO pin. Simultaneously, the same write to SSPBUF also initiates the 8 bit data reception into SSPBUF of whatever appears on RC4/SDI pin at the time of rising edges of the clock on SCK pin. Hence shifting-in and shifting-out of data occur simultaneously.

126

Page 127: Mpmc 11 Marks

Fig : SPI Master / Slave Connection The schematic diagram of SPI Master/Slave connection is shown in the figure.

Timing diagram for data transfer in 'Master mode' :

SSPIF interrupt flag is cleared by the user software if already in the set mode. The interrupt is enabled. Any write to SSPBUF initiates the data transfer, i.e., transmission and reception. The clock pulses (8 clock pulses) are output through SCK pin. The data is received through SDI. When CKP=1 (SSPCON<4>), data changes at SDO at negative clock transition and is read through SDI at positive clock transition. The idle state of clock is high. If CKP=0, data appears at SDO at positive clock transition and is read through SDI at negative clock transition. The idle state of the clock is low. These are shown in the following diagrams.

127

Page 128: Mpmc 11 Marks

(i) Timing diagram for CKP=1

(ii) Timing diagram for CKP=0

Fig : Timing Diagram under SPI mode

128

Page 129: Mpmc 11 Marks

I/O Port Expansion using Serial Peripheral Interface (SPI)

Though SPI is a serial communication interface, it can be used to realize multiple output parallel ports and multiple input parallel ports. We will consider this realization of an output parallel port and an input port separately.

Parallel Output Port Realization A parallel 8-bit output port can be realized through SPI with the help of a shift register chip (74HC595) as shown in Fig 25.1. RC5/SD0 pin outputs serial data while RC3/SCK oin outputs the serial clock. Since input data transfer is not required, port pin RC4/SDI is used to latch the shift register data to the output pins of the shift register. Hence RC4 is configured as an output pin.

Fig : PIC connection (in SPI mode) with a shift register When an 8-bit data is written to SSPBUF, the data is shifted out of RC5/SD0 pin. With CKP = 1, the data is stable at the positive transition but changes at the negative transition. The shift shifts the data at the positive clock transition. After 8 clock pulses, all 8-bits are shifted in the shift register. The completion of data transfer is indicated by SSPIF interrupt flag becoming ' 1' . The interrupt service routine make RC4 ' 1' , thus latching the 8-bit data to the output of the shift register. The configuration of various registers are shown in Fig 25.2 Port configurations

129

Page 130: Mpmc 11 Marks

Fig : Various Register ConfigurationsParallel Input Port Realization A shift register (74HC165) is connected to the PIC microcontroller as shown in Fig 25.3. Pin RD7 is configured as an output and is used to load 8-bit data to the shift register. A dummy write to SSPBUF initiates data transfer. Data bit is read into RC4/SDI at the negative clock transition (CKP = 0) where the data bit is stable. Data is shifted in the shift register at the position clock transition as shown in the timing diagram. After the completion of data transfer, SSPIF interrupt flag goes high. Therafter the 8-bit data can be read by reading SSPBUF.

130

Page 131: Mpmc 11 Marks

Fig : Realization of an 8-bit parallel input port with PIC in SPI mode.

Port configurations Fig 25.4 gives the configurations various registers for inputs parallel port realization.

131

Page 132: Mpmc 11 Marks

Fig : Configurations of various registers for parallel input port

I 2C Communication in PIC Microcontroller:I 2C stands for Inter-Integrated circuit. I 2C communication is a two wire bi-directional interface for connecting one or more master processors with one or more slave devices, such as an EEPROM, ADC, RAM, LCD display, DAC, etc. I 2C interface requires two open drain I/O pins, viz. SDA (Serial Data) and SCL (Serial Clock).

The reason for open drain connection is that the data transfer is bi-directional and any of the devices connected to the I 2C bus can drive the data line (SDA). The serial clock line (SCL) is usually driven by the master. Since SDA and SCL pins are open drain pins, external pull-up resistances are required for operation of I 2C bus.

A typical I2C bus showing the connection of multi-master and multi-slave configuration is shown in the following figure.

Fig : Multimaster Multislave Connection

Some conventions are followed in I2C communication. Let us assume that there is one master and one slave and 8-data bits are sent. We will initially assume that the master is the transmitter and the slave is the receiver. The clock is driven by the master. On receiving 8-bits, an

132

Page 133: Mpmc 11 Marks

acknowledgement bit is driven by the receiver on SDA line. The acknowledgement bit is usually Low (0). The following diagram shows the data communication pattern having 8 data bits and one acknowledgement bit.

Fig : Timing diagram for data transfer

The following features are to be noted -

1. SDA line transmits/ receives data bits. MSB is sent first. 2. Data in SDA line is stable during clock (SCL) high. A new bit is initiated at the negative

clock transition after a specified hold time. 3. Serial clock (SCL) is driven by the master. 4. An acknowledgement bit (0) is driven by the receiver after the end of reception. If the

receiver does not acknowledge, SDA line remains high (1).

I2C bus transfer consists of a number of byte transfers within a START condition and either another START condition or a STOP condition. During the idle state when no data transfer is taking place, both SDA and SCL lines are released by all the devices and remains high. When a master wants to initiate a data transfer, it pulls SDA low followed by SCL being pulled low. This is called START condition. Similarly, when the processor wants to terminate the data transfer it first releases SCL (SCL becomes high) and then SDA. This is called a STOP condition. START and STOP conditions are shown in the diagram as follows.

Fig : Timing diagram for START and STOP Conditions

START and STOP conditions are unique and they never happen within a data transfer.

Data Communication Protocol: In I2C communication both 7-bit and 10-bit slave addressing are possible. In 7-bit addressing mode 128 slaves can be interfaced with a single master. Similarly, in 10-bit addressing mode, 1024 slaves can be interfaced with the master. We will discuss here 7-bit addressing mode only. 10-bit addressing mode is similar to 7-bit addressing except from the fact that the number of address bits is more.

133

Page 134: Mpmc 11 Marks

Following a 'start' condition, the master sends a 7-bit address of the slave on SDA line. The MSB

is sent first. After sending 7-bit address of the slave peripheral, a R/ (8th bit) bit is sent by the

master. If R/ bit is '0', the following byte (after the acknowledgement bit) is written by the

master to the addressed slave peripheral. If R/ =1, the following byte (after the acknowledgement bit) has to be read from the slave by the master.

After sending the 7-bit address of the slave, the master sends the address (usually 8 bit) of the internal register of the slave wherefrom the data has to be read or written to. The subsequent access is automatically directed to the next address of the internal register.

The following diagrams give the general format to write and read from several peripheral internal registers.

Fig : Data transfer protocol for writing to a slave device R/ (Read / Write) bit indicates whether the data is to be written by the master or read by the master. If R/ is 1, the subsequent data are to be read by the master. If R/ = 0, the subsequent data are to be written by the master to the addressed slave. It has to be noted that the slave address is sent first, following a 'start' condition. The addressed slave responds by acknowledging and gets ready for data transfer. If data has to be read from a specific address of the slave device, the master sends the 7-bit address of the slave first following a 'start' condition. R/ bit is sent as 'low'. The addressed slave acknowledges by pulling the ACK line low. The master then sends the 8-bit internal address of the slave from which data has to be read. The slave acknowledges. Since R/ bit was initially 0, the master is in the write mode. To change this to read mode, the 'start' condition is again generated followed by 7-bit address of the slave with R/ = 1. The slave acknowledges. The slave then sends data from previously specified

134

Page 135: Mpmc 11 Marks

internal address to the master. The master acknowledges by pulling ACK bit low. The data transfer stops when the master does not acknowledge the data reception and a 'stop' condition is generated.

Software for I2 C CommunicationThe data transfer in I2C mode is not automatically controlled by hardware unlike UART. The Master has to be programmmed by suitable software to generate 'Start' / 'Stop' conditions, various data bits from sending / receving , acknowledgement bit and clock signal. Here, we will discuss some examples of I2C software.

Since SDA (RC4) and SCL (RC3) are both open drain pins, they can be configured either as an output or as an input. When a PIC Processor is configured is I2C master, the SCL pin will function as open drain output while the SDA pin can be either an input or an open drain output. Hence, the software I 2C will repeatedly access TRISC, the data direction register for PORT C. However, TRISC is located in bank-1 at an address 87H, which cannot be accessed by direct addressing without changing RP0 bit to 1 as given in the following instruction.

bsf STATUS, RP0

Then required bit of TRISC can be changed followed by clearing RP0 and reverting back to Bank-0.

bcf STATUS, RP0

Alternately, the indirect pointer FSR can have the address of TRISC and the required bit setting and bit clearing can be done indirectly.

Consider the following definitions.

SCL equ 3 SDA equ 4

The instruction bsf INDF, SDA will release the SDA line(as RC4/SDA pin is configured as an input, hence tristated), letting the external pullup resister pull it high or some I 2C Slave device/Chip pull it low.

When FSR is used for indirect addressing, care should be taken to restore FSR value when subroutine is completed and the program returns to the main line program.

I 2 C Subroutine

SDA equ 4 SCL equ 3

135

Page 136: Mpmc 11 Marks

The following subroutine DATA_OUT transfers out three bytes, i.e., ADDRDEV, ADDR8, and DATAWRTE

DATA_OUT: call START ; Generate start condition

movf ADDRDEV, W ; Sends 7-bit peripheral address with R/ =0 call TRBYTE ; Transmit movf ADDR8, W ; Send 8-bit internal address call TRBYTE movf DATAWRTE, W ; Send data to be written call TRBYTE call STOP ; Generate Stop condition return

The DATA_IN subroutine, which is given below transfers out ADDRDEV (with R/ =0) and

ADDR8, restarts and transfers out ADDRDEV (with R/ =1) and read one byte back into RAM variable DATARD.

DATA_IN: call START movf ADDRDEV, W ; Send 7-bit peripheral address R/ =0 call TRBYTE movf ADDR8, W ; Send int. address call TRBYTE call START1 ; Restart movf ADDRDEV, W ; Send 7-bit peripheral address R/ =1 iorlwl 01H call TRBYTE bsf TRBUF, 7 ; Generate NO ACK call RCVBYTE movwf DATARD call STOP return

The 'START' subroutine initializes I2C bus and then generates START condition on the I 2C bus. START1 bypasses the initialization of I 2C.

START: movlw 3BH ;enables I2C master mode by programming SSPCON movwf SSPCON bcf PORTC, SDA ; drive SDA low when it is an o/p movlw TRISC ;set indirect pointer to TRISC movwf FSR START1: bsf INDF, SDA ; SDA=1

136

Page 137: Mpmc 11 Marks

bsf INDF , SCL ; SCL=1 call DELAY ; Generates a suitable delay bcf INDF, SDA ; SDA=0 call DELAY ; Generate a suitable delay bcf INDF, SCL ;SCL=0 return STOP: bcf INDF, SDA ;SDA=0 bsf INDF, SCL ; SCL=1 call DELAY ; Generate a suitable delay bsf INDF, SDA ;SDA=1 return

The subroutine 'TRBYTE' send out the byte available in w. It returns with Z=1 if ACK occurs. It returns with Z=0 if NOACK occurs. TRBUF is an 8-bit RAM variable used for temporary storage. The bits are shifted to carry flag (C) and the carry bit transmitted successively. Data transfer is complete when all 8-bits are transmitted. Setting C = 1 initially sets an index for 8-bits to be transferred. C is rotated through TRBUF. After transmitting C, C-bit is cleared. When TRBUF is completely cleared, all 8-bis are transmitted.

TRBYTE:

movwf TRBUF bsf STATUS,C

TR_1:

rlf TRBUF, F movf RBUF,F btfss STATUS, Z call out_bit ; Send a bit available in C btfss STATUS, Z goto TR_1 call in_bit ; Get the ACK bit in RCBUF<0> movlw 01H ; andwf RCBUF, W ; Store the complement of ACK bit in Z flag return

The RCVBYTE subroutine receives a byte from I2 C into W using a RAM variable RCBUF buffer.

137

Page 138: Mpmc 11 Marks

Call RCVBYTE with bit 7 of TRBUF clear for ACK Call RCVBYTE with bit 7 of TRBUF set for NOACK RCBUF is an 8-bit RAM variable used for recieving the data. the bit is recieved in the RCBUF<0> and is rotated successively through RCBUF as shown. The reception ends when all 8-bits are recieved.

RCVBYTE:

movlw 01Hmovwf RCBUF ; Keep an index for 8-bits to be recieved.

RCV_1:

rlf RCBUF, F call In_bit btfss STATUS, C goto RCV_1 rlf TRBUF, F call Out_bit movf RCBUF,w return

The out_bit subroutine transmits carry bit, then clears the carry bit.

Out_bit:

bcf INDF, SDA btfsc STATUS, C bsf INDF, SDA ; Send carry bit bsf INDF, SCL call DELAY bcf INDF, SCL bcf STATUS,C ; Clear carry bit return

The in_bit subroutine receives one bit into bit-0 of RCBUF. In_bit:

bsf INDF,SDA bsf INDF, SCL bcf RCBUF, 0 btfsc PORTC, SDA ; Check SDA line for data bit bsf RCBUF, 0

138

Page 139: Mpmc 11 Marks

bcf INDF, SCL return

Example of I 2 C interfacing DAC interfacing on I 2 C bus:

MAX518 is a dual 8-bit Digital to Analog Converter (DAC) with I2C interface. The address of the device is selectable through two pins AD1 and AD0 . This device works in I2C slave mode. The connection diagram is shown as follows.

Fig : I2C Interface for DAC The 7-bit device address is given as

For the present connection AD1 = 0 and AD0 = 1 The device address is 010 1101 Three bytes are sent to output an analog voltage.

First byte (Address of the DAC and R/ bit )

Second byte (DAC Configuration)

139

Page 140: Mpmc 11 Marks

Third byte (The 8-bit digital data(B) to be converted to analog voltage)B

Analog output voltage = V DD x B/256

PIC 16F84PIC16F84 belongs to a class of 8-bit microcontrollers of RISC architecture. Its general structure is shown on the following map representing basic blocks. Program memory (FLASH)- for storing a written program. Since memory made in FLASH technology can be programmed and cleared more than once, it makes this microcontroller suitable for device development. EEPROM - data memory that needs to be saved when there is no supply. It is usually used for storing important data that must not be lost if power supply suddenly stops. For instance, one such data is an assigned temperature in temperature regulators. If during a loss of power supply this data was lost, we would have to make the adjustment once again upon return of supply.

Thus our device looses on self-reliance. RAM - data memory used by a program during its execution. In RAM are stored all inter-results or temporary data during run-time. PORTA and PORTB are physical connections between the microcontroller and the outside world. Port A has five, and port B has eight pins. FREE-RUN TIMER is an 8-bit register inside a microcontroller that works independently of the program. On every fourth clock of the oscillator it increments its value until it reaches the maximum (255), and then it starts counting over again from zero. As we know the exact timing between each two increments of the timer contents, timer can be used for measuring time which is very useful with some devices. CENTRAL PROCESSING UNIT has a role of connective element between other blocks in the microcontroller. It coordinates the work of other blocks and executes the user program.

140

Page 141: Mpmc 11 Marks

Applications

PIC16F84 perfectly fits many uses, from automotive industries and controlling home appliances to industrial instruments, remote sensors, electrical door locks and safety devices. It is also ideal for smart cards as well as for battery supplied devices because of its low consumption.

EEPROM memory makes it easier to apply microcontrollers to devices where permanent storage of various parameters is needed (codes for transmitters, motor speed, receiver frequencies, etc.). Low cost, low consumption, easy handling and flexibility make PIC16F84 applicable even in areas where microcontrollers had not previously been considered (example: timer functions, interface replacement in larger systems, coprocessor applications, etc.).

In System Programmability of this chip (along with using only two pins in data transfer) makes possible the flexibility of a product, after assembling and testing have been completed. This capability can be used to create assembly-line production, to store calibration data available only after final testing, or it can be used to improve programs on finished products.

Pin description

PIC16F84 has a total of 18 pins. It is most frequently found in a DIP18 type of case but can also be found in SMD case which is smaller from a DIP. DIP is an abbreviation for Dual In Package. SMD is an abbreviation for Surface Mount Devices suggesting that holes for pins to go through when mounting, aren't necessary in soldering this type of a component.

141

Page 142: Mpmc 11 Marks

Pins on PIC16F84 microcontroller have the following meaning:

Pin No. Name DescriptionPin no. 1 RA2 Second pin on port A. Has no additional function.Pin no. 2 RA3 Third pin on port A. Has no additional function.

Pin no. 3 RA4Fourth pin on port A. TOCK1 which functions as a timer is alsofound on this pin.

Pin no. 4 MCLR Reset input and Vpp programming voltage of a microcontroller.Pin no. 5 Vss Ground of power supply.Pin no. 6 RB0 Zero pin on port B. Interrupt input is an additional function.Pin no. 7 RB1 First pin on port B. No additional function.Pin no. 8 RB2 Second pin on port B. No additional function.Pin no. 9 RB3 Third pin on port B. No additional function.Pin no. 10 RB4 Fourth pin on port B. No additional function.Pin no. 11 RB5 Fifth pin on port B. No additional function.Pin no. 12 RB6 Sixth pin on port B. 'Clock' line in program mode.Pin no. 13 RB7 Seventh pin on port B. 'Data' line in program mode.Pin no. 14 Vdd Positive power supply pole.Pin no. 15 OSC2 Pin assigned for connecting with an oscillator.Pin no. 16 OSC1 Pin assigned for connecting with an oscillator.Pin no. 17 RA2 Second pin on port A. No additional function.Pin no. 18 RA1 First pin on port A. No additional function.

142

Page 143: Mpmc 11 Marks

Introduction to LCD interfacingFrequently, an 8051 program must interact with the outside world using input and output

devices that communicate directly with a human being. One of the most common devices attached to an 8051 is an LCD display. Some of the most common LCDs connected to the 8051 are 16x2 and 20x2 displays. This means 16 characters per line by 2 lines and 20 characters per line by 2 lines, respectively.

Fortunately, a very popular standard exists which allows us to communicate with the vast majority of LCDs regardless of their manufacturer. The standard is referred to as HD44780U, which refers to the controller chip which receives data from an external source (in this case, the 8051) and communicates directly with the LCD.

44780 BACKGROUND

The 44780 standard requires 3 control lines as well as either 4 or 8 I/O lines for the data bus. The user may select whether the LCD is to operate with a 4-bit data bus or an 8-bit data bus. If a 4-bit data bus is used the LCD will require a total of 7 data lines (3 control lines plus the 4 lines for the data bus). If an 8-bit data bus is used the LCD will require a total of 11 data lines (3 control lines plus the 8 lines for the data bus).

The three control lines are referred to as EN, RS, and RW.

The EN line is called "Enable." This control line is used to tell the LCD that you are sending it data. To send data to the LCD, your program should make sure this line is low (0) and then set the other two control lines and/or put data on the data bus. When the other lines are completely ready, bring EN high (1) and wait for the minimum amount of time required by the LCD datasheet (this varies from LCD to LCD), and end by bringing it low (0) again.

The RS line is the "Register Select" line. When RS is low (0), the data is to be treated as a command or special instruction (such as clear screen, position cursor, etc.). When RS is high (1), the data being sent is text data which sould be displayed on the screen. For example, to display the letter "T" on the screen you would set RS high.

The RW line is the "Read/Write" control line. When RW is low (0), the information on the data bus is being written to the LCD. When RW is high (1), the program is effectively querying (or reading) the LCD. Only one instruction ("Get LCD status") is a read command. All others are write commands--so RW will almost always be low.

143

Page 144: Mpmc 11 Marks

Finally, the data bus consists of 4 or 8 lines (depending on the mode of operation selected by the user). In the case of an 8-bit data bus, the lines are referred to as DB0, DB1, DB2, DB3, DB4, DB5, DB6, and DB7.

AN EXAMPLE HARDWARE CONFIGURATION

As we've mentioned, the LCD requires either 8 or 11 I/O lines to communicate with. For the sake of this tutorial, we are going to use an 8-bit data bus--so we'll be using 11 of the 8051's I/O pins to interface with the LCD.

Let's draw a sample psuedo-schematic of how the LCD will be connected to the 8051.

As you can see, we've established a 1-to-1 relation between a pin on the 8051 and a line on the 44780 LCD. Thus as we write our assembly program to access the LCD, we are going to equate constants to the 8051 ports so that we can refer to the lines by their 44780 name as opposed to P0.1, P0.2, etc. Let's go ahead and write our initial equates:

DB0 EQU P1.0DB1 EQU P1.1DB2 EQU P1.2DB3 EQU P1.3DB4 EQU P1.4DB5 EQU P1.5DB6 EQU P1.6DB7 EQU P1.7EN EQU P3.7RS EQU P3.6RW EQU P3.5DATA EQU P1

Having established the above equates, we may now refer to our I/O lines by their 44780 name. For example, to set the RW line high (1), we can execute the following insutrction:

SETB RW

HANDLING THE EN CONTROL LINE

As we mentioned above, the EN line is used to tell the LCD that you are ready for it to execute an instruction that you've prepared on the data bus and on the other control lines. Note that the EN line must be raised/lowered before/after each instruction sent to the LCD regardless of whether that instruction is read or write, text or instruction. In short, you must always manipulate EN when communicating with the LCD. EN is the LCD's way of knowing that you are talking to it. If you don't raise/lower EN, the LCD doesn't know you're talking to it on the other lines.

144

Page 145: Mpmc 11 Marks

Thus, before we interact in any way with the LCD we will always bring the EN line low with the following instruction:

CLR ENAnd once we've finished setting up our instruction with the other control lines and data bus lines, we'll always bring this line high:

SETB ENThe line must be left high for the amount of time required by the LCD as specified in its datasheet. This is normally on the order of about 250 nanoseconds, but check the datasheet. In the case of a typical 8051 running at 12 MHz, an instruction requires 1.08 microseconds to execute so the EN line can be brought low the very next instruction. However, faster microcontrollers (such as the DS89C420 which executes an instruction in 90 nanoseconds given an 11.0592 Mhz crystal) will require a number of NOPs to create a delay while EN is held high. The number of NOPs that must be inserted depends on the microcontroller you are using and the crystal you have selected.

The instruction is executed by the LCD at the moment the EN line is brought low with a final CLR EN instruction.

Programming Tip: The LCD interprets and executes our command at the instant the EN line is brought low. If you never bring EN low, your instruction will never be executed. Additionally, when you bring EN low and the LCD executes your instruction, it requires a certain amount of time to execute the command. The time it requires to execute an instruction depends on the instruction and the speed of the crystal which is attached to the 44780's oscillator input.

CHECKING THE BUSY STATUS OF THE LCD

As previously mentioned, it takes a certain amount of time for each instruction to be executed by the LCD. The delay varies depending on the frequency of the crystal attached to the oscillator input of the 44780 as well as the instruction which is being executed.

While it is possible to write code that waits for a specific amount of time to allow the LCD to execute instructions, this method of "waiting" is not very flexible. If the crystal frequency is changed, the software will need to be modified. Additionally, if the LCD itself is changed for another LCD which, although 44780 compatible, requires more time to perform its operations, the program will not work until it is properly modified.

A more robust method of programming is to use the "Get LCD Status" command to determine whether the LCD is still busy executing the last instruction received.

The "Get LCD Status" command will return to us two tidbits of information; the information that is useful to us right now is found in DB7. In summary, when we issue the "Get LCD Status" command the LCD will immediately raise DB7 if it's still busy executing a command or lower DB7 to indicate that the LCD is no longer occupied. Thus our program can query the LCD until

145

Page 146: Mpmc 11 Marks

DB7 goes low, indicating the LCD is no longer busy. At that point we are free to continue and send the next command.

Since we will use this code every time we send an instruction to the LCD, it is useful to make it a subroutine. Let's write the code:

WAIT_LCD:CLR EN ;Start LCD commandCLR RS ;It's a commandSETB RW ;It's a read commandMOV DATA,#0FFh ;Set all pins to FF initiallySETB EN ;Clock out command to LCDMOV A,DATA ;Read the return valueJB ACC.7,WAIT_LCD ;If bit 7 high, LCD still busyCLR EN ;Finish the commandCLR RW ;Turn off RW for future commandsRET

Thus, our standard practice will be to send an instruction to the LCD and then call our WAIT_LCD routine to wait until the instruction is completely executed by the LCD. This will assure that our program gives the LCD the time it needs to execute instructions and also makes our program compatible with any LCD, regardless of how fast or slow it is.

Programming Tip: The above routine does the job of waiting for the LCD, but were it to be used in a real application a very definite improvement would need to be made: as written, if the LCD never becomes "not busy" the program will effectively "hang," waiting for DB7 to go low. If this never happens, the program will freeze. Of course, this should never happen and won't happen when the hardware is working properly. But in a real application it would be wise to put some kind of time limit on the delay--for example, a maximum of 256 attempts to wait for the busy signal to go low. This would guarantee that even if the LCD hardware fails, the program would not lock up.

INITIALIZING THE LCD

Before you may really use the LCD, you must initialize and configure it. This is accomplished by sending a number of initialization instructions to the LCD.

The first instruction we send must tell the LCD whether we'll be communicating with it with an 8-bit or 4-bit data bus. We also select a 5x8 dot character font. These two options are selected by sending the command 38h to the LCD as a command. As you will recall from the last section, we mentioned that the RS line must be low if we are sending a command to the LCD. Thus, to send this 38h command to the LCD we must execute the following 8051 instructions:

CLR RSMOV DATA,#38hSETB ENCLR ENLCALL WAIT_LCD

146

Page 147: Mpmc 11 Marks

Programming Tip: The LCD command 38h is really the sum of a number of option bits. The instruction itself is the instruction 20h ("Function set"). However, to this we add the values 10h to indicate an 8-bit data bus plus 08h to indicate that the display is a two-line display.

We've now sent the first byte of the initialization sequence. The second byte of the initialization sequence is the instruction 0Eh. Thus we must repeat the initialization code from above, but now with the instruction. Thus the the next code segment is:

CLR RSMOV DATA,#0EhSETB ENCLR ENLCALL WAIT_LCDProgramming Tip: The command 0Eh is really the instruction 08h plus 04h to turn the LCD on. To that an additional 02h is added in order to turn the cursor on.

The last byte we need to send is used to configure additional operational parameters of the LCD. We must send the value 06h.

CLR RSMOV DATA,#06hSETB ENCLR ENLCALL WAIT_LCDProgramming Tip: The command 06h is really the instruction 04h plus 02h to configure the LCD such that every time we send it a character, the cursor position automatically moves to the right.

So, in all, our initialization code is as follows:

INIT_LCD:CLR RSMOV DATA,#38hSETB ENCLR ENLCALL WAIT_LCDCLR RSMOV DATA,#0EhSETB ENCLR ENLCALL WAIT_LCDCLR RSMOV DATA,#06hSETB ENCLR EN

147

Page 148: Mpmc 11 Marks

LCALL WAIT_LCDRET

Having executed this code the LCD will be fully initialized and ready for us to send display data to it.

CLEARING THE DISPLAY

When the LCD is first initialized, the screen should automatically be cleared by the 44780 controller. However, it's always a good idea to do things yourself so that you can be completely sure that the display is the way you want it. Thus, it's not a bad idea to clear the screen as the very first opreation after the LCD has been initialiezd.

An LCD command exists to accomplish this function. Not suprisingly, it is the command 01h. Since clearing the screen is a function we very likely will wish to call more than once, it's a good idea to make it a subroutine:

CLEAR_LCD:CLR RSMOV DATA,#01hSETB ENCLR ENLCALL WAIT_LCDRET

How that we've written a "Clear Screen" routine, we may clear the LCD at any time by simply executing an LCALL CLEAR_LCD.

Programming Tip: Executing the "Clear Screen" instruction on the LCD also positions the cursor in the upper left-hand corner as we would expect.

WRITING TEXT TO THE LCD

Now we get to the real meat of what we're trying to do: All this effort is really so we can display text on the LCD. Really, we're pretty much done.

Once again, writing text to the LCD is something we'll almost certainly want to do over and over--so let's make it a subroutine.

WRITE_TEXT:SETB RSMOV DATA,ASETB ENCLR ENLCALL WAIT_LCDRET

The WRITE_TEXT routine that we just wrote will send the character in the accumulator to the LCD which will, in turn, display it. Thus to display text on the LCD all we need to do is load the accumulator with the byte to display and make a call to this routine. Pretty easy, huh?

148

Page 149: Mpmc 11 Marks

A "HELLO WORLD" PROGRAM

Now that we have all the component subroutines written, writing the classic "Hello World" program--which displays the text "Hello World" on the LCD is a relatively trivial matter. Consider:

LCALL INIT_LCDLCALL CLEAR_LCDMOV A,#'H'LCALL WRITE_TEXTMOV A,#'E'LCALL WRITE_TEXTMOV A,#'L'LCALL WRITE_TEXTMOV A,#'L'LCALL WRITE_TEXTMOV A,#'O'LCALL WRITE_TEXTMOV A,#' 'LCALL WRITE_TEXTMOV A,#'W'LCALL WRITE_TEXTMOV A,#'O'LCALL WRITE_TEXTMOV A,#'R'LCALL WRITE_TEXTMOV A,#'L'LCALL WRITE_TEXTMOV A,#'D'LCALL WRITE_TEXT

The above "Hello World" program should, when executed, initialize the LCD, clear the LCD screen, and display "Hello World" in the upper left-hand corner of the display.

CURSOR POSITIONING

The above "Hello World" program is simplistic in the sense that it prints its text in the upper left-hand corner of the screen. However, what if we wanted to display the word "Hello" in the upper left-hand corner but wanted to display the word "World" on the second line at the tenth character? This sounds simple--and actually, it is simple. However, it requires a little more understanding of the design of the LCD.

The 44780 contains a certain amount of memory which is assigned to the display. All the text we write to the 44780 is stored in this memory, and the 44780 subsequently reads this memory to display the text on the LCD itself. This memory can be represented with the following "memory map":

149

Page 150: Mpmc 11 Marks

In the above memory map, the area shaded in blue is the visible display. As you can see, it measures 16 characters per line by 2 lines. The numbers in each box is the memory address that corresponds to that screen position.

Thus, the first character in the upper left-hanad corner is at address 00h. The following character position (character #2 on the first line) is address 01h, etc. This continues until we reach the 16th character of the first line which is at address 0Fh.

However, the first character of line 2, as shown in the memory map, is at address 40h. This means if we write a character to the last position of the first line and then write a second character, the second character will not appear on the second line. That is because the second character will effectively be written to address 10h--but the second line begins at address 40h.

Thus we need to send a command to the LCD that tells it to position the cursor on the second line. The "Set Cursor Position" instruction is 80h. To this we must add the address of the location where we wish to position the cursor. In our example, we said we wanted to display "World" on the second line on the tenth character position.

Referring again to the memory map, we see that the tenth character position of the second line is address 4Ah. Thus, before writing the word "World" to the LCD, we must send a "Set Cursor Position" instruction--the value of this command will be 80h (the instruction code to position the cursor) plus the address 4Ah. 80h + 4Ah = CAh. Thus sending the command CAh to the LCD will position the cursor on the second line at the tenth character position:

CLR RSMOV DATA,#0CAhSETB ENCLR ENLCALL WAIT_LCD

The above code will position the cursor on line 2, character 10. To display "Hello" in the upper left-hand corner with the word "World" on the second line at character position 10 just requires us to insert the above code into our existing "Hello World" program. This results in the following:

LCALL INIT_LCDLCALL CLEAR_LCDMOV A,#'H'LCALL WRITE_TEXTMOV A,#'E'LCALL WRITE_TEXTMOV A,#'L'LCALL WRITE_TEXTMOV A,#'L'LCALL WRITE_TEXTMOV A,#'O'LCALL WRITE_TEXT

150

Page 151: Mpmc 11 Marks

CLR RSMOV DATA,#0CAhSETB ENCLR ENLCALL WAIT_LCDMOV A,#'W'LCALL WRITE_TEXTMOV A,#'O'LCALL WRITE_TEXTMOV A,#'R'LCALL WRITE_TEXTMOV A,#'L'LCALL WRITE_TEXTMOV A,#'D'LCALL WRITE_TEXT

Stepper Motor interfacing with Microcontrollers:

Introduction

This section of tutorial will explain you everything that you need to know about stepper motors. Stepper motors can be used in various areas of your microcontroller projects such as making robots, robotic arm, automatic door lock system etc. This tutorial will explain you construction of stepper motors (unipolar and bipolar stepper motors ), basic pricipal, different controlling types (Half step and Full step), Interfacing Techniques (using L293D or ULN2003) and programming your microcontroller in C and assembly to control stepper motor.

Unipolar stepper motor The unipolar stepper motor has five or six wires and four coils (actually two coils divided by center connections on each coil). The center connections of the coils are tied together and used as the power connection. They are called unipolar steppers because power always comes in on this one pole.

Bipolar stepper motor The bipolar stepper motor usually has four wires coming out of it. Unlike unipolar steppers, bipolar steppers have no common center connection. They have two independent sets of coils instead. You can distinguish them from unipolar steppers by measuring the resistance between the wires. You should find two pairs of wires with equal resistance. If you've got the leads of your meter connected to two wires that are not connected (i.e. not attached to the same coil), you

151

Page 152: Mpmc 11 Marks

should see infinite resistance (or no continuity).

As already said, we will talk mostly on "Unipolar stepper motors" which is most common type of stepper motor available in the market.A simple example of 6 lead step motor is given below and in 5 lead step motor wire 5 and 6 are joined together to make 1 wire as common.

Working of Stepper Motor

Now lets discuss the operation pricipal of a stepper motor. When we energize a coil of stepper motor, The shaft of stepper motor (which is actually a permanent magnet) align itself according to poles of energized coil. So when motor coils are energized in a particular sequence, motor shaft tend to align itself according to pole of coils and hence rotates. A small example of energizing operation is given below.

152

Page 153: Mpmc 11 Marks

You can see in the example, when coil "A" is energized, A north-south polarity is generated at "A+A\" as shown in the figure above and magnetic shaft automatically align itself according to the poles generated. When the next coil is energized the shaft again align itself and take a step. Hence the working pricipal.

153

Page 154: Mpmc 11 Marks

We have seen that to make the stepper motor work, we need to energize coil in a sequence

Stepper motors can be driven in two different patterns or sqeunces. namely,

Full Step Sequence Half Step Sequence

we will go through these sequences one by one.

Full Step Sequence

In the full step sequence, two coils are energized at the same time and motor shaft rotates. The order in which coils has to be energized is given in the table below.

Full Mode SequenceStep A B A\ B\

0 1 1 0 01 0 1 1 02 0 0 1 13 1 0 0 1

154

Page 155: Mpmc 11 Marks

The working of the full mode sequence is given in the animated figure below.

Half Step Sequence

In Half mode step sequence, motor step angle reduces to half the angle in full mode. So the angualar resolution is also increased i.e. it becomes double the angular resolution in full mode. Also in half mode sequence the number of steps gets doubled as that of full mode. Half mode is usually preffered over full mode. Table below shows the pattern of energizing the coils.

Half Mode SequenceStep A B A\ B\

0 1 1 0 01 0 1 0 02 0 1 1 03 0 0 1 04 0 0 1 15 0 0 0 16 1 0 0 17 1 0 0 0

155

Page 156: Mpmc 11 Marks

The working of the half mode sequence is given in the animated figure below.

Step Angle

Step angle of the stepper motor is defined as the angle traversed by the motor in one step. To calculate step angle,simply divide 360 by number of steps a motor takes to complete one revolution. As we have seen that in half mode, the number of steps taken by the motor to complete one revolution gets doubled, so step angle reduces to half.

As in above examples, Stepper Motor rotating in full mode takes 4 steps to complete a revolution, So step angle can be calculated as...

Step Angle ø = 360° / 4 = 90°

and in case of half mode step angle gets half so 45°.

So this way we can calculate step angle for any stepper motor. Usually step angle is given in the spec sheet of the stepper motor you are using. Knowing stepper motor's step angle helps you calibrate the rotation of motor also to helps you move the motor to correct angular position.

Step Sequence for 2-wire control of Unipolar stepper motor

156

Page 157: Mpmc 11 Marks

As seen in above explanation, In every step of the sequence, two wires are always set to opposite polarities. Because of this, it's possible to control steppers with only two wires instead of four, with a slightly more complex circuit. The stepping sequence is the same as it is for the two coils A and B, and the opposite polarity value is given to A\ and B\. The sequence is given in the table below:

2-wire Mode SequenceStep A B

0 0 11 1 12 1 03 0 0

Step Sequence for Bipolar stepper motor

Bipolar motor has simpler construction. It has two windings with no center taps and a permanent magnet at the center just like unipolar stepepr motors. Being simpler in contruction, the stepping sequence is a little complex, as the power for both the coils has to be controlled in such a way that the polarity of the poles get reversed. This polarity sequence is shown in the table below.

Polarity SequenceStep A A\ B B\

0 +ve -ve -ve -ve1 -ve -ve +ve -ve2 -ve +ve -ve -ve3 -ve -ve -ve +ve

The above polarity sequence can be interpreted in terms of logic levels for microcontroller by activating one coil at a time as shown in the table below.

Step SequenceStep A A\ B B\

0 1 0 0 01 0 0 1 02 0 1 0 03 0 0 0 1

#include <REG2051.H>.#define stepper P1void delay();

void main() while(1) stepper = 0x0C; delay(); stepper = 0x06;

157

Page 158: Mpmc 11 Marks

delay(); stepper = 0x03; delay(); stepper = 0x09; delay();

void delay() unsigned char i,j,k; for(i=0;i<6;i++) for(j=0;j<255;j++) for(k=0;k<255;k++);

Assembly Programming

CODE: org 0H

stepper equ P1

main: mov stepper, #0CH acall delay mov stepper, #06H acall delay mov stepper, #03H acall delay mov stepper, #09H acall delay sjmp main

delay: mov r7,#4wait2: mov r6,#0FFHwait1: mov r5,#0FFHwait: djnz r5,wait djnz r6,wait1 djnz r7,wait2 ret end

158

Page 159: Mpmc 11 Marks

The working of the above code can be seen in the demo animation below.

Programming Half step Sequence

C ProgrammingJust the main routine changes rest everything remains same, i mean same delay routine.

CODE:void main() while(1) stepper = 0x08; delay(); stepper = 0x0C; delay(); stepper = 0x04; delay(); stepper = 0x06; delay(); stepper = 0x02; delay(); stepper = 0x03; delay(); stepper = 0x01; delay(); stepper = 0x09;

159

Page 160: Mpmc 11 Marks

delay();

Assembly ProgrammingHere also the main routine changes rest everything remains same.

CODE:main: mov stepper, #08H acall delay mov stepper, #0CH acall delay mov stepper, #04H acall delay mov stepper, #06H acall delay mov stepper, #02H acall delay mov stepper, #03H acall delay mov stepper, #01H acall delay mov stepper, #09H acall delay sjmp main

The working of the above code can be seen in the demo animation below.

160

Page 161: Mpmc 11 Marks

Programming for 2-wire connection of Unipolar Stepper Motor

C ProgrammingCODE:void main() while(1) stepper = 0x03; delay(); stepper = 0x01; delay(); stepper = 0x00; delay(); stepper = 0x02; delay();

Assembly ProgrammingCODE:main: mov stepper, #03H acall delay mov stepper, #01H

161

Page 162: Mpmc 11 Marks

acall delay mov stepper, #00H acall delay mov stepper, #02H acall delay sjmp main

The working of the above code can be seen in the demo animation below.

Programming for Bipolar Stepper Motor

C ProgrammingCODE:

162

Page 163: Mpmc 11 Marks

void main() while(1) stepper = 0x08; delay(); stepper = 0x02; delay(); stepper = 0x04; delay(); stepper = 0x01; delay();

Assembly ProgrammingCODE:main: mov stepper, #08H acall delay mov stepper, #02H acall delay mov stepper, #04H acall delay mov stepper, #01H acall delay sjmp main

The Data Acquisition System

When converting an analog signal to digital form, it is usually not enough just to find a suitable ADC. Usually, more than one input is required and the signal needs processing before it can be converted. In most cases, therefore, it is necessary to build up a complete data acquisition system. The elements of such a system are shown in Figure 11.1. This shows, in block diagram form, a system with multiple inputs, amplification, filtering, source selection, sample and hold, and finally the ADC itself. The different elements are outlined in the sections which follow.

163

Page 164: Mpmc 11 Marks

Figure 11.1: Elements of a (four-channel) data acquisition system

11.2.1 The Analog-to-Digital Converter

The task of the ADC is to determine a digital output number that is the equivalent of its input voltage. The design of such circuits is a non-trivial task. Many very different ADC circuits have been developed, targeted towards different applications. Some, like the dual ramp ADC, are slow but with very high accuracy, and useful for precision measurements such as digital voltmeters. Others, like the Flash converter (not to be confused with Flash memory technology), are fast but of lesser accuracy, and are used to convert highspeed signals like video or radar. Others, like the successive approximation ADC, are of medium speed and medium accuracy, and useful for general-purpose industrial applications. This is the type most commonly found in embedded systems.

An ADC is characterised principally by the following features.

Conversion Characteristic

The ADC accepts an input voltage that is infinitely variable. It converts this to one of a fixed number of output values. An example ADC conversion characteristic is shown in Figure 11.2, where the input voltage is represented on the horizontal axis and digital output on the vertical. If the ADC is converting continuously and the input voltage is gradually increased from zero, the output is also initially zero. At a certain value of input, the output changes to …001. It stays at this same value as the input increases further, until at another input value the output switches to …010. If the input voltage increases continuously, the output at some point reaches its maximum value. The input has then traversed its full range. The output will have moved stepwise up to its maximum value. For an n-bit ADC, the maximum output value will be (2n - 1). For example, for an 8-bit ADC, the final value will be (28 - 1), or 11111111B, or 255D.

164

Page 165: Mpmc 11 Marks

Figure 11.2: The ideal ADC input/output characteristic

The input range shown in Figure 11.2 starts from zero and goes up to the value Vmax. This is placed a little to the right of where one might expect it, at the centre of where a step for 2n would occur. This positioning allows the horizontal axis to be divided into exactly 2n equal segments, each centred on an output transition.

Many ADCs have a characteristic like in Figure 11.2, for example with an input range of 0–5 V. Others, however, have a bipolar range, with the input voltage taking both positive and negative values, for example -5 to +5 V. In every case the input range Vr is the difference between maximum input voltage and minimum input voltage. The range usually relates in a direct way to the value of the voltage reference, which forms part of the ADC.

It can be seen intuitively from the diagram that the more the number of output bits, the more will be the number of output steps and the finer is the conversion. A measure of the fineness of conversion is called the resolution. This is the amount by which the input has to change to go from one output value up to the next. In the diagram, the resolution is the width of one step in the conversion characteristic. An ADC with n output bits can take 2n possible output values, from 0 up to 2n - 1. It therefore has a resolution of Vr/2n, where Vr is the input voltage range. An incoming signal should use as much of the input range as possible, without exceeding it. If it only uses a part of it, then the effective resolution is degraded and the ADC is not being put to best use.

Conversion Speed

An ADC takes time to do its work. That time is called the conversion time. A slow ADC, with a high conversion time, will only be able to convert low-frequency signals, as Nyquist's criterion (Section 11.2.2) must always be satisfied. The conversion time of an ADC defines which type of signal it can be used to convert. As suggested earlier, high-accuracy ADCs generally take longer to complete a conversion.

Digital Interface

165

Page 166: Mpmc 11 Marks

The digital interface is made up of the control signals and the data output. Typical control signals are shown in Figure 11.1. Generally, there is a signal to the ADC that causes a conversion to start. When the conversion is complete, the ADC signals that completion with an output signal. A further signal causes the ADC to output its data. Depending on the type of interface required, the ADC has a parallel or serial data interface.

An ADC always works in conjunction with a voltage reference. This is a device or circuit that maintains a very precise and stable voltage, and is based around a zener diode or a band-gap reference. The ADC effectively uses the voltage reference as the ruler, with which it measures the incoming voltage. An ADC is only as good as its voltage reference. For accurate A-to-D conversion, a good ADC must be used with a good reference.

11.2.2 Signal Conditioning — Amplification and Filtering

To make best use of the ADC, the input voltage should traverse as much of its input range as possible, without exceeding it. Yet most signal sources, say a microphone or thermocouple, produce very small voltages. Therefore, in many cases amplification is needed to exploit the range to best effect. Voltage level shifting may also be required, for example if the signal source is bipolar while the ADC input is unipolar (voltage is positive only).

If the signal being converted is periodic, then a fundamental requirement of conversion is that the conversion rate must be at least twice the highest signal frequency. This is known as the Nyquist sampling criterion. If this criterion is not met, then a deeply unpleasant form of signal corruption takes place, known as aliasing (see Ref. 1.1 or signal processing text for further details). Anti-aliasing filtering may therefore be required to ensure that the Nyquist criterion is satisfied.

11.2.3 The Analog Multiplexer

If there are to be multiple inputs, then an analog multiplexer is used. The alternative, of multiple ADCs, is both costly and space consuming. The multiplexer acts as a selector switch, choosing which input out of several is connected to the ADC at any one instant. The multiplexer is built around a set of semiconductor switches. It is important to know that the semiconductor switch is an imperfect device. In particular, when switched 'on', it has internal series resistance, which can range from tens to thousands of ohms. This can impact on the data acquisition process, as we shall see.

11.2.4 Sample and Hold, and Acquisition Time

Because most ADCs are unable to convert accurately a changing voltage, a sample and hold (S&H) circuit is often found. This takes a sample of the voltage, like a snapshot, and holds it steady for the duration of the conversion. A circuit of a simple but practical S&H is shown in Figure 11.3. At its heart are just a semiconductor switch and a capacitor. When the switch is closed, the capacitor charges up to the input voltage VS. At this moment, ideally VO = VC = VS, as the buffer amplifier just has unity gain. When the switch opens, the charge is left on the capacitor and VC (and hence VO) remains at a fixed value. In practice there is some leakage from the

166

Page 167: Mpmc 11 Marks

capacitor, so the output voltage drifts. This circuit is sometimes also called track and hold, as when the switch is closed the output voltage follows, or tracks, the input.

Figure 11.3: A simple form of sample and hold circuit

One problem with this simple circuit is that there is inevitably series resistance in the signal path. This is represented by the resistor in the circuit. When the switch closes, therefore, the capacitor voltage VC does not take on the signal voltage immediately, but rises towards it exponentially. This is shown in Figure 11.4. The voltage rise is given by:

(11.1)

Figure 11.4: Exploring acquisition time (not to scale)

Our interest from a data acquisition point of view is to ensure that the voltage has risen sufficiently close to its final value with the switch closed, before the switch is opened (the signal is then 'held'), and a conversion allowed to start. The time that VC (and hence VO) takes to reach a value deemed to be acceptable is called the acquisition time.

Let us suppose that VC must rise to 90 per cent of its final value, VS. Then, substituting into equation (11.1):

0.9VS = VS1 - exp(-t/RC)exp(-t/RC)= 1 - 0.9

-t= RC ln(0.1)t= 2.3RC.

167

Page 168: Mpmc 11 Marks

This is shown in Figure 11.4. It is, however, an undemanding requirement. To ensure good accuracy in data conversion, the error introduced by this process should be less than the equivalent of half of 1 LSB. Hence, for 8-bit conversion, this implies that the acquired voltage value VC must reach ≥ (511/512)VS, or 0.9980VS. For 10-bit conversion it must be ≥ (2047/2048)VS, or 0.9995VS.

Following the calculation above, but substituting the 10-bit value in, we get:

- t= RC ln(1/2048)t= 7.6RC.

The resulting acquisition times are shown in Figure 11.4. It is clear that acquisition time increases with increasing resistance, capacitance and with accuracy required. We will meet practical application of this calculation later in the chapter.

It is worth noting that the multiplexer circuit and S&H circuit can be merged into one, with the multiplexer switches forming the S&H switch. This is common practice.

11.2.5 Timing and Microprocessor Control

Usually, a data acquisition system is under the control of a microprocessor or microcontroller. This can control the overall system timing, including which input is being selected, when the selected signal is sampled and when the conversion starts.

The process of a single conversion can be represented as a flow diagram, as shown in Figure 11.5. Two major time requirements need to be satisfied — the acquisition time (of the S&H) and the conversion time (of the ADC).

168

Page 169: Mpmc 11 Marks

Figure 11.5: Typical timing requirement of one A-to-D conversion

Once the system is initialised, the multiplexer switch can be set. The S&H can then start its sample process. A period of time equal to or greater than the required S&H acquisition time must elapse. The ADC can then start its conversion. Again, this takes finite time. The ADC flags when it has completed a conversion and the microprocessor can read the output data.

11.2.6 Data Acquisition in the Microcontroller Environment

Embedded systems need ADCs, so it is natural to expect to find an ADC integrated onto a microcontroller as one of its peripherals. It is important, however, to realise that ADCs and microcontrollers do not make happy bedfellows. To operate to a good level of accuracy, an ADC needs a quiet life (electronically speaking), with excellent and clean power supply and ground, and freedom from electromagnetic interference. A microcontroller, on the other hand, being a digital device, tends to corrupt its power supply and ground with a voltage spike on every switching edge. As a consequence, with all its intensive internal digital activity, it radiates a smog of local interference. Therefore, to integrate an ADC onto a microcontroller is at best a compromise and high accuracy is not usually possible.

Despite this, ADCs are widely available in the microcontroller environment, with many microcontrollers having an on-chip ADC. These are mostly 8- or 10-bit.

169

Page 170: Mpmc 11 Marks

The PIC® 16F87XA ADC Module

11.3.1 Overview and Block Diagram

The 16F87XA has a versatile and powerful 10-bit ADC module, shown in Figure 11.6. This provides a subset of the overall data acquisition system shown in Figure 11.1, having an ADC, a multiplexer and the possibility of using the supply voltage as the voltage reference. The particular ADC design used incorporates in an interesting way the function of sample and hold, discussed further in Section 11.3.3.

Figure 11.6: The 16F87XA analog-to-digital converter (supplementary labels in shaded boxes added by the author)

The input multiplexer, seen to the right of the diagram, has five channels for the 16F873A and F875A, and eight for the 16F874A and F876A. The inputs are shared with five of the six Port A bits and three of the eight Port E (for 16F874 and F876) bits. Only Port A bit 4 is not used, as it already shares with the important Timer 0 input. Port bits can be allocated in a flexible way to analog or digital input, according to settings in an SFR.

An external voltage reference can be used for applications requiring reasonable accuracy, with terminals for both positive and negative connections provided. Provision of the negative connection means that the reference does not have to be referred to system ground. For lower-cost, lower-accuracy conversions, the power supply voltage can be used as reference. The input range is equal to whatever voltage reference is chosen.

11.3.2 Controlling the ADC

The ADC is controlled by two SFRs, ADCON0 (Figure 11.7) and ADCON1 (Figure 11.8). The result of the conversion is placed in two further SFRs, ADRESH and ADRESL. These four registers can all be seen in Figure 7.6. Other SFRs also have an important impact on the ADC. These include TRISA and (for the 40-pin devices) TRISE. Any bits used for analog input must

170

Page 171: Mpmc 11 Marks

be set as inputs in these. Registers PIR1 and PIE1, which contain the ADC interrupt flag and interrupt enable bits respectively, are also used.

Figure 11.7: The ADCON0 register (address 1FH)

DC Motors

Motion is one of the primary differentiators between a robot and a computer. More robots get their motion from DC (Direct Current) motors than from any other mechanism (see Figure 17-1).

Figure 17-1: Ordinary DC motor

This chapter details the different varieties of DC motors and their characteristics. If you don't find this subject interesting, you can skim this chapter and move on to the next. Motors won't be selected and attached to the line-following robot circuit until the next chapter.

171

Page 172: Mpmc 11 Marks

How DC Motors Work

In an electric motor, electricity is converted to motion by magnetism.

Most people have played with a pair of magnets. Placing the magnets facing each other causes the magnets to attract and pull together. Turning one of the magnets around causes the pair to repel each other and push apart.

One magnet can attract with enough strength to drag the other magnet across a surface. This technique can be improved by adding a third magnet. The first magnet attracts the second magnet, while the third magnet repels from the rear.

When magnets are mounted around a pole, the combination of pulling and pushing can result in a rotating motion. A magnet on the shaft or pole is attracted to a magnet mounted nearby, while simultaneously being repelled by another magnet mounted on the opposite side. As soon as the shaft rotates to the magnet pulling it, the shaft magnet flips polarity and starts pushing away.

The key to making this mechanism operate is that flowing electricity can create a magnetic field. Instead of physically flipping over a magnet to change from attract to repel, the flow of electricity can be flipped forwards and backwards.

Looking inside an Iron-Core Permanent-Magnet DC Brush Motor

An iron-core permanent-magnet DC brush motor (see Figure 17-2) consists of two major sections: the stationary parts (stator) and the rotating parts (rotor). The cap, also called the endcap or assembly, at the end of the motor is connected to the stator and doesn't move.

Figure 17-2: Guts of an ordinary DC motor: (left to right) stator with permanent magnets mounted near the outside walls; rotor with shaft, armature, windings, and commutator; and cap with brushes

Stator

The classic stator (the stationary part) includes two permanent magnets mounted opposite each other in a metal can (see Figure 17-3). The term "permanent magnets" indicates that the magnets remain magnetized even when the electricity is turned off. The magnetic field created by the electricity is going to push and pull against these two permanent magnets.

172

Page 173: Mpmc 11 Marks

Figure 17-3: A pair of permanent magnets removed from the metal can. The clip in the foreground keeps the magnets from sliding together

At high enough temperatures (Curie temperature), permanent magnets lose their magnetic field, resulting in reduced performance or even complete failure. Therefore, it's important not to abuse a motor by allowing it to overheat during use. Provide for adequate ventilation and, if possible, mount the motor body against other metal objects to provide a large thermal path to wick away the heat.

Interestingly, the metal container that makes up the body of the motor acts as a return path for the magnetic field. As such, less of the magnetic field is "leaked" into nearby components.

Rotor

The rotor (the rotating part) is built around a shaft. The shaft sticks out the end of the motor body so that wheels, belts, fan blades, or gears can be connected to it.

To limit friction, only a small portion of the rotor touches the motor body. High-quality motors and large motors often include ball bearings at those locations to improve carrying strength and decrease friction.

Rotor Windings

In the middle of the shaft is an armature containing many windings of wire (see Figure 17-4). The wire carries the electricity around and around an iron core in an oval loop. This increases the magnetic field that pushes and pulls against the permanent magnets on the stator.

173

Page 174: Mpmc 11 Marks

Figure 17-4: Motor shaft and armature with wire windings and an iron-based core

Besides generating and transmitting the magnetic field, the iron core also dissipates and evenly distributes heat, allowing for hard running. However, the relatively heavy iron core makes it more difficult to start or stop the shaft because of inertia.

Note Almost all motors have three or more windings. Motors with only two windings wouldn't necessarily rotate in the same direction at power up, nor would they necessarily rotate all the way around. For example: Initially the shaft would rotate toward the first magnet, but then the windings reverse, so it might rotate back the way it came. Hopefully, inertia would carry the rotor around in the direction it was already going.

Rotor Shoes

At the ends of the armature are metal plates; each group is called a shoe. Motors with only a couple of shoes tend to start up unevenly and settle oddly when stopping. The irregular rotation is called cogging.

With power disconnected, it's easy to feel for cogging by gently turning the shaft with your fingers. Spin the shaft and watch it slow down. Better motors have smoother operation by increasing the number of shoes and by slanting the shoes' angles so one end overlaps the other relative to the magnets.

Rotor Commutator

At the end of the shaft is a commutator (see Figure 17-5). It contains two or more segments to receive the electricity for the armature windings. Because the commutator segments are electrical contacts, it's important that they do not become soiled or coated in any non-conductive lubricant.

174

Page 175: Mpmc 11 Marks

Figure 17-5: Motor commutator

The commutator is necessary because power wires need to be attached to the armature windings. However, the wires can't be attached directly because they'd tangle up as the rotor turned. Instead, the commutator slides between metal brushes (see Figure 17-6) to make an electrical connection between the power wires coming in from the cap and the wire windings in the armature.

Figure 17-6: Shaft installed in the cap with brushes pressed against the commutator

As the commutator rotates around, sometimes a winding is connected to the positive and negative terminals of the battery, and sometimes a winding is connected in reverse. This feature flips the electrical flow forwards and backwards. Thus, the magnetic field flips between attract and repel.

A great thing about the commutator mechanism is that the flipping automatically speeds up as the motor turns faster!

Rotor Brushes

The "brush" term in "DC brush motor" indicates that the motor has brushes. The brushes connect directly to the battery or other power source. As stated earlier, the brushes press against the commutator to make the connection between the battery and the armature windings. The brushes must press firmly (see Figure 17-7) or else the electrical connection breaks and the electrical flow ceases.

175

Page 176: Mpmc 11 Marks

Figure 17-7: Brushes with pads pressed against each other because the motor shaft has been removed

There are a couple of downsides to brushes. First, the pressing of the brushes against the rotor adds friction, thus slowing down the motor and increasing heat. Second, the constant making and breaking of contacts generates electrical noise (like television static when a vacuum cleaner is run) and causes sparking. Last, but most important, the brushes wear out.

Even the most well-made, well-maintained brush motor is eventually going to encounter brush failure. Brush degeneration is caused more by sparking than by friction. High-end brush motors have capacitors to absorb sparks and the motors are designed to be serviceable to replace the brushes

176

Page 177: Mpmc 11 Marks

Figure 11.8: The ADCON1 register (address 9FH)

The control possibilities are now described, in the approximate sequence they would be used.

Switching On

The ADC is switched on and off by the ADON bit of ADCON0. Switching it off when not needed offers a slight power-saving advantage.

Setting the Conversion Speed

Operation of the 16F87XA ADC is governed by the ADC clock, which has a period TAD. A full 10-bit conversion takes around 12 TAD cycles, depending slightly on which clock source is chosen. The user can select the clock frequency from a number of options. Although one generally wants a conversion to take place as quickly as possible, there is an upper limit to the clock frequency. For the 16F87XA the minimum clock period for correct operation is specified as 1.6 µs (from the Electrical Characteristics of Ref. 7.1), or a frequency of 625 kHz. This implies a fastest conversion time of 19.2 µs. At the other extreme, if conversion is too slow, charge leaks from the storage capacitance and the conversion becomes inaccurate. Best practice is therefore to set the ADC clock frequency such that it has a period equal to or just less than 1.6 µs.

177

Page 178: Mpmc 11 Marks

Selection of the ADC clock source is controlled by bits ADCS2 in ADCON1, and ADCS1 and ADCS0 in ADCON0, as seen in Figure 11.7. This shows that various divisions of the main clock frequency are possible. There is also a dedicated RC oscillator which can be chosen. This has a typical period of 4 µs, but may range from 2 to 6 µs.

If the system clock is fast, it is usually appropriate to use it to derive the clock source. If the system clock is slow, however, it is better to use the RC oscillator. The dividing line between a 'slow' and 'fast' clock oscillator here is around 500 kHz. With an internal oscillator running at this speed, the fastest ADC clock that can be derived from it is 250 kHz. This gives a period of 4 µs, equal to the typical RC oscillator period. If the main oscillator is lower than this frequency, it will then generally be advisable to use the RC oscillator.

Configuring the Input Channels and Selecting the Voltage Reference

The way the input port bits are used is defined by the setting of bits PGFC3 to PGFC0 of ADCON1. It is worth looking at this closely in Figure 11.8. The variety of opportunity is impressive, both in terms of input channels and voltage reference. We can see that it ranges from just a single Port A channel used for input (PGFC3:PGFC0 = 1110) to all eight analog inputs in play (PGFC3:PGFC0 = 0000). Many combinations which include an external reference are also possible. Note again that any port pin that is to be used as an analog input must be set as an input in its TRIS register. Otherwise, the pin will act as an output and the (unintended) digital output value will be converted!

Selecting the Input Channel

The input channel is selected by the channel select bits CHS2 to CHS0 in ADCON0. These bits determine which switch in Figure 11.6 is closed. Making this selection is usually the first step in the data acquisition process, as we shall see below.

Starting a Conversion and Flagging its End

A conversion is initiated by setting bit GO/DONE in register ADCON0. When the conversion is complete the bit is returned to zero by the hardware. Completion of conversion is also signalled by an ADC interrupt flag ADIF, as seen in Figure 7.10. Completion of conversion may therefore be detected by testing either of the bits GO/DONE or ADIF, or by enabling the interrupt and responding to it in an ISR.

Formatting the Result

The result of the conversion is placed in registers ADRESH and ADRESL. Two possible result formats are possible, as shown in Figure 11.9. The result can be left justified, in which case the 8 most significant bits appear in ADRESH. This is useful if only an 8-bit result is required, as the contents of ADRESL can then be ignored. In most other cases a right-justified result will be the more useful. The formatting is controlled by bit ADFM in ADCON1.

178

Page 179: Mpmc 11 Marks

Figure 11.9: Formatting the ADC conversion result

11.3.3 The Analog Input Model

It was demonstrated earlier in this chapter that an understanding of the actual signal path is necessary in order to understand and predict system characteristics. Figure 11.10 is a diagram of the signal path for this ADC — and what an obstacle course it appears to be! This diagram is effectively a real-life representation of parts of Figure 11.6, shown from the signal's point of view.

Figure 11.10: The 16F87XA ADC input model

The signal source, together with internal resistance, is depicted to the left of the diagram, modelled as voltage source in series with internal resistance. The signal voltage enters the microcontroller through the pin labelled ANx. There is a small input capacitance (5 pF), and the input protection diodes and other input circuitry clearly have the potential to leak current into the signal path. The signal then passes through the interconnect resistance, RIC, before reaching the multiplexer switch. This is one of the switches of the analog input multiplexer in Figure 11.6. The internal resistance of this switch, RSS, is shown. The approximate value of this is dependent on supply voltage and is given by the small graph on the bottom right of Figure 11.10. From this we see that the switch resistance is a sobering 7 kΩ approximately, when the supply voltage is 5 V.

The ADC itself is a so-called switched capacitor type (Ref. 1.1, Chapter 5). First of all, that means that the ADC has internal capacitance, which must be charged up to the input voltage before a conversion can start. Neatly, however, this capacitance takes on the function of the S&H

179

Page 180: Mpmc 11 Marks

capacitor. On the downside, the capacitance, all 120 pF of it, must be charged up in the first place.

11.3.4 Calculating Acquisition Time

In Ref. 7.1 Microchip define three sources of time delay in their calculations for acquisition time, tac, as shown:

(11.2)

The reference specifies the amplifier settling time as a fixed 2 µs. The temperature coefficient applies only when temperature is above 25°C and is specified as:

Temperature coefficient = (Temperature - 25°C)(0.05 µs/°C).

It can be seen that this creates a time delay of only 0.5 µs for every 10° above 25°, so its impact in most cases is slight.

It is the capacitor charging time that dominates the acquisition time, which we now explore. The analog input model of Figure 11.10 can be related back to the S&H diagram of Figure 11.3 and equation (11.1). To analyse this, we neglect the effects of the input leakage current and the small input capacitance. Actual values for R and C in Figure 11.3 for the 16F87XAADC can be extracted from Figure 11.10. R is made up of (RSS +RIC +RS), or (1k + 7k + RS), for a supply voltage of 5 V. C is the 120 pF shown. Calculations made for Figure 11.4 showed us that, for 10-bit accuracy, an acquisition time of 7.6RC was needed. Substituting values in, assuming at first negligible source resistance, gives:

tac = 7.6RC = 7.6(1k + 7k)120 pF = 7.3 µs.

If amplifier settling time is added to this, as it must be, the acquisition time rises to 9.3 µs.

This represents a best possible value. To determine the overall time needed to complete a single conversion, this acquisition time must be added to the conversion time, discussed in Section 3.2. There, a best possible conversion time of 19.2 µs was deduced. Adding this to the best possible acquisition time leads to a total time to complete a conversion of (2 + 7.3 + 19.2) µs, i.e. 28.5 µs.

In many cases the source resistance is not negligible and any external series resistance will degrade the acquisition time calculated above. In Ref. 7.1 Microchip recommend a maximum source resistance of 2.5 kΩ. In this case:

tac = 7.6(1k + 7k + 2.5k)120 pF = 9.6 µs.

180

Page 181: Mpmc 11 Marks

Note that this is not the highest acquisition time that may be encountered, as the maximum allowed source resistance is specified in Ref. 7.1 as being 10 kΩ.

11.3.5 Repeated Conversions

When a conversion is complete, the converter waits for a period of 2 × TAD before it is available to start a new conversion cycle. Once this time is up, either the same input channel may be converted again, or a new one (which may already have been selected).

A best possible conversion time of 28.5 µs was calculated in Section 11.3.4. If a period of 2×TAD is added to this, i.e. 3.2 µs for fastest possible, then the complete conversion cycle time becomes 31.7 µs. If successive conversions are intended, this implies a maximum sampling rate of around 30 kHz. Note, however, that this figure takes no account of software overheads, which would tend to slow the conversion rate.

11.3.6 Trading Off Conversion Speed and Resolution

The conversion times deduced above are not particularly fast by today's standards and there will be occasions when a faster conversion time is needed. While one option is to use an external ADC, another is to consider whether the full 10-bit resolution is needed. If it is not, then the conversion time can be reduced. One technique, described in Ref. 11.1, is to start a conversion with a valid ADC clock frequency and then to switch it during the conversion to a faster speed, which violates the clock specification. The higher order bits converted before the switch will be valid and can be used. Those converted after will not be valid. A lower resolution conversion, at higher speed, has thus been achieved. It is up to the program, however, to determine when the switch should take place.

An alternative approach is to reduce the acquisition time, as suggested in Figure 11.4, so that, for example, the acquisition is only to 8-bit accuracy. The conversion can then be allowed to run its full course. The switching of the ADC clock frequency, as just described, can still be implemented.

che Application of the PIC24FJ Microcontroller with the 240x128 LCD Display and the Analog Accelerometer Sensor.

The source code has been written in C (C30 compiler). The sensor used is Freescale MMA7260QT, accommodated on the sensor board of Sure Electronics. For the convenience we put the board with sensor to the metal box as shown in the figure.

181

Page 182: Mpmc 11 Marks

Figure 41: The accelerometer MMA7260QT, accommodated on the sensor board

Schematic diagram of the accelerometer with operational amplifiers is shown in figure 42.

Figure 42: The accelerometer MMA7260QT, schematic diagram

Figure 43: The accelerometer application circuit.

After powering up, the program waits for pressing the switch (connected to RC3). Then on the LCD display appears the text: "a_z = ". Also on the left side of the screen appear in the first column the marks "-". They allow to imagine, where is the Mid of the vertical scale.

182

Page 183: Mpmc 11 Marks

Now system waits for data from accelerometer attached to the cable. When we shake the box with accelerometer, then the processor calculates if data from sensor are greater than sensor noise. If so, then 22 results are collected.

Reason of the number 22 is, that in the application LCD operates in the text mode. It has 30 columns and 16 rows. Last 7 columns are reserved for numerical values of the data, while the first column has scale marks. Therefore only 30 - 7 - 1 = 22 results are needed for scattergram.

First the data are collected and saved in the array. After finishing the sequence the scattergram is plotted in the text mode and first numeric values are presented on the screen, as shown in figures a, b and c.

Figure 44: Scattergram with data from accelerometter

Those values are raw data not converted to acceleration units, nor to mVolts yet. For 10-bits ADC module they are in the range of 0 to 1024. The center of the scattergram is about the value of 500. For better clarity we truncated lowest and highest part of the scale.

Application runs according to following two flowcharts:

183

Page 184: Mpmc 11 Marks

Figure 45: Aplication flowchart nr 1

184

Page 185: Mpmc 11 Marks

Figure 46: Aplication flowchart nr 2

185


Top Related