Microprocessor and Microcontroller (III EEE)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 270

CONTENTS

1 Unit-I : 8086 ARCHITECTURE Page NO


1.1 Introduction 1
1.2 Unit-I notes 1-33
1.3 Part A Questions 34
1.4 Part B Questions 34
2 Unit-II : Instruction Set And Assembly Language 36-97
Programming of 8086
2.1 8086 Instruction Set 36
2.2 Unit-II notes 36-94
2.3 Part A Questions 95
2.4 Part B Questions 96-97
3 Unit-III : MSP 430 98-164
3.1 Introduction 98
3.2 Unit-III notes 98-164
3.3 Part A Questions 164
3.4 Part B Questions 164
4 Unit-IV : Timers 165-222
4.1 Introduction 165
4.2 Unit-IV notes 166-221
4.3 Part A Questions 222
4.4 Part B Questions 222
5 Unit-V : Serial Communication 223-268
5.1 Introduction 223
5.2 Unit-V notes 223-267
5.3 Part A Questions 267
5.4 Part B Questions 268
UNIT- I
8086 ARCHITECTURE
OVERVIEW OF 8086:

The INTEL 8086 is the first 16-bit processor released by INTEL in


the year 1978. 8086 is packed in a 40 pin DIP and requires a 5 Volt
supply. 8086 microprocessor has a much more powerful instruction set
along with the architectural developments which imparted substantial
programming flexibility and improvement in speed over the 8-bit
microprocessors.

The peripheral chips designed earlier for 8085 were compatible with
microprocessor 8086 with slight or no modifications. Though there is a
considerable difference between the memory addressing techniques of
8085 and 8086, the memory interfacing technique similar, but includes
the use of a few additional signals. The clock requirements are also
different as compared to 8085, but the overall minimal system
organization of 8086 is similar to that of a general 8-bit microprocessor.

The 8086 does not have internal clock circuit. The 8086 requires an
external asymmetric clock source with 33% duty cycle. The 8284 clock
generator is used to generate the required clock for 8086. The maximum
internal clock of 8086 is 5 MHz. The other versions of 8086 with different
.clock rates are 8086-1, 8086-2 and 8086-4 with maximum internal clock
frequency of 10MHz, 8MHz and 4MHz respectively.

The 8086 uses a 20-bit address to access memory and hence it can
directly address upto one megabytes (220 = 1 Mega) of memory space.
The one megabytes (1 Mb) of addressable memory space of 8086 are
organised as two memory banks of 512 kilobytes each (512 kb + 512 kb
1Mb). The memory banks are called even (or lower) bank and odd (or
upper) bank. The address line A0 is used to select even bank and the
control signal BHE is used to select odd bank.

1
For accessing I/O mapped devices, the 8086 uses a separate 16-bit
address, and so the 8086 can generate 64k (2 16) I/O addresses. The
signal M /IO is used to differentiate the memory and I/O addresses. For
memory address the signal M /IO is asserted high and for I/O address
the signal M /IO is asserted low by the processor.

The 8086 can operate in two modes, and they are minimum mode
and maximum mode. The mode is decided by a signal at MN/MX pin.
When the MN/MX is tied high, it works in minimum mode and the system
is called uniprocessor system. When MN / MX is tied low, it works in
maximum mode and the system is called multiprocessor system. Usually
the pin MN/ MX is permanently tied to low or high so that the 8086
system can work in any one of the two modes. The 8086 can work with
8087 coprocessor in maximum mode. In this mode an external bus
controller 8288 is required to generate bus control signals

The 8086 has two family of processors. They are 8086 and 8088.
The 8088 uses 8-bit data bus externally but 8086 uses 16-bit data bus
externally. The 8086 access memory in words but 8088 access memory in
bytes. The IBM designed its first personal computer (PC) using INTEL
8088 microprocessor as CPU.

FEATURES OF 8086:
• It is a 16-bit μp.
• 8086 has a 20 bit address bus can access up to 2^20 memory

locations (1 MB).
• It can support up to 64K I/O ports.

• It provides 14, 16 -bit registers.


• It has multiplexed address and data bus AD0- AD15 and A16 –
A19.
• It requires single phase clock with 33% duty cycle to provide

internal timing.
• 8086 is designed to operate in two modes, Minimum and
Maximum.
2
• It can pre-fetches up to 6 instruction bytes from memory and
queues them in order to speed up instruction execution.
• It requires +5V power supply.

• A 40 pin dual in line package.

ARCHITECTURE OF 8086:
 8086 has two blocks BIU and 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 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, IP, address adder.
 EU contains control circuitry, Instruction decoder, ALU, Flag register.

3
Bus Interface Unit:
 It provides full 16 bit bidirectional data bus and 20 bit address bus.
 The BIU is responsible for performing all external bus operations.
Specifically it has the following functions:
 Instructions 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 pipeline architecture.
 This queue permits pre-fetch of up to six bytes of instruction code.
Whenever 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

4
operands from memory, the BIU is free to look ahead in the program by
pre-fetching the next sequential instruction.
 These pre-fetching 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 bus 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 20
bit 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.

Physical address generation

Thus, Physical Address = Segment Register content 16 D + Offset

5
 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 EU extracts instructions from 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 bus 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.

PIN OUT SIGNALS AND FUNCTIONS OF 8086:

The microprocessor 8086 is a 16-bit CPU available in three clock


rates, i.e. 5, 8 and 10 MHz, packaged in a 40 pin CERDIP or plastic
package. The 8086 operates in single processor or multiprocessor
configurations to achieve high performance. The pin configuration is
shown in Fig. 1.1. Some of the pins serve a particular function in
minimum mode (single processor mode) and others function in maximum
mode (multiprocessor mode) configuration.

The 8086 signals can be categorised in three groups. The first are
the signals having common functions in minimum as well as maximum

6
mode, the second are the signals which have special functions for
minimum mode and the third are the signals having special functions for
maximum mode.

The following signal descriptions are common for both the minimum and
maximum modes.

AD15 -- AD0: These are the time multiplexed memory I/O address and
data lines. Address remains on the lines during T 1 state, while the data is
available on the data bus during T 2, T3, Tw and T4. Here T2, T3, T4 and Tw
are the clock states of a machine cycle. T w is a wait state. These lines are
active high and float to a tristate during interrupt acknowledge and local
bus hold acknowledge cycles.

7
A19/S6, A18/S5, A17/S4, A16/S3: These are the time multiplexed address
and status lines. During T1, these are the most significant address lines
for memory operations. During I/O operations, these lines are low. During
memory or I/O operations, status information is available on those lines
for T2, T3, Tw and T4. The status of the interrupt enable flag bit (displayed
on S5) is updated at the beginning of each clock cycle. The S4 and S3
combinedly indicate which segment register is presently being used for
memory accesses as shown in Table 1.1. These lines float to tri-state off
(tristated) during the local bus hold acknowledge. The status line S6 is
always low (logical). The address bits are separated from the status bits
using latches controlled by the ALE signal.

BHE / S7-Bus High Enable/Status: The bus high enable signal is used
to indicate the transfer of data over the higher order (D 15—D8) data bus
as shown in Table 1.2. It goes low for the data transfers over D15—D8 and
is used to derive chip selects of odd address memory bank or peripherals.
BHE is low during T1 for read, write and interrupt acknowledge cycles,
whenever a byte is to be transferred on the higher byte of the data bus.
The status information is available during T2, T3 and T4. The signal is
active low and is tristated during ‘hold’. It is low during T1 for the first
pulse of the interrupt acknowledge cycle.

Table 1 .2 Bus High Enable/Status

BHE A0 Indications

0 0 Whole Word

0 1 Upper byte from or


to odd address

1 0 Lower byte from or


to even address

8
1 1 None

RD-Read Read signal, when low, indicates the peripherals that the
processor is performing a memory or I/O read operation. RD is active low
and shows the state for T2, T3, Tw of any read cycle. The signal remains
tristated during the ‘hold acknowledge’.

READY This is the acknowledgement from the slow devices or memory


that they have completed the data transfer. The signal made available by
the devices is synchronized by the 8284A clock generator to provide
ready input to the 8086. The signal is active high.

INTR- Interrupt Request This is a level triggered input. This is sampled


during the last clock cycle of each instruction to determine the availability
of the request. If any interrupt request is pending, the processor enters
the interrupt acknowledge cycle. This can be internally masked by
resetting the interrupt enable flag. This signal is active high and internally
synchronized.

TEST This input is examined by a ‘WAIT’ instruction. If the TEST input


goes low, execution will continue, else, the processor remains in an idle
state. The input is synchronized internally during each clock cycle on
leading edge of clock.

NMI-Non-maskable Interrupt This is an edge-triggered input which


causes a Type2 interrupt. The NMI is not maskable internally by software.

9
A transition from low to high initiates the interrupt response at the end of
the current instruction. This input is internally synchronized.

RESET This input causes the processor to terminate the current activity
and start execution from FFFF0H. The signal is active high and must be
active for at least four clock cycles. It restarts execution when the RESET
returns low. RESET is also internally synchronised.

CLK-Clock Input The clock input provides the basic timing for processor
operation and bus control activity. Its an asymmetric square wave with
33% duty cycle. The range of frequency for different 8086 versions is
from 5MHz to 10MHz.

Vcc +5V power supply for the operation of the internal circuit.

GND ground for the internal circuit.

MN/ MX The logic level at this pin decides whether the processor is to
operate in either minimum (single processor) or maximum
(multiprocessor) mode.

The following pin functions are for the minimum mode operation of
8086.

M / I/O -Memory/IO This is a status line logically equivalent to S2 in


maximum mode. When it is low, it indicates the CPU is having an I/O
operation, and when it is high, it indicates that the CPU is having a
memory operation. This line becomes, active in the previous T 4 and
remains active till final T4 of the current cycle. It is tristated during local
bus “hold acknowledge”.

INTA -Interrupt Acknowledge This signal is used as a read strobe for


interrupt acknowledge cycles. In other words, when it goes low, it means
that the processor has accepted the interrupt. It is active low during T 2,
T3, and Tw of each interrupt acknowledge cycle.

10
ALE-Address Latch Enable This output signal indicates the availability
of the valid address on the address/data lines, and is connected to latch
enable input of latches. This signal is active high and is never tristated.

DT / R-Data Transmit/Receive This output is used to decide the


direction of data flow through the transreceivers (bidirectional buffers).
When the processor sends out data, this signal is high and when the
processor is receiving data, this signal is low. Logically, this is equivalent
to S1 in maximum mode. Its timing is the same as M/ I/O. This is tristated
during ‘hold acknowledge’.

DEN-Data Enable This signal indicates the availability of valid data over
the address/data lines. It is used to enable the transreceivers
(bidirectional buffers) to separate the data from the multiplexed
address/data signal. It is active from the middle of T 2 until the middle of
T4. DEN is tristated during ‘hold acknowledge’ cycle.

HOLD, HLDA-Hold /Hold Acknowledge When the HOLD line goes high,
it indicates to the processor that another master is requesting the bus
access. The processor, after receiving the HOLD request, issues the hold
acknowledge signal on HLDA pin, in the middle of the next clock cycle
after completing the current bus (instruction) cycle. At the same time, the
processor floats the local bus and control lines. When the processor
detects the HOLD line low, it lowers the HLDA signal. HOLD is an
asynchronous input, and it should be externally synchronized.

If the DMA request is made while the CPU is performing a memory or I/O
cycle, it will release the local bus during T 4 provided:

1. The request occurs on or before T2 state of the current cycle.


2. The current cycle is not operating over the lower byte of a word (or
operating on an odd address).
3. The current cycle is not the first acknowledge of an interrupt
acknowledge sequence.
4. A Lock instruction is not being executed.
11
The following pin functions are applicable for maximum mode operation
of 8086.

S2, S1, S0 - Status Lines These are the status lines which reflect the type
of operation, being carried out by the processor. These become active
during T4 of the previous cycle and remain active during T 1 and T2 of the
current bus cycle. The status lines return to passive state during T 3 of the
current bus cycle so that they may again become active for the next bus
cycle during T4. Any change in these lines during T3 indicates the starting
of a new cycle, and return to passive state indicates end of the bus cycle.
These status lines are encoded in Table 1.3.

Table 1 .3

S2 S1 S0 Indications

0 0 0 Interrupt
Acknowledge

0 0 1 Read I/O port

0 1 0 Write I/O port

0 1 1 Halt

1 0 0 Code Access

1 0 1 Read Memory

1 1 0 Write memory

1 1 1 Passive

LOCK This output pin indicates that other system bus masters will be
prevented from the system bus, while the LOCK signal is low. The LOCK
signal is activated by the LOCK prefix instruction and remains active until

12
the completion of the next instruction. This floats to tri-state off during
“hold acknowledge”. When the CPU is executing a critical instruction
which requires the system bus, the LOCK prefix instruction ensures that
other processors connected in the system will not gain the control of the
bus. The 8086, while executing the prefixed instruction, asserts the bus
lock signal output, which may be connected to an external bus controller.

QS1, QS0-Queue Status These lines give information about the status of
the code prefetch queue. These are active during the CLK cycle after
which the queue operation is performed. These are encoded as shown in
Table 1.4.

Table 1 .4

QS1 QS2 Indications

0 0 No operation

0 1 First byte of Opcode from the


queue

1 0 Empty queue

1 1 Subsequent byte from the queue

This modification in a simple fetch and execute architecture of a


conventional microprocessor offers an added advantage of pipelined
processing of the instructions. The 8086 architecture has a 6-byte
instruction prefetch queue. Thus even the largest (6-bytes) instruction
can be prefetched from the memory and stored in the prefetch queue.
This results in a faster execution of the instructions. In 8085, an
instruction (opcode and operand) is fetched, decoded and executed and
only after the execution of this instruction, the next one is fetched. By
prefetching the instruction, there is a considerable speeding up in

13
instruction execution in 8086. This scheme is known as instruction
pipelining.

At the starting the CS: IP is loaded with the required address from which
the execution is At the starting the CS: IP is loaded with the required
address from which the execution is to be started. Initially, the queue will
be empty and the microprocessor starts a fetch operation to bring one
byte (the first byte) of instruction code, if the CS: IP address is odd or
two bytes at a time, if the CS: IP address is even. The first byte is a
complete opcode in case of some instructions (one byte opcode
instruction) and it is a part of opcode, in case of other instructions (two
byte long opcode instructions), the remaining part of opcode may lie in
the second byte. But invariably the first byte of an instruction is an
opcode. These opcodes along with data are fetched and arranged in the
queue. When the first byte from the queue goes for decoding and
interpretation, one byte in the queue becomes empty and subsequently
the queue is updated. The microprocessor does not perform the next
fetch operation till at least two bytes of the instruction queue are
emptied. The instruction execution cycle is never broken for fetch
operation. After decoding the first byte, the decoding circuit decides
whether the instruction is of single opcode byte or double opcode byte. If
it is single opcode byte, the next bytes are treated as data bytes
depending upon the decoded instruction length, otherwise, the next byte
in the queue is treated as the second byte of the instruction opcode. The
second byte is then decoded in continuation with the first byte to decide
the instruction length and the number of subsequent bytes to be treated
as instruction data. The queue is updated after every byte is read from
the queue but the fetch cycle is initiated by BIU only if at least two bytes
of the queue are empty and the EU may be concurrently executing the
fetched instructions.

The next byte after the instruction is completed is again the first opcode
byte of the next instruction. A similar procedure is repeated till the

14
complete execution of the program. The main point to be noted here is
that the fetch operation of the next instruction is overlapped with the
execution of the current instruction. As shown in the architecture, there
are two separate units, namely, execution unit and bus interface unit
while the execution unit is busy in executing an instruction, after it is
completely decoded, the bus interface unit may be fetching the bytes of
the next instruction from memory, depending upon the queue status.
Figure 1.2 explains the queue operation.

RQ / GT0 , RQ / GT1 -Request/Grant These pins are used by other local

bus masters, in maximum mode, to force the processor to release the


local bus at the end of the processor’s current bus cycle. Each of the pins
is bidirectional with RQ / GT0 having higher priority than RQ / GT1 .

RQ / GT pins have internal pull-up resistors and may be left unconnected.

The request/grant sequence is as follows:

1. A pulse one clock wide from another bus master requests the bus
access to 8086.
2. During T4 (current) or T1 (next) clock cycle, a pulse one clock wide
from 8086 to the requesting master, indicates that the 8086 has
allowed the local bus to float and that it will enter the “hold

15
acknowledge” state at next clock cycle. The CPU’s bus interface unit
is likely to be disconnected from the local bus of the system.
3. A one clock wide pulse from another master indicates to 8086 that
the ‘hold’ request is about to end and the 8086 may regain control
of the local bus at the next clock cycle.

Thus each master to master exchange of the local bus is a sequence of


3 pulses. There must be at least one dead clock cycle after each bus
exchange. The request and grant pulses are active low. For the bus
requests those are received while 8086 is performing memory or I/O
cycle, the granting of the bus is governed by the rules as discussed in
case of HOLD and HLDA in minimum mode.

REGISTER ORGANIZATION OF 8086:

The 8086 has four groups of the user accessible internal registers.
They are the instruction pointer, four data registers, four pointer and
index register, four segment registers. The 8086 has a total of fourteen
16-bit registers including a 16 bit register called the status register,
with 9 of bits implemented for status and control flags.
There are four different 64 KB segments for instructions, stack, data
and extra data. To Specify where in 1 MB of processor memory these 4
segments are located the processor uses four segment registers:
• Code segment (CS) is a 16-bit register containing address of 64 KB
segment with processor instructions. The processor uses CS segment for

16
all accesses to instructions referenced by instruction pointer (IP) register.
CS register cannot be changed directly. The CS register is automatically
updated during far jump, far call and far return instructions.
• Stack segment (SS) is a 16-bit register containing address of 64KB
segment with program stack. By default, the processor assumes that all
data referenced by the stack pointer (SP) and base pointer (BP) registers
is located in the stack segment. SS register can be changed directly using
POP instruction.
• Data segment (DS) is a 16-bit register containing address of 64KB
segment with program data. By default, the processor assumes that all
data referenced by general registers (AX, BX, CX, DX) and index register
(SI, DI) is located in the data segment.DS register can be changed
directly using POP and LDS instructions.
• 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 low order byte of the word, 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 low order 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

17
operations. In integer 32-bit multiply and divide instruction the DX
register contains high-order word of the initial or resulting number.

The following registers are both general and index registers:


• Stack Pointer (SP) is a 16-bit register pointing to program stack.
• Base Pointer (BP) is a 16-bit register pointing to data in stack segment.
BP register is usually used for based, based indexed or register indirect
addressing.
• Source Index (SI) is a 16-bit register. SI is used for indexed, based
indexed and register indirect addressing, as well as a source data address
in string manipulation instructions.
• Destination Index (DI) is a 16-bit register. DI is used for indexed,
based indexed and register indirect addressing, as well as a destination
data address in string manipulation instructions.
Instruction Pointer (IP) register acts as a program counter for 8086. It
points to the address of the next instruction to be executed Its content is
automatically incremented when the program execution of a program
proceeds further. The contents of IP and CS register are used to compute
the memory address of the instruction code to be fetched.

FLAG REGISTER OF 8086:

It is a 16-bit register, also called flag register or Program Status


Word (PSW). Seven bits unused while the rest nine are used to indicate
the conditions of flags. The status flags of the register are shown below in
Fig.

18
Status flags of Intel 8086:

 Out of nine flags, six are condition flags and three are control flags.
The control flags
 are TF (Trap), IF (Interrupt) and DF (Direction) flags, which can be
set/reset by the
 programmer, while the condition flags [OF (Overflow), SF
(Sign), ZF (Zero), AF (Auxiliary
 Carry), PF (Parity) and CF (Carry)] are set/reset depending on
the results of some arithmetic or logical operations during program
execution.
 CF is set if there is a carry out of the MSB position resulting from an
addition operation or if a borrow is needed out of the MSB position
during subtraction.
 PF is set if the lower 8-bits of the result of an operation contains an
even number of 1’s. AF is set if there is a carry out of bit 3 resulting
from an addition operation or borrow required from bit 4 into bit 3
during subtraction operation.
 ZF is set if the result of an arithmetic or logical operation is zero.
 SF is set if the MSB of the result of an operation is 1. SF is used with
unsigned numbers.
 OF is used only for signed arithmetic operation and is set if the result
is too large to be fitted in the number of bits available to
accommodate it.

19
The three control flags of 8086 are TF, IF and DF. These three
flags are programmable, i.e., can be set/reset by the
programmer so as to control the operation of the processor.
 When TF (trap flag) is set (=1), the processor operates in single
stepping mode—i.e., pausing after each instruction is executed.
This mode is very useful during program development or program
debugging.
 When an interrupt is recognized, TF flag is cleared. When the CPU
returns to the main program from ISS (interrupt service subroutine),
by execution of IRET in the last line of ISS, TF flag is restored to its
value that it had before interruption.
 TF cannot be directly set or reset. So indirectly it is done by pushing
the flag register on the stack, changing TF as desired and then
popping the flag register from the stack.
 When IF (interrupt flag) is set, the maskable interrupt INTR is
enabled otherwise disabled (i.e., when IF = 0).
 IF can be set by executing STI instruction and cleared by CLI
instruction. Like TF flag, when an interrupt is recognized, IF flag is
cleared, so that INTR is disabled. In the last line of ISS when IRET is
encountered, IF is restored to its original value. When 8086 is reset,
IF is cleared, i.e., reset.
 DF (direction flag) is used in string (also known as block move)
operations. It can be set by STD instruction and cleared by CLD.
If DF is set to 1 and MOVS instruction is executed, the contents of the
index registers DI and SI are automatically decremented to access
the string from the highest memory location down to the lowest
memory location.

MEMORY SEGMENTATION:

The memory in an 8086/8088 based system is organised as


segmented memory. In this scheme, the complete physically available
memory may be divided into a number of logical segments. Each segment
20
is 64K bytes in size and is addressed by one of the segment registers. The
16-bit contents of the segment register actually point to the starting
location of a particular segment. To address a specific memory location
within a segment, we need an offset address. The offset address is also
16-bit long so that the maximum offset value can be FFFFH, and the
maximum size of any segment is thus 64K locations.

The CPU 8086 is able to address 1Mbytes of physical memory. The


complete 1Mbytes memory can be divided into 16 segments, each of
64Kbytes size. The addresses of the segments may be assigned as 0000H
to F000H respectively. The offset address values are from 0000H to ‘FFFH
so that the physical addresses range from 00000H to FFFFFH. In the
above said case, the segments are called non-overlapping segments. The
non-overlapping segments are shown in Fig. 1.6(a). In some cases,
however, the segments may be overlapping. Suppose a segment starts at
a particular address and its maximum size can be 64Kbytes. But, if
another segment starts before this 64Kbytes location of the first segment,
the two segments are said to be overlapping segments. The area of
memory from the start of the second segment to the possible end of the
first segment is called as overlapped segment area. Figure 1.6(b) explains
the phenomenon more clearly. The locations lying in the overlapped area
may be addressed by the same physical address generated from two
different Sets of segment and offset addresses.

21
The main advantages of the segmented memory scheme are as follows:

1.Allows the memory capacity to be 1Mbytes although the actual


addresses to be handled are of 16-bit size.

2.Allows the placing of code, data and stack portions of the same program
in different parts (segments) of memory, for data and code protection.

3.Permits a program and/or its data to be put into different areas of


memory each time program is executed, i.e. provision for relocation
may be done.

In the Overlapped Area Locations Physical Address = CS1 + IP1 =


CS2 + IP2 indicates the procedure of physical address formation.

GENERAL BUS OPERATION:


The 8086 has a combined address and data bus commonly referred
to as a time multiplexed address and data bus. The main reason behind
multiplexing address and data over the same pins is the maximum
utilization of processor pins and it facilitates the use of 40 pin standard

22
DIP package. The bus can be Demultiplexer using a few latches and
transreceivers, whenever required.
Basically, all the processor bus cycles consist of at least four clock
cycles. These are referred to as T1, T2, T3 and T4. The address is
transmitted by the

processor during T1. It is present on the bus only for one cycle. During
T2, i.e. the next cycle, the bus is tristated for changing the direction of
bus for the following data read cycle. The data transfer takes place during
T3 and T4. In case, an addressed device is slow and shows ‘NOT READY’
status the wait states Tw are inserted between T3 and T4. These clock
states during wait period are called idle states (Ti), wait states (Tw) or
inactive states. The processor uses these cycles for internal
housekeeping. The address latch enable (ALE) signal is emitted during T1
by the processor (minimum mode) or the bus controller (maximum mode)
depending upon the status of the MN/ MX input. The negative edge of this
ALE pulse is used to separate the address and the data or status
information. In maximum mode, the status lines S0 , S1 and S2 are used to

indicate the type of operation. Status bits S3 to S7 are multiplexed with

higher order address bits and the BHE signal. Address is valid during T1
while the status bits S3 to S7 are valid during T2 through T4. The Fig.1.7
shows a general bus operation cycle of 8086.

23
Minimum Mode 8086 System And Timings:

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.

The latches are generally buffered output D-type flip-flops, like,


74LS373 or 8282. They are used for separating the valid address from the

24
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 signal. They are
controlled by two signals, namely, DEN and DT/ R . The DEN signal
indicates that the valid data is available on the data bus, while
DT/ R indicates the direction of data, i.e. from or to the processor. The
system contains memory for the monitor and users program storage.
Usually, EPROMS are used for monitor storage, while RAMs for users
program storage. A system may contain I/O devices for communication
with the processor as well as some special purpose I/O devices. The clock
generator generates the clock from the crystal oscillator and then shapes
it and divides to make it more precise so that it can be used as an
accurate timing reference for the system. The clock generator also
synchronizes some external signals with the system clock. The general
system organization is shown in Fig. 1.8. Since it has 20 address lines and
16 data lines, the 8086 CPU requires three octal address latches and two
octal data buffers for the complete address and data separation.

The working of the minimum mode configuration system can be


better described in terms of the timing diagrams rather than qualitatively
describing the operations. The opcode fetch and read cycles are similar.
Hence the timing diagram can be categorized in two parts, the first is the
timing diagram for read cycle and the second is the timing diagram for
write cycle.

The read cycle begins in T1 with the assertion of the address latch
enable (ALE) signal and also M/IO signal. During the negative going edge
of this signal, the valid address is latched on the local bus. The BHE and
A0 signals address low, high or both bytes. From T1 to T4, the M/ IO signal
indicate a memory or I/O operation. At T2, the address is removed from
the local bus and is sent to the output. The bus is then tristated. The read
( RD ) control signal is also activated in T2. The read ( RD ) signal causes

25
the addressed device to enable its data bus drivers. After RD goes low,
the valid data is available on the data bus. The addressed device will drive
the READY line high. When the processor returns the read signal to high
level, the addressed device will again tristate its bus drivers.

A write cycle also begins with the assertion of ALE and the emission
of the address. The M/ IO signal is again asserted to indicate a memory or

I/O operation. In T2, after sending the address in T1, the processor sends
the data to be written to the addressed location. The data remains on the
bus until middle of T4 state. TheWR becomes active at the beginning of T2
(unlike RD is somewhat delayed in T2 to provide time for floating).

The BHE and A0 signals are used to select the proper byte or bytes
of memory or I/O word to be read or written.

The M/ IO , RD and WR signals indicate the types of data transfer as


specified in Table1.5.

M/ IO RD WR Indications

0 0 1 I/O Read

0 1 0 I/O Write

1 0 1 Memory
Read

1 1 0 Memory
Write
Figure 1.9(a)
shows the read cycle while the Fig. 1.9(b) shows the write cycle.

26
27
Maximum Mode 8086 System And Timings:

In the maximum mode, the 8086 is operated by strapping the


MN/ MX pin to ground. In this mode, the processor derives the status

signals S2 , S1 and S0 . Another chip called bus controller derives the control

signals using this status information. In the maximum mode, there may
be more than one microprocessor in the system configuration. The other
components in the system are the same as in the minimum mode system.

The basic functions of the bus controller chip 1C8288, is to derive


control signals like RD andWR (for memory and I/O devices), DEN ,

DT/ R , ALE, etc. using the information made available by the processor on

the status lines. The bus controller chip has input lines and S2 , S1 and S0

CLK. These inputs to 8288 are driven by the CPU. It derives the outputs

28
ALE, DEN , DT/ R , MRDC , MWTC , AMWC , IORC , IOWC and AIOWC.
The AEN , IOB and CEN pins are specially useful for multiprocessor

systems. 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 cascaded

8259A, else it acts as peripheral data enable used in the multiple


bus configurations. INTA pin is used to issue two interrupt acknowledge

pulses to the interrupt controller or to an interrupting device.

IORC, IOWCare 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 addressed port. The MRDC , MWTC are memory read

command and memory write command signals respectively and may be


used as memory read and write signals. All these command signals
instruct the memory to accept or send data from or to the bus. For both
of these write command signals, the advanced signals namely AMWC and
AIOWCare available. They also serve the same purpose, but are activated
one clock cycle earlier than the IOWC and MWTC signals, respectively.
The maximum mode system is shown in Fig. 1.10.

The maximum mode system timing diagrams are also divided in two
portions as read (input) and write (output) timing diagrams. The
address/data and address/status timings are similar to the minimum
mode. ALE is asserted in T1, just like minimum mode. The only difference
lies in the status signals used and the available control and advanced
command signals.

29
INTERRUPTS OF 8086:
An interrupt is the method of processing the microprocessor by
peripheral device. An interrupt is used to cause a temporary halt in the
execution of program. Microprocessor responds to the interrupt with an
interrupt service routine, which is short program or subroutine that
instructs the microprocessor on how to handle the interrupt.
There are two basic type of interrupt, maskable and non-maskable,
non-maskable interrupt requires an immediate response by
microprocessor, it usually used for serious circumstances like power
failure. A maskable interrupt is an interrupt that the microprocessor can
ignore depending upon some predetermined upon some predetermined
condition defined by status register.

Interrupt can be divided in to five groups:


1.hardware interrupt
2.Non-maskable interrupt
3.Software interrupt
4.Internal interrupt
5.Reset
Hardware, software and internal interrupt are service on priority basis.
Each interrupt is given a different priority level by assigning it a type

30
number. Type 0 identifies the highest-priority and type 255 identifies the
lowest-priority interrupt.
The 80x86 chips allow up to 256 vectored interrupts. This means
that you can have up to 256 different sources for an interrupt and the
80x86 will directly call the service routine for that interrupt without any
software processing. This is in contrast to non-vectored interrupts that
transfer control directly to a single interrupt service routine, regardless of
the interrupt source.

Memory (I/O) address assignment

Each memory chip covers a section of memory address

By analyzing the addresses for a single chip, we find:

1) Several most significant bits are in common.


2) Several least significant bits various from zeros to ones.
 Example: 4K * 8-bit chip starting at 10000h
From 10000h to 10FFF
31
0001 0000 0000 0000 0000

0001 0000 1111 1111 1111

 What if we have a chip containing 4000 bytes?


Then, no such easy break up...

We prefer memory chip sizes like 256,512,1024…

3) The higher part is for CS logic, while the lower part is connected to the chip directly.
Difference between 8088 and 8086

A0
A1
/BHE
8-bit A0
8-bit
D0~D7
Memory
A19
CS ?
8086 CPU
A0
A1 CS ?
8-bit
D8~D15 A19
Memory 8-bit
A19

1) What is the supported memory size of 8088? And 8086?


2) 8086 is fully compatible with 8088.
a) All programs for 8088 must work for 8086.
b) Byte-based memory accesses are the same.
c) Word-based memory accesses are partially optimized.
i. Word alignment matters. See the example:
A word at address A0000h and A0001h

…0000 …0001

32
…0001 …0010

ii. Only even-addressed words will be loaded in one cycle in 8086 processors.
3) Data Bus Interface for 8086
a) Even addressed bytes are accessed on D7~D0
b) Odd addressed bytes are accessed on D15~D8
c) Thus, even addressed words is easily on D15~D0
i. A19~A1 represents the word
ii. A19~A1 will be sent to both even and odd banks.
d) However, odd-addressed words can not be accessed in one cycle
i. Because the even and odd banks needs different values for A19~A1
ii. Such accesses will be two byte-operations.
4) How to support this structure?
Byte Even
A0 = 0
Word Even & Odd

Byte Odd
A0 = 1
Word None

a) A0 decides the even bank


b) What for the odd bank? We have /BHE!!!
BHE* A0 CS*

0 0 Choose both odd and even memory bank

0 1 Choose only odd memory bank

1 0 Choose only even memory bank

1 1 None is chosen

33
PART-A

1. What are different data transfer schemes?

2. How is clock signal generated in 8086? What is the maximum internal clock
frequency of 8086?

3. State the function of status lines in 8086 microprocessor.

4. What is a Microprocessor? What is the difference between microprocessor and CPU?

5. Why are the program counter and the stack pointer registers 16 bits?

6. What are Tristate devices?

7. Draw the flag register for 8086.

8. What is the purpose of BIU?

9. What is the need for ALE signal in 8086?

10. Write the size of the data bus and address bus of 8086?

11. What is the function of accumulator?

12. What is the clock frequency of 8086?

13. List the advantages of using direct memory access.

PART B

1. With a neat functional block diagram, explain the architecture of 8086


microprocessor.

2. Explain the generation of dedicated address and data bus signals from multiplexed
address/data bus.

3. Explain the bus structure of 8086 with a neat sketch.

4. Draw the pin diagram of 8086 microprocessor and explain the function of each pin.

5. Explain the internal hardware architecture of 8086 microprocessor with neat diagram.

6. Explain the different data transfer schemes with examples.

7. What are the peripheral I/O instructions? Write its syntax. Explain the same with the
timing diagram.

8. How are 8086 instructions classified according to their functional categories? Explain
with examples.

34
9. Explain the organization of 8086 stack and the instructions that will operate on the
stack.

10. Distinguish between memory mapped I/O and I/O mapped I/O.

11. Explain the external memory addressing of 8086

12. Explain the interrupt architecture of 8086 microprocessor.

13. Explain maximum mode bus cycle in 8086 microprocessor.

14. Draw and explain the signals and bus cycles in maximum mode system configuration
of 8086 microprocessor.

15. How is 8086 configured in maximum mode and in minimum mode? Explain.

16. Write short note on the Direct Memory Access.

35
UNIT-II
INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMING OF 8086

2.1 8086 INSTRUCTION SET

Data Transfer Instructions

MOV – MOV Destination, Source


The MOV instruction copies a word or byte of data from a specified source
to a specified destination. The destination can be a register or a memory
location. The source can be a register, a memory location or an immediate
number. The source and destination cannot both be memory locations. They
must both be of the same type (bytes or words). MOV instruction does not affect
any flag.

MOV CX, 037AH Put immediate number 037AH to CX


MOV BL, [437AH] Copy byte in DS at offset 437AH to BL
MOV AX, BX Copy content of register BX to AX
MOV DL, [BX] Copy byte from memory at [BX] to DL
MOV DS, BX Copy word from BX to DS register
MOV RESULT [BP], AX Copy AX to two memory locations;
AL to the first location, AH to the second;
EA of the first memory location is sum of the
displacement

represented by RESULTS and content of BP.


Physical address = EA + SS.
MOV ES: RESULTS [BP], AX Same as the above instruction, but physical
address = EA + ES,
because of the segment override prefix ES

XCHG – XCHG Destination, Source


The XCHG instruction exchanges the content of a register with the content
of another register or with the content of memory location(s). It cannot directly
36
exchange the content of two memory locations. The source and destination must
both be of the same type (bytes or words). The segment registers cannot be
used in this instruction. This instruction does not affect any flag.

Exchange word in AX with word in


XCHG AX, DX DX
Exchange byte in BL with byte in
XCHG BL, CH CH
Exchange byte in AL with byte in
XCHG AL, PRICES [BX] memory at
EA = PRICE [BX] in DS.

LEA – LEA Register, Source


This instruction determines the offset of the variable or memory location
named as the source and puts this offset in the indicated 16-bit register. LEA
does not affect any flag.

Load BX with offset of PRICE in


LEA BX, PRICES DS
Load BP with offset of STACK_TOP
LEA BP, SS: STACK_TOP in SS
LEA CX, [BX][DI] Load CX with EA = [BX] + [DI]

LDS – LDS Register, Memory address of the first word


This instruction loads new values into the specified register and into the
DS register from four successive memory locations. The word from two memory
locations is copied into the specified register and the word from the next two
memory locations is copied into the DS registers. LDS does not affect any flag.

Copy content of memory at displacement 4326H


LDS BX, [4326] in DS to BL,
content of 4327H to BH. Copy content at
displacement of

37
4328H and 4329H in DS to DS register.
Copy content of memory at displacement SPTR
LDS SI, SPTR and SPTR + 1
in DS to SI register. Copy content of memory at
displacements SPTR + 2 and SPTR + 3 in DS to
DS register. DS: SI now points at start of the
desired string.
LES – LES Register, Memory address of the first word
This instruction loads new values into the specified register and into the
ES register from four successive memory locations. The word from the first two
memory locations is copied into the specified register, and the word from the
next two memory locations is copied into the ES register. LES does not affect
any flag.

LES BX, [789AH] Copy content of memory at displacement 789AH


in DS to BL,
content of 789BH to BH, content of memory at
displacement
789CH and 789DH in DS is copied to ES
register.
LES DI, [BX] Copy content of memory at offset [BX] and
offset [BX] + 1 in
DS to DI register. Copy content of memory at
offset [BX] + 2

and [BX] + 3 to ES register.

Arithmetic Instructions

ADD – ADD Destination, Source


ADC – ADC Destination, Source
These instructions add a number from some source to a number in some
destination and put the result in the specified destination. The ADC also adds the
status of the carry flag to the result. The source may be an immediate number,
a register, or a memory location. The destination may be a register or a memory
38
location. The source and the destination in an instruction cannot both be
memory locations. The source and the destination must be of the same type
(bytes or words). If you want to add a byte to a word, you must copy the byte to
a word location and fill the upper byte of the word with 0’s before adding. Flags
affected: AF, CF, OF, SF, ZF.

ADD AL, 74H Add immediate number 74H to content of AL.


Result in AL
ADC CL, BL Add content of BL plus carry status to content of
CL
ADD DX, BX Add content of BX to content of DX
ADD DX, [SI] Add word from memory at offset [SI] in DS to
content of DX
ADC AL, PRICES [BX] Add byte from effective address PRICES [BX]
plus carry status to content of AL
ADD AL, PRICES [BX] Add content of memory at effective address
PRICES [BX]
to AL
SUB – SUB Destination, Source
SBB – SBB Destination, Source
These instructions subtract the number in some source from the number
in some destination and put the result in the destination. The SBB instruction
also subtracts the content of carry flag from the destination. The source may be
an immediate number, a register or memory location. The destination can also
be a register or a memory location. However, the source and the destination
cannot both be memory location. The source and the destination must both be of
the same type (bytes or words). If you want to subtract a byte from a word, you
must first move the byte to a word location such as a 16-bit register and fill the
upper byte of the word with 0’s. Flags affected: AF, CF, OF, PF, SF, ZF.

SUB CX, BX CX – BX; Result in CX


Subtract content of AL and content of CF from
SBB CH, AL content of CH.
Result in CH

39
SUB AX, 3427H Subtract immediate number 3427H from AX
Subtract word at displacement 3427H in DS and
SBB BX, [3427H] content of CF
from BX
SUB PRICES [BX], 04H Subtract 04 from byte at effective address
PRICES [BX],
if PRICES is declared with DB; Subtract 04
from word at
effective address PRICES [BX], if it is declared
with DW.
SBB CX, TABLE [BX] Subtract word from effective address TABLE
[BX]
and status of CF from CX.
SBB TABLE [BX], CX Subtract CX and status of CF from word in
memory at
effective address TABLE[BX].

MUL – MUL Source


This instruction multiplies an unsigned byte in some source with an
unsigned byte in AL register or an unsigned word in some source with an
unsigned word in AX register. The source can be a register or a memory
location. When a byte is multiplied by the content of AL, the result (product) is
put in AX. When a word is multiplied by the content of AX, the result is put in DX
and AX registers. If the most significant byte of a 16-bit result or the most
significant word of a 32-bit result is 0, CF and OF will both be 0’s. AF, PF, SF and
ZF are undefined after a MUL instruction.

If you want to multiply a byte with a word, you must first move the byte
to a word location such as an extended register and fill the upper byte of the
word with all 0’s. You cannot use the CBW instruction for this, because the CBW
instruction fills the upper byte with copies of the most significant bit of the lower
byte.

MUL BH Multiply AL with BH; result in AX


MUL CX Multiply AX with CX; result high word in DX, low

40
word in AX
MUL BYTE PTR [BX] Multiply AL with byte in DS pointed to by [BX]
MUL FACTOR [BX] Multiply AL with byte at effective address
FACTOR [BX], if it
is declared as type byte with DB. Multiply AX
with word at

effective address FACTOR [BX], if it is declared


as type word
with DW.
MOV AX, MCAND_16 Load 16-bit multiplicand into AX
MOV CL, MPLIER_8 Load 8-bit multiplier into CL
MOV CH, 00H Set upper byte of CX to all 0’s

MUL CX AX times CX; 32-bit result in DX and AX

IMUL – IMUL Source


This instruction multiplies a signed byte from source with a signed byte in
AL or a signed word from some source with a signed word in AX. The source can
be a register or a memory location. When a byte from source is multiplied with
content of AL, the signed result (product) will be put in AX. When a word from
source is multiplied by AX, the result is put in DX and AX. If the magnitude of
the product does not require all the bits of the destination, the unused byte /
word will be filled with copies of the sign bit. If the upper byte of a 16-bit result
or the upper word of a 32-bit result contains only copies of the sign bit (all 0’s or
all 1’s), then CF and the OF will both be 0; If it contains a part of the product, CF
and OF will both be 1. AF, PF, SF and ZF are undefined after IMUL.
If you want to multiply a signed byte with a signed word, you must first move
the byte into a word location and fill the upper byte of the word with copies of
the sign bit. If you move the byte into AL, you can use the CBW instruction to do
this.

IMUL BH Multiply signed byte in AL with signed byte in


BH;
result in AX.

41
IMUL AX Multiply AX times AX; result in DX and AX
MOV CX, MULTIPLIER Load signed word in CX
MOV AL, MULTIPLICAND Load signed byte in AL
CBW Extend sign of AL into AH

IMUL CX Multiply CX with AX; Result in DX and AX

DIV – DIV Source


This instruction is used to divide an unsigned word by a byte or to divide
an unsigned double word (32 bits) by a word. When a word is divided by a byte,
the word must be in the AX register. The divisor can be in a register or a
memory location. After the division, AL will contain the 8-bit quotient, and AH
will contain the 8-bit remainder. When a double word is divided by a word, the
most significant word of the double word must be in DX, and the least significant
word of the double word must be in AX. After the division, AX will contain the 16-
bit quotient and DX will contain the 16-bit remainder. If an attempt is made to
divide by 0 or if the quotient is too large to fit in the destination (greater than
FFH / FFFFH), the 8086 will generate a type 0 interrupt. All flags are undefined
after a DIV instruction.

If you want to divide a byte by a byte, you must first put the dividend
byte in AL and fill AH with all 0’s. Likewise, if you want to divide a word by
another word, then put the dividend word in AX and fill DX with all 0’s.

DIV BL Divide word in AX by byte in BL; Quotient in AL,


remainder in AH
DIV CX Divide down word in DX and AX by word in CX;
Quotient in AX, and remainder in DX.
DIV SCALE [BX] AX / (byte at effective address SCALE [BX]) if SCALE
[BX] is of type
byte; or (DX and AX) / (word at effective address
SCALE[BX]

if SCALE[BX] is of type word

42
IDIV – IDIV Source
This instruction is used to divide a signed word by a signed byte, or to
divide a signed double word by a signed word.

When dividing a signed word by a signed byte, the word must be in the
AX register. The divisor can be in an 8-bit register or a memory location. After
the division, AL will contain the signed quotient, and AH will contain the signed
remainder. The sign of the remainder will be the same as the sign of the
dividend. If an attempt is made to divide by 0, the quotient is greater than 127
(7FH) or less than –127 (81H), the 8086 will automatically generate a type 0
interrupt.
When dividing a signed double word by a signed word, the most
significant word of the dividend (numerator) must be in the DX register, and the
least significant word of the dividend must be in the AX register. The divisor can
be in any other 16-bit register or memory location. After the division, AX will
contain a signed 16-bit quotient, and DX will contain a signed 16-bit remainder.
The sign of the remainder will be the same as the sign of the dividend. Again, if
an attempt is made to divide by 0, the quotient is greater than +32,767 (7FFFH)
or less than –32,767 (8001H), the 8086 will automatically generate a type 0
interrupt.

All flags are undefined after an IDIV.


If you want to divide a signed byte by a signed byte, you must first put
the dividend byte in AL and sign-extend AL into AH. The CBW instruction can be
used for this purpose. Likewise, if you want to divide a signed word by a signed
word, you must put the dividend word in AX and extend the sign of AX to all the
bits of DX. The CWD instruction can be used for this purpose.

IDIV BL Signed word in AX/signed byte in BL


Signed double word in DX and AX/signed
IDIV BP word in BP
IDIV BYTE PTR [BX] AX / byte at offset [BX] in DS

INC – INC Destination


The INC instruction adds 1 to a specified register or to a memory location.
43
AF, OF, PF, SF, and ZF are updated, but CF is not affected. This means that if an
8-bit destination containing FFH or a 16-bit destination containing FFFFH is
incremented, the result will be all 0’s with no carry.

INC BL Add 1 to contains of BL register


INC CX Add 1 to contains of CX register
INC BYTE PTR [BX] Increment byte in data segment at offset
contained in BX.
INC WORD PTR [BX] Increment the word at offset of [BX] and [BX +
1]
in the data segment.
INC TEMP Increment byte or word named TEMP in the data
segment.

Increment byte if MAX_TEMP declared with DB.


Increment word if MAX_TEMP is declared with
DW.
INC PRICES [BX] Increment element pointed to by [BX] in array
PRICES.
Increment a word if PRICES is declared as an
array of words;
Increment a byte if PRICES is declared as an
array of bytes.

DEC – DEC Destination


This instruction subtracts 1 from the destination word or byte. The
destination can be a register or a memory location. AF, OF, SF, PF, and ZF are
updated, but CF is not affected. This means that if an 8-bit destination
containing 00H or a 16-bit destination containing 0000H is decremented, the
result will be FFH or FFFFH with no carry (borrow).

DEC CL Subtract 1 from content of CL register


DEC BP Subtract 1 from content of BP register
DEC BYTE PTR [BX] Subtract 1 from byte at offset [BX] in DS.
DEC WORD PTR [BP] Subtract 1 from a word at offset [BP] in SS.

44
DEC COUNT Subtract 1 from byte or word named COUNT in
DS.
Decrement a byte if COUNT is declared with a
DB;
Decrement a word if COUNT is declared with a
DW.

DAA (DECIMAL ADJUST AFTER BCD ADDITION)


This instruction is used to make sure the result of adding two packed BCD
numbers is adjusted to be a legal BCD number. The result of the addition must
be in AL for DAA to work correctly. If the lower nibble in AL after an addition is
greater than 9 or AF was set by the addition, then the DAA instruction will add 6
to the lower nibble in AL. If the result in the upper nibble of AL in now greater
than 9 or if the carry flag was set by the addition or correction, then the DAA
instruction will add 60H to AL.
Let AL = 59 BCD, and BL = 35 BCD
ADD AL, BL AL = 8EH; lower nibble > 9, add 06H to AL
DAA AL = 94 BCD, CF = 0
Let AL = 88 BCD, and BL = 49 BCD
ADD AL, BL AL = D1H; AF = 1, add 06H to AL

DAA AL = D7H; upper nibble > 9, add 60H to AL


AL = 37 BCD, CF = 1

The DAA instruction updates AF, CF, SF, PF, and ZF; but OF is undefined.

DAS (DECIMAL ADJUST AFTER BCD SUBTRACTION)


This instruction is used after subtracting one packed BCD number from
another packed BCD number, to make sure the result is correct packed BCD. The
result of the subtraction must be in AL for DAS to work correctly. If the lower
nibble in AL after a subtraction is greater than 9 or the AF was set by the
subtraction, then the DAS instruction will subtract 6 from the lower nibble AL. If
the result in the upper nibble is now greater than 9 or if the carry flag was set,
the DAS instruction will subtract 60 from AL.

45
Let AL = 86 BCD, and BH = 57 BCD

SUB AL, BH AL = 2FH; lower nibble > 9, subtract 06H from AL AL


= 29 BCD, CF = 0
Let AL = 49 BCD, and BH = 72 BCD
SUB AL, BH AL = D7H; upper nibble > 9, subtract 60H from
AL

DAS AL = 77 BCD, CF = 1 (borrow is needed)

The DAS instruction updates AF, CF, SF, PF, and ZF; but OF is undefined.

CBW (CONVERT SIGNED BYTE TO SIGNED WORD)


This instruction copies the sign bit of the byte in AL to all the bits in AH.
AH is then said to be the sign extension of AL. CBW does not affect any flag.

Let AX = 00000000 10011011 (–155 decimal)


CBW Convert signed byte in AL to signed
word in AX AX = 11111111
10011011 (–155 decimal)

CWD (CONVERT SIGNED WORD TO SIGNED DOUBLE WORD)


This instruction copies the sign bit of a word in AX to all the bits of the DX
register. In other words, it extends the sign of AX into all of DX. CWD affects no
flags.

Let DX = 00000000 00000000, and AX = 11110000 11000111 (–3897


decimal)

CWD Convert signed word in AX to signed double


word in DX:AX DX = 11111111 11111111
AX = 11110000 11000111 (–3897 decimal)

AAA (ASCII ADJUST FOR ADDITION)


Numerical data coming into a computer from a terminal is usually in ASCII
46
code. In this code, the numbers 0 to 9 are represented by the ASCII codes 30H
to 39H. The 8086 allows you to add the ASCII codes for two decimal digits
without masking off the “3” in the upper nibble of each. After the addition, the
AAA instruction is used to make sure the result is the correct unpacked BCD.

Let AL = 0011 0101 (ASCII 5), and BL = 0011 1001 (ASCII 9)


AL = 0110 (6EH, which is incorrect
ADD AL, BL 1110 BCD)
AL = 0000
AAA 0100 (unpacked BCD 4)
CF = 1 indicates answer is 14
decimal.

The AAA instruction works only on the AL register. The AAA instruction updates
AF and CF; but OF, PF, SF and ZF are left undefined.

AAS (ASCII ADJUST FOR SUBTRACTION)


Numerical data coming into a computer from a terminal is usually in an
ASCII code. In this code the numbers 0 to 9 are represented by the ASCII codes
30H to 39H. The 8086 allows you to subtract the

ASCII codes for two decimal digits without masking the “3” in the upper nibble
of each. The AAS instruction is then used to make sure the result is the correct
unpacked BCD.

Let AL = 00111001 (39H or ASCII 9), and BL = 00110101 (35H or ASCII 5)


AL = (BCD 04), and CF
SUB AL, BL 00000100 =0
AL = (BCD 04), and CF (no borrow
AAS 00000100 =0 required)
Let AL = 00110101 (35H or ASCII 5), and BL = 00111001 (39H or ASCII 9)
AL = (– 4 in 2’s complement form), and
SUB AL, BL 11111100 CF = 1
AL = (BCD 06), and CF (borrow
AAS 00000100 =1 required)

47
The AAS instruction works only on the AL register. It updates ZF and CF; but OF,
PF, SF, AF are left undefined.

AAM (BCD ADJUST AFTER MULTIPLY)


Before you can multiply two ASCII digits, you must first mask the upper 4
bit of each. This leaves unpacked BCD (one BCD digit per byte) in each byte.
After the two unpacked BCD digits are multiplied, the AAM instruction is used to
adjust the product to two unpacked BCD digits in AX. AAM works only after the
multiplication of two unpacked BCD bytes, and it works only the operand in AL.
AAM updates PF, SF and ZF but AF; CF and OF are left undefined.

Let AL = 00000101 (unpacked BCD 5), and BH = 00001001 (unpacked BCD 9)


MUL BH AL x BH: AX = 00000000 00101101 = 002DH
= 0405H (unpacked BCD
AAM AX = 00000100 00000101 for 45)

AAD (BCD-TO-BINARY CONVERT BEFORE DIVISION)


AAD converts two unpacked BCD digits in AH and AL to the equivalent
binary number in AL. This adjustment must be made before dividing the two
unpacked BCD digits in AX by an unpacked BCD byte. After the BCD division, AL
will contain the unpacked BCD quotient and AH will contain the unpacked BCD
remainder. AAD updates PF, SF and ZF; AF, CF and OF are left undefined.

Let AX = 0607 (unpacked BCD for 67 decimal), and CH = 09H


AAD AX = 0043 (43H = 67 decimal)

DIV CH AL = 07; AH = 04; Flags undefined after DIV

If an attempt is made to divide by 0, the 8086 will generate a type 0 interrupt.

Logical Instructions
AND – AND Destination, Source
This instruction ANDs each bit in a source byte or word with the same
numbered bit in a destination byte or word. The result is put in the specified
48
destination. The content of the specified source is not changed.

The source can be an immediate number, the content of a register, or the


content of a memory location. The destination can be a register or a memory
location. The source and the destination cannot both be memory locations. CF
and OF are both 0 after AND. PF, SF, and ZF are updated by the AND instruction.
AF is undefined. PF has meaning only for an 8-bit operand.

AND word in DS at offset [SI] with word in


AND CX, [SI] CX register;
Result in CX register
AND BH, CL AND byte in CL with byte in BH; Result in BH
00FFH Masks upper byte, leaves lower byte
AND BX, 00FFH unchanged.

OR – OR Destination, Source
This instruction ORs each bit in a source byte or word with the same
numbered bit in a destination byte or word. The result is put in the specified
destination. The content of the specified source is not changed.
The source can be an immediate number, the content of a register, or the
content of a memory location. The destination can be a register or a memory
location. The source and destination cannot both be memory locations. CF and
OF are both 0 after OR. PF, SF, and ZF are updated by the OR instruction. AF is
undefined. PF has meaning only for an 8-bit operand.

OR AH, CL CL ORed
with AH, result in AH, CL
not OR BP, SI SI ORed with BP, result in BP, SI not changed
OR SI, BP BP ORed with SI, result in SI, BP not changed
BL ORed with immediate number 80H; sets MSB
OR BL, 80H of BL to 1
CX ORed with word from effective address
OR CX, TABLE [SI] TABLE [SI];
Content of memory is not changed.

49
XOR – XOR Destination, Source
This instruction Exclusive-ORs each bit in a source byte or word with the
same numbered bit in a destination byte or word. The result is put in the
specified destination. The content of the specified source is not changed.
The source can be an immediate number, the content of a register, or the
content of a memory location. The destination can be a register or a memory
location. The source and destination cannot both be memory locations. CF and
OF are both 0 after XOR. PF, SF, and ZF are updated. PF has meaning only for
an 8-bit operand. AF is undefined.

XOR CL, BH Byte in BH exclusive-ORed with byte in


CL.
Result in CL. BH not changed.
XOR BP, DI Word in DI exclusive-ORed with word in
BP.
Result in BP. DI not changed.
XOR WORD PTR [BX], 00FFH Exclusive-OR immediate number 00FFH
with word at
offset [BX] in the data segment.

Result in memory location [BX]

NOT – NOT Destination


The NOT instruction inverts each bit (forms the 1’s complement) of a byte
or word in the specified destination. The destination can be a register or a
memory location. This instruction does not affect any flag.

NOT BX Complement content or BX register


Complement memory byte at offset [BX] in
NOT BYTE PTR [BX] data segment.

NEG – NEG Destination


This instruction replaces the number in a destination with its 2’s
complement. The destination can be a register or a memory location. It gives
50
the same result as the invert each bit and add one algorithm. The NEG
instruction updates AF, AF, PF, ZF, and OF.

Replace number in AL with its 2’s


NEG AL complement
Replace number in BX with its 2’s
NEG BX complement
Replace byte at offset BX in DX with its 2’s
NEG BYTE PTR [BX] complement
Replace word at offset BP in SS with its 2’s
NEG WORD PTR [BP] complement

CMP – CMP Destination, Source


This instruction compares a byte / word in the specified source with a byte
/ word in the specified destination. The source can be an immediate number, a
register, or a memory location. The destination can be a register or a memory
location. However, the source and the destination cannot both be memory
locations. The comparison is actually done by subtracting the source byte or
word from the destination byte or word. The source and the destination are not
changed, but the flags are set to indicate the results of the comparison. AF, OF,
SF, ZF, PF, and CF are updated by the CMP instruction. For the instruction CMP
CX, BX, the values of CF, ZF, and SF will be as follows:

CF ZF SF
CX = BX 0 1 0 Result of subtraction is 0
CX > BX 0 0 0 No borrow required, so CF = 0
CX < BX 1 0 1 Subtraction requires borrow, so CF = 1

CMP AL, 01H Compare immediate number 01H with byte in AL


CMP BH, CL Compare byte in CL with byte in BH
Compare word in DS at displacement TEMP with
CMP CX, TEMP word at CX
CMP PRICES [BX], Compare immediate number 49H with byte at
49H offset [BX]

51
in array PRICES

TEST – TEST Destination, Source


This instruction ANDs the byte / word in the specified source with the byte
/ word in the specified destination. Flags are updated, but neither operand is
changed. The test instruction is often used to set flags before a Conditional jump
instruction.

The source can be an immediate number, the content of a register, or the


content of a memory location. The destination can be a register or a memory
location. The source and the destination cannot both be memory locations. CF
and OF are both 0’s after TEST. PF, SF and ZF will be updated to show the
results of the destination. AF is be undefined.

AND BH with AL. No result stored; Update


TEST AL, BH PF, SF, ZF.
TEST CX, 0001H AND CX with immediate number 0001H;
No result stored; Update PF, SF, ZF
AND word are offset [BX][DI] in DS with
TEST BP, [BX][DI] word in BP.
No result stored. Update PF, SF, and ZF

Rotate And Shift Instructions


RCL – RCL Destination, Count
This instruction rotates all the bits in a specified word or byte some
number of bit positions to the left. The operation circular because the MSB of the
operand is rotated into the carry flag and the bit in the carry flag is rotated
around into LSB of the operand.

CF MSB LSB

For multi-bit rotates, CF will contain the bit most recently rotated out of the
MSB.
52
The destination can be a register or a memory location. If you want to
rotate the operand by one bit position, you can specify this by putting a 1 in the
count position of the instruction. To rotate by more than one bit position, load
the desired number into the CL register and put “CL” in the count position of the
instruction.
RCL affects only CF and OF. OF will be a 1 after a single bit RCL if the MSB
was changed by the rotate. OF is undefined after the multi-bit rotate.

RCL DX, 1 Word in DX 1 bit left, MSB to CF, CF to LSB


Load the number of bit positions to rotate into
MOV CL, 4 CL
Rotate byte or word at effective address SUM
RCL SUM [BX], CL [BX] 4 bits left
Original bit 4 now in CF, original CF now in bit 3.

RCR – RCR Destination, Count


This instruction rotates all the bits in a specified word or byte some
number of bit positions to the right. The operation circular because the LSB of
the operand is rotated into the carry flag and the bit in the carry flag is rotate
around into MSB of the operand.

CF MSB LSB

For multi-bit rotate, CF will contain the bit most recently rotated out of the LSB.

The destination can be a register or a memory location. If you want to


rotate the operand by one bit position, you can specify this by putting a 1 in the
count position of the instruction. To rotate more than one bit position, load the
desired number into the CL register and put “CL” in the count position of the
instruction.

RCR affects only CF and OF. OF will be a 1 after a single bit RCR if the
MSB was changed by the rotate. OF is undefined after the multi-bit rotate.

53
Word in BX right 1 bit, CF to MSB, LSB to
RCR BX, 1 CF
MOV CL, 4 Load CL for rotating 4 bit position
Rotate the byte at offset [BX] in DS 4 bit
RCR BYTE PTR [BX], 4 positions right
CF = original bit 3, Bit 4 – original CF.

ROL – ROL Destination, Count


This instruction rotates all the bits in a specified word or byte to the left
some number of bit positions. The data bit rotated out of MSB is circled back into
the LSB. It is also copied into CF. In the case of multiple-bit rotate, CF will
contain a copy of the bit most recently moved out of the MSB.

CF MSB LSB

The destination can be a register or a memory location. If you to want


rotate the operand by one bit position, you can specify this by putting 1 in the
count position in the instruction. To rotate more than one bit position, load the
desired number into the CL register and put “CL” in the count position of the
instruction.

ROL affects only CF and OF. OF will be a 1 after a single bit ROL if the
MSB was changed by the rotate.

Rotate the word in AX 1 bit position left, MSB to


ROL AX, 1 LSB and CF
MOV CL, 04H Load number of bits to rotate in CL
ROL BL, CL Rotate BL 4 bit positions
Rotate the word or byte in DS at EA = FACTOR
ROL FACTOR [BX], 1 [BX]
by 1 bit position left into CF

ROR – ROR Destination, Count


This instruction rotates all the bits in a specified word or byte some

54
number of bit positions to right. The operation is desired as a rotate rather than
shift, because the bit moved out of the LSB is rotated around into the MSB. The
data bit moved out of the LSB is also copied into CF. In the case of multiple bit
rotates, CF will contain a copy of the bit most recently moved out of the LSB.

CF MSB LSB

Rotate all bits in BL right 1 bit position LSB to MSB


ROR BL, 1 and to CF
MOV CL, 08H Load CL with number of bit positions to be rotated
Rotate word in DS at offset [BX] 8 bit position
ROR WORD PTR [BX], CL right
The destination can be a register or a memory location. If you want to
rotate the operand by one bit position, you can specify this by putting 1 in the
count position in the instruction. To rotate by more than one bit position, load
the desired number into the CL register and put “CL” in the count position of the
instruction.
ROR affects only CF and OF. OF will be a 1 after a single bit ROR if the
MSB was changed by the rotate.

SAL – SAL Destination, Count


SHL – SHL Destination, Count
SAL and SHL are two mnemonics for the same instruction. This instruction
shifts each bit in the specified destination some number of bit positions to the
left. As a bit is shifted out of the LSB operation, a 0 is put in the LSB position.
The MSB will be shifted into CF. In the case of multi-bit shift, CF will contain the
bit most recently shifted out from the MSB. Bits shifted into CF previously will be
lost.

CF MSB LSB 0

The destination operand can be a byte or a word. It can be in a register or


in a memory location. If you want to shift the operand by one bit position, you

55
can specify this by putting a 1 in the count position of the instruction. For shifts
of more than 1 bit position, load the desired number of shifts into the CL
register, and put “CL” in the count position of the instruction.
The flags are affected as follow: CF contains the bit most recently shifted
out from MSB. For a count of one, OF will be 1 if CF and the current MSB are not
the same. For multiple-bit shifts, OF is undefined. SF and ZF will be updated to
reflect the condition of the destination. PF will have meaning only for an operand
in AL. AF is undefined.

SAL BX, 1 Shift word in BX 1 bit position left, 0 in LSB


MOV CL, 02h Load desired number of shifts in CL
SAL BP, CL Shift word in BP left CL bit positions, 0 in LSBs
Shift byte in DX at offset [BX] 1 bit position
SAL BYTE PTR [BX], 1 left, 0 in LSB

SAR – SAR Destination, Count


This instruction shifts each bit in the specified destination some number of
bit positions to the right. As a bit is shifted out of the MSB position, a copy of the
old MSB is put in the MSB position. In other words, the sign bit is copied into the
MSB. The LSB will be shifted into CF. In the case of multiple-bit shift, CF will
contain the bit most recently shifted out from the LSB. Bits shifted into CF
previously will be lost.

MSB MSB LSB CF

The destination operand can be a byte or a word. It can be in a register or in a


memory location. If you want to shift the operand by one bit position, you can
specify this by putting a 1 in the count position of the instruction. For shifts of
more than 1 bit position, load the desired number of shifts into the CL register,
and put “CL” in the count position of the instruction.
The flags are affected as follow: CF contains the bit most recently shifted
in from LSB. For a count of one, OF will be 1 if the two MSBs are not the same.
After a multi-bit SAR, OF will be 0. SF and ZF will be updated to show the
condition of the destination. PF will have meaning only for an 8- bit destination.
AF will be undefined after SAR.
56
Shift word in DI one bit position right, new MSB
SAR DX, 1 = old MSB
MOV CL, 02H Load desired number of shifts in CL

SAR WORD PTR [BP], CL Shift word at offset [BP] in stack segment right
by two bit
positions, the two MSBs are now copies of
original LSB

SHR – SHR Destination, Count


This instruction shifts each bit in the specified destination some number of
bit positions to the right. As a bit is shifted out of the MSB position, a 0 is put in
its place. The bit shifted out of the LSB position goes to CF. In the case of multi-
bit shifts, CF will contain the bit most recently shifted out from the LSB. Bits
shifted into CF previously will be lost.

0 MSB LSB CF

The destination operand can be a byte or a word in a register or in a


memory location. If you want to shift the operand by one bit position, you can
specify this by putting a 1 in the count position of the instruction.
For shifts of more than 1 bit position, load the desired number of shifts
into the CL register, and put “CL” in the count position of the instruction.
The flags are affected by SHR as follow: CF contains the bit most recently
shifted out from LSB. For a count of one, OF will be 1 if the two MSBs are not
both 0’s. For multiple-bit shifts, OF will be meaningless. SF and ZF will be
updated to show the condition of the destination. PF will have meaning only for
an 8-bit destination. AF is undefined.

Shift word in BP one bit position right, 0 in


SHR BP, 1 MSB
MOV CL, 03H Load desired number of shifts into CL
Shift byte in DS at offset [BX] 3 bits right; 0’s
SHR BYTE PTR [BX] in 3 MSBs

57
Transfer-Of-Control Instructions
Note: The following rules apply to the discussions presented in this section.
The terms above and below are used when referring to the magnitude of
unsigned numbers. For example, the number 00000111 (7) is above the
number 00000010 (2), whereas the number 00000100
(4) is below the number 00001110 (14).

The terms greater and less are used to refer to the relationship of two signed
numbers. Greater means more positive. The number 00000111 (+7) is
greater than the number 11111110 (-2), whereas the number 11111100 (-4)
is less than the number 11110100 (-6).

In the case of Conditional jump instructions, the destination address must be


in the range of –128 bytes to +127 bytes from the address of the next
instruction
These instructions do not affect any flags.

JMP (Unconditional Jump To Specified Destination)


This instruction will fetch the next instruction from the location specified in
the instruction rather than from the next location after the JMP instruction. If the
destination is in the same code segment as the JMP instruction, then only the
instruction pointer will be changed to get the destination location. This is
referred to as a near jump. If the destination for the jump instruction is in a
segment with a name different from that of the segment containing the JMP
instruction, then both the instruction pointer and the code segment register
content will be changed to get the destination location. This referred to as a far
jump. The JMP instruction does not affect any flag.

JMP CONTINUE
This instruction fetches the next instruction from address at label CONTINUE. If
the label is in the same segment, an offset coded as part of the instruction will
be added to the instruction pointer to produce the new fetch address. If the label
is another segment, then IP and CS will be replaced with value coded in part of
the instruction. This type of jump is referred to as direct because the
58
displacement of the destination or the destination itself is specified directly in the
instruction.

JMP BX
This instruction replaces the content of IP with the content of BX. BX must first
be loaded with the offset of the destination instruction in CS. This is a near
jump. It is

also referred to as an indirect jump because the new value of IP comes from a
register rather than from the instruction itself, as in a direct jump.

JMP WORD PTR [BX]


This instruction replaces IP with word from a memory location pointed to by BX
in DX. This is an indirect near jump.

JMP DWORD PTR [SI]


This instruction replaces IP with word pointed to by SI in DS. It replaces CS with
a word pointed by SI + 2 in DS. This is an indirect far jump.

JA / JNBE (Jump If Above / Jump If Not Below Or Equal)


If, after a compare or some other instructions which affect flags, the zero
flag and the carry flag both are 0, this instruction will cause execution to jump to
a label given in the instruction. If CF and ZF are not both 0, the instruction will
have no effect on program execution.

CMP AX, 4371H Compare by subtracting 4371H from AX


JA NEXT Jump to label NEXT if AX above 4371H
CMP AX, 4371H Compare (AX – 4371H)
Jump to label NEXT if AX not below or equal
JNBE NEXT to 4371H

JAE / JNB / JNC


(Jump If Above Or Equal / Jump If Not Below / Jump If No Carry)
If, after a compare or some other instructions which affect flags, the carry
flag is 0, this instruction will cause execution to jump to a label given in the
59
instruction. If CF is 1, the instruction will have no effect on program execution.

CMP AX, 4371H Compare (AX – 4371H)


JAE NEXT Jump to label NEXT if AX above 4371H
CMP AX, 4371H Compare (AX – 4371H)
JNB NEXT Jump to label NEXT if AX not below 4371H
ADD AL, BL Add two bytes
JNC NEXT If the result with in acceptable range, continue

JB / JC / JNAE (Jump If Below / Jump If Carry / Jump If Not


Above Or Equal)
If, after a compare or some other instructions which affect flags, the carry
flag is a 1, this instruction will cause execution to jump to a label given in the
instruction. If CF is 0, the instruction will have no effect on program execution.

CMP AX, 4371H Compare (AX – 4371H)


JB NEXT Jump to label NEXT if AX below 4371H
ADD BX, CX Add two words
JC NEXT Jump to label NEXT if CF = 1
CMP AX, 4371H Compare (AX – 4371H)
JNAE NEXT Jump to label NEXT if AX not above or equal to
4371H

JBE / JNA (Jump If Below Or Equal / Jump If Not Above)


If, after a compare or some other instructions which affect flags, either
the zero flag or the carry flag is 1, this instruction will cause execution to jump
to a label given in the instruction. If CF and ZF are both 0, the instruction will
have no effect on program execution.

CMP AX, 4371H Compare (AX – 4371H)


Jump to label NEXT if AX is below or equal
JBE NEXT to 4371H
CMP AX, 4371H Compare (AX – 4371H)
JNA NEXT Jump to label NEXT if AX not above 4371H

60
JG / JNLE (Jump If Greater / Jump If Not Less Than Or Equal)
This instruction is usually used after a Compare instruction. The
instruction will cause a jump to the label given in the instruction, if the zero flag
is 0 and the carry flag is the same as the overflow flag.

CMP BL, 39H Compare by subtracting 39H from BL


Jump to label NEXT if BL more positive than
JG NEXT 39H
CMP BL, 39H Compare by subtracting 39H from BL
Jump to label NEXT if BL is not less than or
JNLE NEXT equal to 39H

JGE / JNL (Jump If Greater Than Or Equal / Jump If Not Less


Than)
This instruction is usually used after a Compare instruction. The
instruction will cause a jump to the label given in the instruction, if the sign flag
is equal to the overflow flag.

CMP BL, 39H Compare by subtracting 39H from BL


Jump to label NEXT if BL more positive than or
JGE NEXT equal to 39H
CMP BL, 39H Compare by subtracting 39H from BL
JNL NEXT Jump to label NEXT if BL not less than 39H

JL / JNGE (Jump If Less Than / Jump If Not Greater Than Or


Equal)
This instruction is usually used after a Compare instruction. The
instruction will cause a jump to the label given in the instruction if the sign flag
is not equal to the overflow flag.

CMP BL, 39H Compare by subtracting 39H from BL


Jump to label AGAIN if BL more negative than
JL AGAIN 39H
CMP BL, 39H Compare by subtracting 39H from BL

61
Jump to label AGAIN if BL not more positive than
JNGE AGAIN or equal to
39H

JLE / JNG (Jump If Less Than Or Equal / Jump If Not Greater)


This instruction is usually used after a Compare instruction. The
instruction will cause a jump to the label given in the instruction if the zero flag
is set, or if the sign flag not equal to the overflow flag.

CMP BL, 39H Compare by subtracting 39H from BL


Jump to label NEXT if BL more negative than or
JLE NEXT equal to 39H
CMP BL, 39H Compare by subtracting 39H from BL
Jump to label NEXT if BL not more positive than
JNG NEXT 39H

JE / JZ (Jump If Equal / Jump If Zero)


This instruction is usually used after a Compare instruction. If the zero
flag is set, then this instruction will cause a jump to the label given in the
instruction.

CMP BX, DX Compare (BX-DX)


JE DONE Jump to DONE if BX = DX
IN AL, 30H Read data from port 8FH
SUB AL, 30H Subtract the minimum value.
Jump to label START if the result of
JZ START subtraction is 0

JNE / JNZ (Jump Not Equal / Jump If Not Zero)


This instruction is usually used after a Compare instruction. If the zero
flag is 0, then this instruction will cause a jump to the label given in the
instruction.

IN AL, 0F8H Read data value from port


62
CMP AL, 72 Compare (AL –72)
JNE NEXT Jump to label NEXT if AL 72
ADD AX, 0002H Add count factor 0002H to AX
DEC BX Decrement BX
JNZ NEXT Jump to label NEXT if BX 0

JS (Jump If Signed / Jump If Negative)


This instruction will cause a jump to the specified destination address if
the sign flag is set. Since a 1 in the sign flag indicates a negative signed
number, you can think of this instruction as saying “jump if negative”.

ADD BL, DH Add signed byte in DH to signed byte in DL


Jump to label NEXT if result of addition is
JS NEXT negative number

JNS (Jump If Not Signed / Jump If Positive)


This instruction will cause a jump to the specified destination address if
the sign flag is 0. Since a 0 in the sign flag indicate a positive signed number,
you can think to this instruction as saying “jump if positive”.

DEC AL Decrement AL
JNS NEXT Jump to label NEXT if AL has not decremented to
FFH

JP / JPE (Jump If Parity / Jump If Parity Even)


If the number of 1’s left in the lower 8 bits of a data word after an
instruction which affects the parity flag is even, then the parity flag will be set. If
the parity flag is set, the JP / JPE instruction will cause a jump to the specified
destination address.

IN AL, 0F8H Read ASCII character from Port F8H


OR AL, AL Set flags
JPE ERROR Odd parity expected, send error message if
parity found even
63
JNP / JPO (Jump If No Parity / Jump If Parity Odd)
If the number of 1’s left in the lower 8 bits of a data word after an
instruction which affects the parity flag is odd, then the parity flag is 0. The JNP
/ JPO instruction will cause a jump to the specified destination address, if the
parity flag is 0.

IN AL, 0F8H Read ASCII character from Port F8H


OR AL, AL Set flags
JPO ERROR Even parity expected, send error message if
parity found odd

JO (Jump If Overflow)
The overflow flag will be set if the magnitude of the result produced by
some signed arithmetic operation is too large to fit in the destination register or
memory location. The JO instruction will cause a jump to the destination given in
the instruction, if the overflow flag is set.

ADD AL, BL Add signed bytes in AL and BL


JO ERROR Jump to label ERROR if overflow from add

JNO (Jump If No Overflow)


The overflow flag will be set if some signed arithmetic operation is too
large to fit in the destination register or memory location. The JNO instruction
will cause a jump to the destination given in the instruction, if the overflow flag
is not set.

ADD AL, BL Add signed byte in AL and BL


JNO DONE Process DONE if no overflow

JCXZ (Jump If The CX Register Is Zero)


This instruction will cause a jump to the label to a given in the instruction,
if the CX register contains all
0’s. The instruction does not look at the zero flag when it decides whether to
64
jump or not.
JCXZ SKIP SUB [BX], 07H SKIP: ADD C
If CX = 0, skip the process Subtract 7 from data value Next instruction

LOOP (Jump To Specified Label If Cx 0 After Auto Decrement)


This instruction is used to repeat a series of instructions some number of
times. The number of times the instruction sequence is to be repeated is loaded
into CX. Each time the LOOP instruction executes, CX is automatically
decremented by 1. If CX is not 0, execution will jump to a destination specified
by a label in the instruction. If CX = 0 after the auto decrement, execution will
simply go on to the next instruction after LOOP. The destination address for the
jump must be in the range of –128 bytes to +127 bytes from the address of the
instruction after the LOOP instruction. This instruction does not affect any flag.

MOV BX, OFFSET PRICES Point BX at first element in array


MOV CX, 40 Load CX with number of elements in array
NEXT: MOV AL, [BX] Get element from array

INC AL Increment the content of AL


MOV [BX], AL Put result back in array

INC BX Increment BX to point to next location


LOOP NEXT Repeat until all elements adjusted

LOOPE / LOOPZ (LOOP WHILE CX 0 AND ZF = 1)


This instruction is used to repeat a group of instructions some number of
times, or until the zero flag becomes 0. The number of times the instruction
sequence is to be repeated is loaded into CX. Each time the LOOP instruction
executes, CX is automatically decremented by 1. If CX 0 and ZF = 1,
execution will jump to a destination specified by a label in the instruction. If CX
= 0, execution simply go on the next instruction after LOOPE / LOOPZ. In other
words, the two ways to exit the loop are CX = 0 or ZF = 0. The destination
address for the jump must be in the range of –128 bytes to +127 bytes from the
address of the instruction after the LOOPE / LOOPZ instruction. This instruction
does not affect any flag.
65
MOV BX, OFFSET ARRAY Point BX to address of ARRAY before start of
array
DEC BX Decrement BX
MOV CX, 100 Put number of array elements in CX

NEXT: INC BX Point to next element in array


CMP [BX], OFFH Compare array element with FFH

LOOPE NEXT

LOOPNE / LOOPNZ (LOOP WHILE CX 0 AND ZF = 0)


This instruction is used to repeat a group of instructions some number of
times, or until the zero flag becomes a 1. The number of times the instruction
sequence is to be repeated is loaded into the count register CX. Each time the
LOOPNE / LOOPNZ instruction executes, CX is automatically decremented by 1.
If CX 0 and ZF = 0, execution will jump to a destination specified by a label in
the instruction. If CX = 0, after the auto decrement or if ZF = 1, execution
simply go on the next instruction after LOOPNE / LOOPNZ. In other words, the
two ways to exit the loop are CX = 0 or ZF = 1. The destination address for the
jump must be in the range of –128 bytes to +127 bytes from the address of the
instruction after the LOOPNE / LOOPZ instruction. This instruction does not affect
any flags.

MOV BX, OFFSET ARRAY Point BX to adjust before start of array


DEC BX Decrement BX
MOV CX, 100 Put number of array in CX
NEXT: INC BX Point to next element in array

CMP [BX], ODH Compare array element with 0DH


LOOPNZ NEXT

CALL (Call A Procedure)


The CALL instruction is used to transfer execution to a subprogram or a
procedure. There two basic type of calls near and far.

66
1. A near call is a call to a procedure, which is in the same code segment as the
CALL instruction. When the 8086 executes a near CALL instruction, it
decrements the stack pointer by 2 and copies the offset of the next
instruction after the CALL into the stack. This offset saved in the stack is
referred to as the return address, because this is the address that execution
will return to after the procedure is executed. A near CALL instruction will
also load the instruction pointer with the offset of the first instruction in the
procedure. A RET instruction at the end of the procedure will return
execution to the offset saved on the stack which is copied back to IP.

2. A far call is a call to a procedure, which is in a different segment from the


one that contains the CALL instruction. When the 8086 executes a far call, it
decrements the stack pointer by 2 and copies the content of the CS register
to the stack. It then decrements the stack pointer by 2 again and copies the
offset of the instruction after the CALL instruction to the stack. Finally, it
loads CS with the segment base of the segment that contains the procedure,
and loads IP with the offset of the first instruction of the procedure in that
segment. A RET instruction at the end of the procedure will return execution
to the next instruction after the CALL by restoring the saved values of CS
and IP from the stack.

CALL MULT
This is a direct within segment (near or intra segment) call. MULT is the
name of the procedure. The assembler determines the displacement of MULT
from the instruction after the CALL and codes this displacement in as part of the
instruction.

CALL BX
This is an indirect within-segment (near or intra-segment) call. BX
contains the offset of the first instruction of the procedure. It replaces content of
IP with content of register BX.

CALL WORD PTR [BX]


This is an indirect within-segment (near or intra-segment) call. Offset of

67
the first instruction of the procedure is in two memory addresses in DS. Replaces
content of IP with content of word memory location in DS pointed to by BX.

CALL DIVIDE
This is a direct call to another segment (far or inter-segment call). DIVIDE
is the name of the procedure. The procedure must be declared far with DIVIDE
PROC FAR at its start. The assembler will determine the code segment base for
the segment that contains the procedure and the offset of the start of the
procedure. It will put these values in as part of the instruction code.

CALL DWORD PTR [BX]


This is an indirect call to another segment (far or inter-segment call). New
values for CS and IP are fetched from four-memory location in DS. The new
value for CS is fetched from [BX] and [BX + 1]; the new IP is fetched from [BX
+ 2] and [BX +3].
RET (Return Execution From Procedure To Calling Program)
The RET instruction will return execution from a procedure to the next
instruction after the CALL instruction which was used to call the procedure. If the
procedure is near procedure (in the same code segment as the CALL
instruction), then the return will be done by replacing the IP with a word from
the top of the stack. The word from the top of the stack is the offset of the next
instruction after
the CALL. This offset was pushed into the stack as part of the operation of the
CALL instruction. The stack pointer will be incremented by 2 after the return
address is popped off the stack.

If the procedure is a far procedure (in a code segment other than the one
from which it is called), then the instruction pointer will be replaced by the word
at the top of the stack. This word is the offset part of the return address put
there by the CALL instruction. The stack pointer will then be incremented by 2.
The CS register is then replaced with a word from the new top of the stack. This
word is the segment base part of the return address that was pushed onto the
stack by a far call operation. After this, the stack pointer is again incremented by
2.

68
A RET instruction can be followed by a number, for example, RET 6. In
this case, the stack pointer will be incremented by an additional six addresses
after the IP when the IP and CS are popped off the stack. This form is used to
increment the stack pointer over parameters passed to the procedure on the
stack.
The RET instruction does not affect any flag.

STRING MANIPULATION INSTRUCTIONS


MOVS – MOVS Destination String Name, Source String Name
MOVSB – MOVSB Destination String Name, Source String Name
MOVSW – MOVSW Destination String Name, Source String Name
This instruction copies a byte or a word from location in the data segment
to a location in the extra segment. The offset of the source in the data segment
must be in the SI register. The offset of the destination in the extra segment
must be in the DI register. For multiple-byte or multiple-word moves, the
number of elements to be moved is put in the CX register so that it can function
as a counter. After the byte or a word is moved, SI and DI are automatically
adjusted to point to the next source element and the next destination element.
If DF is 0, then SI and DI will incremented by 1 after a byte move and by 2 after
a word move. If DF is 1, then SI and DI will be decremented by 1 after a byte
move and by 2 after a word move. MOVS does not affect any flag.

When using the MOVS instruction, you must in some way tell the
assembler whether you want to move a string as bytes or as word. There are
two ways to do this. The first way is to indicate the name of the source and
destination strings in the instruction, as, for example. MOVS DEST, SRC. The
assembler will code the instruction for a byte / word move if they were declared
with a DB / DW. The second way is to add a “B” or a “W” to the MOVS
mnemonic. MOVSB says move a string as bytes; MOVSW says move a string as
words.

MOV SI, OFFSET SOURCE Load offset of start of source string in DS


into SI
MOV DI, OFFSET DESTINATION Load offset of start of destination string in
ES into DI
69
CLD Clear DF to auto increment SI and DI
after move

MOV CX, 04H Load length of string into CX as counter


REP MOVSB Move string byte until CX = 0

LODS / LODSB / LODSW (Load String Byte Into Al Or String Word


Into Ax)
This instruction copies a byte from a string location pointed to by SI to AL,
or a word from a string location pointed to by SI to AX. If DF is 0, SI will be
automatically incremented (by 1 for a byte string, and 2 for a word string) to
point to the next element of the string. If DF is 1, SI will be automatically
decremented (by 1 for a byte string, and 2 for a word string) to point to the
previous element of the string. LODS does not affect any flag.

CLD Clear direction flag so that SI is auto-


incremented
MOV SI, OFFSET SOURCE Point SI to start of string
LODS SOURCE Copy a byte or a word from string to AL or AX

Note: The assembler uses the name of the string to determine whether the
string is of type bye or type word. Instead of using the string name to do this,
you can use the mnemonic LODSB to tell the assembler that the string is type
byte or the mnemonic LODSW to tell the assembler that the string is of type
word.

STOS / STOSB / STOSW (Store String Byte Or String Word)


This instruction copies a byte from AL or a word from AX to a memory
location in the extra segment pointed to by DI. In effect, it replaces a string
element with a byte from AL or a word from AX. After the copy, DI is
automatically incremented or decremented to point to next or previous element
of the string. If DF is cleared, then DI will automatically incremented by 1 for a
byte string and by 2 for a word string. If DI is set, DI will be automatically
decremented by 1 for a byte string and by 2 for a word string. STOS does not
70
affect any flag.

MOV DI, OFFSET


TARGET STOS
TARGET

Note: The assembler uses the string name to determine whether the string is of
type byte or type word. If it is a byte string, then string byte is replaced with
content of AL. If it is a word string, then string word is replaced with content of
AX.

MOV DI, OFFSET


TARGET STOSB

“B” added to STOSB mnemonic tells assembler to replace byte in string with
byte from AL. STOSW would tell assembler directly to replace a word in the
string with a word from AX.

CMPS / CMPSB / CMPSW (Compare String Bytes Or String Words)


This instruction can be used to compare a byte / word in one string with a
byte / word in another string. SI is used to hold the offset of the byte or word in
the source string, and DI is used to hold the offset of the byte or word in the
destination string.
The AF, CF, OF, PF, SF, and ZF flags are affected by the comparison, but
the two operands are not affected. After the comparison, SI and DI will
automatically be incremented or decremented to point to the next or previous
element in the two strings. If DF is set, then SI and DI will automatically be
decremented by 1 for a byte string and by 2 for a word string. If DF is reset,
then SI and DI will automatically be incremented by 1 for byte strings and by 2
for word strings. The string pointed to by SI must be in the data segment. The
string pointed to by DI must be in the extra segment.
The CMPS instruction can be used with a REPE or REPNE prefix to compare all
the elements of a string.

MOV SI, OFFSET FIRST Point SI to source string

71
MOV DI, OFFSET SECOND Point DI to destination string
CLD DF cleared, SI and DI will auto-increment after
compare
MOV CX, 100 Put number of string elements in CX

REPE CMPSB Repeat the comparison of string bytes until end


of string
or until compared bytes are not equal

CX functions as a counter, which the REPE prefix will cause CX to be


decremented after each compare. The B attached to CMPS tells the assembler
that the strings are of type byte. If you want to tell the assembler that strings
are of type word, write the instruction as CMPSW. The REPE CMPSW instruction
will cause the pointers in SI and DI to be incremented by 2 after each compare,
if the direction flag is set.

SCAS / SCASB / SCASW (Scan A String Byte Or A String Word)


SCAS compares a byte in AL or a word in AX with a byte or a word in ES
pointed to by DI. Therefore, the string to be scanned must be in the extra
segment, and DI must contain the offset of the byte or the word to be
compared. If DF is cleared, then DI will be incremented by 1 for byte strings and
by 2 for word strings. If DF is set, then DI will be decremented by 1 for byte
strings and by 2 for word strings. SCAS affects AF, CF, OF, PF, SF, and ZF, but it
does not change either the operand in AL (AX) or the operand in the string.
The following program segment scans a text string of 80 characters for a
carriage return, 0DH, and puts the offset of string into DI:

MOV DI, OFFSET STRING


MOV AL, 0DH Byte to be scanned for into AL
MOV CX, 80 CX used as element counter

CLD Clear DF, so that DI auto increments


REPNE SCAS STRING Compare byte in string with byte in AL

72
REP / REPE / REPZ / REPNE / REPNZ (PREFIX)
(Repeat String Instruction Until Specified Conditions Exist)
REP is a prefix, which is written before one of the string instructions. It
will cause the CX register to be decremented and the string instruction to be
repeated until CX = 0. The instruction REP MOVSB, for example, will continue to
copy string bytes until the number of bytes loaded into CX has been copied.

REPE and REPZ are two mnemonics for the same prefix. They stand for
repeat if equal and repeat if zero, respectively. They are often used with the
Compare String instruction or with the Scan String instruction. They will cause
the string instruction to be repeated as long as the compared bytes or words are
equal (ZF = 1) and CX is not yet counted down to zero. In other words, there
are two conditions that will stop the repetition: CX = 0 or string bytes or words
not equal.

REPE CMPSB Compare string bytes until end of string or


until string bytes not equal.

REPNE and REPNZ are also two mnemonics for the same prefix. They
stand for repeat if not equal and repeat if not zero, respectively. They are often
used with the Compare String instruction or with the Scan String instruction.
They will cause the string instruction to be repeated as long as the compared
bytes or words are not equal (ZF = 0) and CX is not yet counted down to zero.

REPNE SCASW Scan a string of word until a word in the string


matches the word
in AX or until all of the string has been scanned.
The string instruction used with the prefix determines which flags are affected.

FLAG MANIPULATION INSTRUCTIONS

STC (Set Carry Flag)


This instruction sets the carry flag to 1. It does not affect any other flag.

73
CLC (Clear Carry Flag)
This instruction resets the carry flag to 0. It does not affect any other flag.

CMC (Complement Carry Flag)


This instruction complements the carry flag. It does not affect any other
flag.

STD (Set Direction Flag)


This instruction sets the direction flag to 1. It does not affect any other
flag.

CLD (Clear Direction Flag)


This instruction resets the direction flag to 0. It does not affect any other
flag.

STI (Set Interrupt Flag)


Setting the interrupt flag to a 1 enables the INTR interrupt input of the
8086. The instruction will not take affect until the next instruction after STI.
When the INTR input is enabled, an interrupt signal on this input will then cause
the 8086 to interrupt program execution, push the return address and flags on
the stack, and execute an interrupt service procedure. An IRET instruction at the
end of the interrupt service procedure will restore the return address and flags
that were pushed onto the stack and return execution to the interrupted
program. STI does not affect any other flag.

CLI (Clear Interrupt Flag)


This instruction resets the interrupt flag to 0. If the interrupt flag is reset,
the 8086 will not respond to an interrupt signal on its INTR input. The CLI
instructions, however, has no effect on the non-maskable interrupt input, NMI. It
does not affect any other flag.

LAHF (Copy Low Byte Of Flag Register To Ah Register)


The LAHF instruction copies the low-byte of the 8086 flag register to AH
register. It can then be pushed onto the stack along with AL by a PUSH AX

74
instruction. LAHF does not affect any flag.

SAHF (Copy Ah Register To Low Byte Of Flag Register)


The SAHF instruction replaces the low-byte of the 8086 flag register with a byte
from the AH register. SAHF changes the flags in lower byte of the flag register.

STACK RELATED INSTRUCTIONS


PUSH – PUSH Source

The PUSH instruction decrements the stack pointer by 2 and copies a word from
a specified source to the location in the stack segment to which the stack pointer
points. The source of the word can be general-purpose register, segment
register, or memory. The stack segment register and the stack pointer must be
initialized before this instruction can be used. PUSH can be used to save data on
the stack so that it will not destroyed by a procedure. This instruction does not
affect any flag.

PUSH BX Decrement SP by 2, copy BX to stack.


PUSH DS Decrement SP by 2, copy DS to stack.
PUSH BL Illegal; must push a word
Decrement SP by 2, and copy word from
PUSH TABLE [BX] memory in DS at
EA = TABLE + [BX] to stack

POP – POP Destination

The POP instruction copies a word from the stack location pointed to by the stack
pointer to a destination specified in the instruction. The destination can be a
general-purpose register, a segment register or a memory location. The data in
the stack is not changed. After the word is copied to the specified destination,

75
the stack pointer is automatically incremented by 2 to point to the next word on
the stack. The POP instruction does not affect any flag.

Copy a word from top of stack to DX;


POP DX increment SP by 2
Copy a word from top of stack to DS;
POP DS increment SP by 2
Copy a word from top of stack to memory in
POP TABLE [DX] DS with
EA = TABLE + [BX]; increment SP by 2.

PUSHF (Push Flag Register To Stack)

The PUSHF instruction decrements the stack pointer by 2 and copies a word in
the flag register to two memory locations in stack pointed to by the stack
pointer. The stack segment register is not affected. This instruction does to
affect any flag.

POPF (Pop Word From Top Of Stack To Flag Register)

The POPF instruction copies a word from two memory locations at the top of the
stack to the flag register and increments the stack pointer by 2. The stack
segment register and word on the stack are not affected. This instruction does to
affect any flag.

INPUT-OUTPUT INSTRUCTIONS

IN – IN Accumulator, Port

The IN instruction copies data from a port to the AL or AX register. If an 8-bit


port is read, the data will go to AL. If a 16-bit port is read, the data will go to
AX.

76
The IN instruction has two possible formats, fixed port and variable port. For
fixed port type, the 8-bit address of a port is specified directly in the instruction.
With this form, any one of 256 possible ports can be addressed.

Input a byte from port


IN AL, OC8H OC8H to AL
Input a word from port 34H
IN AX, 34H to AX

For the variable-port form of the IN instruction, the port address is loaded into
the DX register before the IN instruction. Since DX is a 16-bit register, the port
address can be any number between 0000H and FFFFH. Therefore, up to 65,536
ports are addressable in this mode.

MOV DX, 0FF78H Initialize DX to point to port


IN AL, DX Input a byte from 8-bit port 0FF78H to AL
IN AX, DX Input a word from 16-bit port 0FF78H to AX

The variable-port IN instruction has advantage that the port address can be
computed or dynamically determined in the program. Suppose, for example,
that an 8086-based computer needs to input data from 10 terminals, each
having its own port address. Instead of having a separate procedure to input
data from each port, you can write one generalized input procedure and simply
pass the address of the desired port to the procedure in DX.

The IN instruction does not change any flag.

OUT – OUT Port, Accumulator

The OUT instruction copies a byte from AL or a word from AX to the specified
port. The OUT instruction has two possible forms, fixed port and variable port.

For the fixed port form, the 8-bit port address is specified directly in the
instruction. With this form, any one of 256 possible ports can be addressed.

77
Copy the content of AL to
OUT 3BH, AL port 3BH
Copy the content of AX to
OUT 2CH, AX port 2CH

For variable port form of the OUT instruction, the content of AL or AX will be
copied to the port at an address contained in DX. Therefore, the DX register
must be loaded with the desired port address before this form of the OUT
instruction is used.

MOV DX, 0FFF8H Load desired port address in DX


OUT DX, AL Copy content of AL to port FFF8H

OUT DX, AX Copy content of AX to port FFF8H

The OUT instruction does not affect any flag.

MISCELLANEOUS INSTRUCTIONS

HLT (Halt Processing)

The HLT instruction causes the 8086 to stop fetching and executing instructions.
The 8086 will enter a halt state. The different ways to get the processor out of
the halt state are with an interrupt signal on the INTR pin, an interrupt signal on
the NMI pin, or a reset signal on the RESET input.

NOP (Perform No Operation)

This instruction simply uses up three clock cycles and increments the instruction
pointer to point to the next instruction. The NOP instruction can be used to
increase the delay of a delay loop. When hand coding, a NOP can also be used to
hold a place in a program for an instruction that will be added later. NOP does
not affect any flag.
78
ESC (Escape)

This instruction is used to pass instructions to a coprocessor, such as the 8087


Math coprocessor, which shares the address and data bus with 8086.
Instructions for the coprocessor are represented by a 6-bit code embedded in
the ESC instruction. As the 8086 fetches instruction bytes, the coprocessor also
fetches these bytes from the data bus and puts them in its queue. However, the
coprocessor treats all the normal 8086 instructions as NOPs. When 8086 fetches
an ESC instruction, the coprocessor decodes the instruction and carries out the
action specified by the 6-bit code specified in the instruction. In most cases, the
8086 treats the ESC instruction as a NOP. In some cases, the 8086 will access a
data item in memory for the coprocessor.

INT – Int Type

The term type in the instruction format refers to a number between 0 and 255,
which identify the interrupt. When an 8086 executes an INT instruction, it will

1. Decrement the stack pointer by 2 and push the flags on to the stack.

2. Decrement the stack pointer by 2 and push the content of CS onto the stack.

3. Decrement the stack pointer by 2 and push the offset of the next instruction
after the INT number instruction on the stack.

4. Get a new value for IP from an absolute memory address of 4 times the type
specified in the instruction. For an INT 8 instruction, for example, the new IP
will be read from address 00020H.

5. Get a new for value for CS from an absolute memory address of 4 times the
type specified in the instruction plus 2, for an INT 8 instruction, for example,

79
the new value of CS will be read from address 00022H.
6. Reset both IF and TF. Other flags are not affected.

IRET

When the 8086 responds to an interrupt signal or to an interrupt instruction, it


pushes the flags, the current value of CS, and the current value of IP onto the stack.
It then loads CS and IP with the starting address of the procedure, which you write
for the response to that interrupt. The IRET instruction is used at the end of the
interrupt service procedure to return execution to the interrupted program. To do
this return, the 8086 copies the saved value of IP from the stack to IP, the stored
v
l alue of CS from the stack to CS, and the stored value of the flags back to the flag
register. Flags will have the values they had before the interrupt, so any flag
settings from the procedure will be lost unless they are specifically saved in some
way.
INT 35 New IP from 0008CH, new CS from 0008Eh
This is a special form, which has the single-byte
INT 3 code of CCH;
Many systems use this as a break point
instruction
(Get new IP from 0000CH new CS from 0000EH).

INTO (Interrupt On Overflow)

If the overflow flag (OF) is set, this instruction causes the 8086 to do an indirect
far call to a procedure you write to handle the overflow condition. Before doing
the call, the 8086 will
1. Decrement the stack pointer by 2 and push the flags on to the stack.

2. Decrement the stack pointer by 2 and push CS on to the stack.

3. Decrement the stack pointer by 2 and push the offset of the next instruction
after INTO instruction onto the stack.
4. Reset TF and IF. Other flags are not affected. To do the call, the 8086 will
read a new value for IP from address 00010H and a new value of CS from
address 00012H.

80
ASSEMBLER DIRECTIVE:
The SEGMENT directive is used to indicate the start of a logical segment.
Preceding the SEGMENT directive is the name you want to give the segment. For
example, the statement CODE SEGMENT indicates to the assembler the start of
a logical segment called CODE. The SEGMENT and ENDS directive are used to
“bracket” a logical segment containing code of data.

Additional terms are often added to a SEGMENT directive statement to indicate


some special way in which we want the assembler to treat the segment. The
statement CODE SEGMENT WORD tells the assembler that we want the content
Many microcomputer systems contain several microprocessors. Each microprocessor
has its own local buses and memory. The individual microprocessors are connected
together by a system bus so that each can access system resources such as disk
drive or memory. Each microprocessor takes control of the system bus only when it
needs to access some system resources. The LOCK prefix allows a microprocessor to
make sure that another processor does not take control of the system bus while it is
in the middle of a critical instruction, which uses the system bus. The LOCK prefix is
.put in front of the critical instruction. When an instruction with a LOCK prefix
executes, the 8086 will assert its external bus controller device, which then prevents
any other processor from taking over the system bus. LOCK instruction does not
affect any flag.
When this instruction is executed, the 8086 enters an idle condition in which it is
doing no processing. The 8086 will stay in this idle state until the 8086 test input pin
is made low or until an interrupt signal is received on the INTR or the NMI interrupt
input pins. If a valid interrupt occurs while the 8086 is in this idle state, the 8086
will return to the idle state after the interrupt service procedure executes. It returns
to the idle state because the address of the WAIT instruction is the address pushed
on the stack when the 8086 responds to the interrupt request. WAIT does not affect
any flag. The WAIT instruction is used to synchronize the 8086 with external
hardware such as the 8087 Math coprocessor.
of this segment located on the next available word (even address) when
segments ate combined and given absolute addresses. Without this WORD
addition, the segment will be located on the next available paragraph (16-byte)
address, which might waste as much as 15 bytes of memory. The statement

81
CODE SEGMENT PUBLIC tells the assembler that the segment may be put
together with other segments named CODE from other assembly modules when
the modules are linked together.

ENDS (End Segment)


This directive is used with the name of a segment to indicate the end of
that logical segment.

Start of logical segment containing code


CODE SEGMENT instruction statements
CODE ENDS End of segment named CODE

END (End Procedure)


The END directive is put after the last statement of a program to tell the
assembler that this is the end of the program module. The assembler will ignore
any statements after an END directive, so you should make sure to use only one
END directive at the very end of your program module. A carriage return is
required after the END directive.

ASSUME
The ASSUME directive is used tell the assembler the name of the logical
segment it should use for a specified segment. The statement ASSUME CS:
CODE, for example, tells the assembler that the instructions for a program are in
a logical segment named CODE. The statement ASSUME DS: DATA tells the
assembler that for any program instruction, which refers to the data segment, it
should use the logical segment called DATA.

DB (Define Byte)

The DB directive is used to declare a byte type variable, or a set aside one or
more storage locations of type byte in memory.

PRICES DB 49H, 98H, 29H Declare array of 3 bytes named PRICE and
initialize them
82
with specified values.
NAMES DB “THOMAS” Declare array of 6 bytes and initialize with ASCII
codes
for the letters in THOMAS.
TEMP DB 100 DUP (?) Set aside 100 bytes of storage in memory and
give it the name
TEMP. But leave the 100 bytes un-initialized.
PRESSURE DB 20H DUP (0) Set aside 20H bytes of storage in memory, give
it the name
PRESSURE and put 0 in all 20H locations.

DD (Define Double Word)


The DD directive is used to declare a variable of type double word or to
reserve memory locations, which can be accessed as type double word. The
statement ARRAY DD 25629261H, for example, will define a double word named
ARRAY and initialize the double word with the specified value when the program
is loaded into memory to be run. The low word, 9261H, will be put in memory at
a lower address than the high word.

DQ (Define Quadword)
The DQ directive is used to tell the assembler to declare a variable 4
words in length or to reserve 4 words of storage in memory. The statement
BIG_NUMBER DQ 243598740192A92BH, for example, will declare a variable
named BIG_NUMBER and initialize the 4 words set aside with the specified
number when the program is loaded into memory to be run.
DT (Define Ten Bytes)
The DT directive is used to tell the assembler to declare a variable, which
is 10 bytes in length or to reserve 10 bytes of storage in memory. The statement
PACKED_BCD DT 11223344556677889900 will declare an array named
PACKED_BCD, which is 10 bytes in length. It will initialize the 10 bytes with the
values 11, 22, 33, 44, 55, 66, 77, 88, 99, and 00 when the program is loaded
into memory to be run. The statement RESULT DT 20H DUP (0) will declare an
array of 20H blocks of 10 bytes each and initialize all 320 bytes to 00 when the
program is loaded into memory to be run.

83
DW (Define Word)
The DW directive is used to tell the assembler to define a variable of type
word or to reserve storage locations of type word in memory. The statement
MULTIPLIER DW 437AH, for example, declares a variable of type word named
MULTIPLIER, and initialized with the value 437AH when the program is loaded
into memory to be run.

WORDS DW 1234H, 3456H Declare an array of 2 words and initialize them


with the specified values.
STORAGE DW 100 DUP (0) Reserve an array of 100 words of memory and
initialize all 100
words with 0000. Array is named as STORAGE.
STORAGE DW 100 DUP (?) Reserve 100 word of storage in memory and
give it the name
STORAGE, but leave the words un-initialized.
EQU (Equate)
EQU is used to give a name to some value or symbol. Each time the
assembler finds the given name in the program, it replaces the name with the
value or symbol you equated with that name. Suppose, for example, you write
the statement FACTOR EQU 03H at the start of your program, and later in the
program you write the instruction statement ADD AL, FACTOR. When the
assembler codes this instruction statement, it will code it as if you had written
the instruction ADD AL, 03H.

84
CONTROL EQU 11000110 B MOV AL, CONTROL

DECIMAL_ADJUST EQU DAA ADD AL, BL DECIMAL_ADJUST

Replacement
Assignment

Create clearer mnemonic for DAA Add BCD numbers


Keep result in BCD format

LENGTH
LENGTH is an operator, which tells the assembler to determine the
number of elements in some named data item, such as a string or an array.
When the assembler reads the statement MOV CX, LENGTH STRING1, for
example, will determine the number of elements in STRING1 and load it into CX.
If the string was declared as a string of bytes, LENGTH will produce the number
of bytes in the string. If the string was declared as a word string, LENGTH will
produce the number of words in the string.

OFFSET
OFFSET is an operator, which tells the assembler to determine the offset
or displacement of a named data item (variable), a procedure from the start of
the segment, which contains it. When the assembler reads the statement MOV
BX, OFFSET PRICES, for example, it will determine the offset of the variable
PRICES from the start of the segment in which PRICES is defined and will load
this value into BX.

PTR (POINTER)
The PTR operator is used to assign a specific type to a variable or a label.
It is necessary to do this in any instruction where the type of the operand is not
clear. When the assembler reads the instruction INC [BX], for example, it will
not know whether to increment the byte pointed to by BX. We use the PTR
operator to clarify how we want the assembler to code the instruction. The

85
statement INC BYTE PTR [BX] tells the assembler that we want to increment the
byte pointed to by BX. The statement INC WORD PTR [BX] tells the assembler
that we want to increment the word pointed to by BX. The PTR operator assigns
the type specified before PTR to the variable specified after PTR.

We can also use the PTR operator to clarify our intentions when we use indirect
Jump instructions. The statement JMP [BX], for example, does not tell the
assembler whether to code the instruction for a near jump. If we want to do a
near jump, we write the instruction as JMP WORD PTR [BX]. If we want to do a
far jump, we write the instruction as JMP DWORD PTR [BX].

EVEN (Align On Even Memory Address)


As an assembler assembles a section of data declaration or instruction
statements, it uses a location counter to keep track of how many bytes it is from
the start of a segment at any time. The EVEN directive tells the assembler to
increment the location counter to the next even address, if it is not already at an
even address. A NOP instruction will be inserted in the location incremented
over.

DATA SEGMENT
SALES DB 9 DUP (?) Location counter will point to 0009 after this
instruction.
EVEN Increment location counter to 000AH

INVENTORY DW 100 DUP (0) Array of 100 words starting on even address
for quicker read DATA ENDS

PROC (Procedure)
The PROC directive is used to identify the start of a procedure. The PROC
directive follows a name you give the procedure. After the PROC directive, the
term near or the term far is used to specify the type of the procedure. The
statement DIVIDE PROC FAR, for example, identifies the start of a procedure
named DIVIDE and tells the assembler that the procedure is far (in a segment
with different name from the one that contains the instructions which calls the

86
procedure). The PROC directive is used with the ENDP directive to “bracket” a
procedure.

ENDP (End Procedure)


The directive is used along with the name of the procedure to indicate the
end of a procedure to the assembler. The directive, together with the procedure
directive, PROC, is used to “bracket” a procedure.

Start of
SQUARE_ROOT PROC procedure.
End of
SQUARE_ROOT ENDP procedure.

ORG (Origin)
As an assembler assembles a section of a data declarations or instruction
statements, it uses a location counter to keep track of how many bytes it is from
the start of a segment at any time. The location counter is automatically set to
0000 when assembler starts reading a segment. The ORG directive allows you to
set the location counter to a desired value at any point in the program. The
statement ORG 2000H tells the assembler to set the location counter to 2000H,
for example.

A “$” it often used to symbolically represent the current value of the location
counter, the $ actually represents the next available byte location where the
assembler can put a data or code byte. The $ is often used in ORG statements to
tell the assembler to make some change in the location counter relative to its
current value. The statement ORG $ + 100 tells the assembler increment the
value of the location counter by 100 from its current value.

NAME
The NAME directive is used to give a specific name to each assembly
module when programs consisting of several modules are written.

LABEL

87
As an assembler assembles a section of a data declarations or instruction
statements, it uses a location counter to be keep track of how many bytes it is
from the start of a segment at any time. The LABEL directive is used to give a
name to the current value in the location counter. The LABEL directive must be
followed by a term that specifics the type you want to associate with that name.
If the label is going to be used as the destination for a jump or a call, then the
label must be specified as type near or type far. If the label is going to be used
to reference a data item, then the label must be specified as type byte, type
word, or type double word. Here’s how we use the LABEL directive for a jump
address.

ENTRY_POINT LABEL FAR Can jump to here from another segment


NEXT: MOV AL, BL Can not do a far jump directly to a label with a
colon

The following example shows how we use the label directive for a data
reference.

STACK_SEG SEGMENT STACK


DW 100 DUP (0) Set aside 100 words for stack

STACK_TOP LABEL WORD Give name to next location after last word in
stack
STACK_SEG ENDS
To initialize stack pointer, use MOV SP, OFFSET STACK_TOP.

EXTRN
The EXTRN directive is used to tell the assembler that the name or labels
following the directive are in some other assembly module. For example, if you
want to call a procedure, which in a program module assembled at a different
time from that which contains the CALL instruction, you must tell the assembler
that the procedure is external. The assembler will then put this information in
the object code file so that the linker can connect the two modules together. For
a reference to externally named variable, you must specify the type of the
variable, as in the statement EXTRN DIVISOR: WORD. The statement EXTRN

88
DIVIDE: FAR tells the assembler that DIVIDE is a label of type FAR in another
assembler module. Name or labels referred to as external in one module must
be declared public with the PUBLIC directive in the module in which they are
defined.

PROCEDURE SEGMENT

EXTRN DIVIDE: FAR Found in segment PROCEDURES


PROCEDURE ENDS

PUBLIC
Large program are usually written as several separate modules. Each
module is individually assembled, tested, and debugged. When all the modules
are working correctly, their object code files are linked together to form the
complete program. In order for the modules to link together correctly, any
variable name or label referred to in other modules must be declared PUBLIC in
the module in which it is defined. The PUBLIC directive is used to tell the
assembler that a specified name or label will be accessed from other modules.
An example is the statement PUBLIC DIVISOR, DIVIDEND, which makes the two
variables DIVISOR and DIVIDEND available to other assembly modules.

SHORT
The SHORT operator is used to tell the assembler that only a 1 byte
displacement is needed to code a jump instruction in the program. The
destination must in the range of –128 bytes to +127 bytes from the address of
the instruction after the jump. The statement JMP SHORT NEARBY_LABEL is an
example of the use of SHORT.

TYPE
The TYPE operator tells the assembler to determine the type of a specified
variable. The assembler actually determines the number of bytes in the type of
the variable. For a byte-type variable, the assembler will give a value of 1, for a
word-type variable, the assembler will give a value of 2, and for a double word-
type variable, it will give a value of 4. It can be used in instruction such as ADD

89
BX, TYPE-WORD-ARRAY, where we want to increment BX to point to the next
word in an array of words.
GLOBAL (Declare Symbols As Public Or Extrn)
The GLOBAL directive can be used in place of a PUBLIC directive or in
place of an EXTRN directive. For a name or symbol defined in the current
assembly module, the GLOBAL directive is used to make the symbol available to
other modules. The statement GLOBAL DIVISOR, for example, makes the
variable DIVISOR public so that it can be accessed from other assembly
modules.

INCLUDE (Include Source Code From File)


This directive is used to tell the assembler to insert a block of source code
from the named file into the current source module.
ADDRESSING MODES OF 8086
The set of mechanisms by which an instruction can specify how to obtain
its operands is known as Addressing modes. The CPU can access
the operands (data) in a number of different modes.
The addressing modes available in Intel 8086 are: 1. Register
Addressing 2. Immediate Addressing 3. Direct Addressing 4.
Register Indirect Addressing 5. Based Relative Addressing 6.
Indexed Relative Addressing
7. Based Indexed Relative Addressing
Register Addressing Mode: With the Register Addressing mode the
operand to be accessed is specified as residing in an internal
register of the 8086.
Example: MOV AX , BX This stands for move the contents of BX (the
source operand) to AX (the destination operand).Both the source
and the destination operands have been specified as the contents of
internal registers of the 8086.
Immediate Addressing Mode: If a source operand is part of the
instruction instead of the contents of a register or memory location,
it represents what is called the immediate operand and is accessed
using immediate addressing mode. Typically immediate operand

90
represents constant data. Immediate operands can be either a byte
or word of data.
Example: MOV AL , 015H In this instruction the operand 015H is an
example of a byte wide immediate source operand. The destination
operand, which consists of the contents of AL, uses register
addressing. Thus this instruction employs both immediate and
registers addressing modes
Direct Addressing Mode : Direct addressing differs from immediate
addressing, that the locations following the instruction op-code hold
an effective memory address (EA). This effective address is a 16-bit
offset of the storage location of the operand from the current value
in the data segment (DS) register .EA is combined with the contents
of DS in the BIU to produce the physical address of the operand.
Example: MOV CX , BETA This stands for move the contents of the
memory location, which is offset by BETA from the current value in
DS into internal register CX.
Register Indirect Addressing Mode: Register indirect addressing is
similar to direct addressing, that an effective address is combined
with the contents of DS to obtain a physical address. However it
differs in a way that the offset is specified. Here EA resides in either
a pointer register or an index register within the 8086.The pointer
register can be either a base register BX or a base pointer register
BP and the index register can be source index register SI or the
destination index register DI.
Example MOV AX , [SI] This instruction moves the contents of the
memory location offset by the value of EA in SI from the current
value in DS to the AX register.
Based Addressing Mode: In the based addressing mode, the physical
address of the operand is obtained by adding a direct or indirect
displacement of the contents of either base register BX or base
pointer register BP and the current value in DS and SS respectively.
Example MOV [BX] . BETA , AL This instruction uses base register BX and

91
direct displacement BETA to derive the EA of the destination
operand. The based addressing mode is implemented by specifying
the base register in the brackets followed by a period and direct
displacement .The source operand is located in the byte
accumulator AL.
Indexed Addressing Mode: Indexed addressing mode works identically
to the based addressing but it uses the contents of the index
registers instead of BX or BP, in the generation of the physical
address.
Example MOV AL , ARRAY [SI] The source operand has been specified
using direct index addressing. The notation this time is such ARRAY,
which is a direct displacement, prefixes the selected index register,
SI.
Based Indexed Addressing Mode: Combining the based addressing mode
and the indexed addressing mode together results in a new, more
powerful mode known as based indexed addressing.
Example: MOV AH , [BX] . BETA [SI] Here the source operand is
accessed using the based indexed addressing mode. The effective
address of the source operand is obtained as EA=(BX)+BETA+(SI)

Simple ALP’s
1. Write an ALP to find factorial of number for 8086.

MOV AX, 05H

MOV CX, AX

Back: DEC CX

MUL CX

LOOP back

results stored in AX

to store the result at

D000H

92
MOV [D000], AX

HLT

2 The 8 data bytes are stored from memory location E000H to E007H. Write 8086
ALP to transfer the block of data to new location B001H to B008H.

MOV BL, 08H

MOV CX, E000H

MOV EX, B001H

Loop: MOV DL, [CX]

MOV [EX], DL

DEC BL

JNZ loop

HLT

3. Write a program to display string ‘Electronics Engineering’ for 8086.

.model small

.stack

.data

String1 db ‘ Electronics Engineering’, $

.code

Main

proc

MOV AX, @data

MOV DS, AX

MOV AH, 09H

MOV DX, offset String1

93
INT 21H

MOV AH, 4CH

INT 21H

Main endp
End Main
4. Write a program to reverse the given string for 8086.
Title reverse the given string
.model small
.stack 100h
.data
String1 db .assembly language program., $
Length dw $-String1-1
.code
Main proc
MOV AX, @data
MOV DS, AX
MOV SI, offset String1
MOV CX, Length
ADD SI, CX
Back: MOV DL, [SI]
MOV AH, 02H
INT 21H
DEC SI
LOOP Back
MOV AH, 4CH
INT 21H
Main endp
end

5. Sum of series of 10 numbers and store result in memory location total.


Title Sum of series
.model small
.stack 100h
.data
List db 12,34,56,78,98,01,13,78,18,36
Total dw ?
.code
Main proc
MOV AX, @data
MOV DS, AX
MOV AX, 0000H
MOV CX, 0AH ; counter
MOV BL, 00H ; to count carry
MOV SI, offset List
Back: ADD AL, [SI]
JC Label

94
Back1: INC SI
LOOP Back
MOV Total, AX
MOV Total+2, BL
MOV AH, 4CH
INT 21H
Label: INC BL
JMP Back1
Main endp
End Main

PART A
1. How will carry and zero flags reflect the result of the instruction CMP BX, CX?
2. Write any four miscellaneous instructions in 16 bit microprocessor.
3. What is the purpose of LEA instruction in 8086?
4. List any four program control instructions available in 8086.
5. What are the 8086 instructions used for BCD arithmetic?
6. State the function of the given 8085 instructions JP, JPE, JPO, and JNZ.
7. List any two external hardware synchronization instructions.
8. What is the purpose of the following commands in 8086?

a) AAD

b) RCL

9. Write an ALP for 8086 to multiply two 16 bit unsigned numbers.

10.List any four string instructions.

11.List the addressing modes in 8086.

12.What is an assembler?

13. What is an assembler directive? Write two examples.

14. What is the function of the assembler directives ALIGN and ASSUME?

15.What is the function of the assembler directives SEGMENT and ENDS?

16.What is the function of the assembler directives TITLE and TYPE?

95
PART B

1. Explain the 8086 instructions used for transferring data between registers,
memory, stack, and I/O devices.

2. Write a program using 8086 instruction set to multiply a constant value with
a sequence of data, from 1 to n, stored in memory.

3. Write a program using 8086 instruction set to compute the average of ‘n’
number of bytes stored in the memory.

4. Explain data transfer, arithmetic and logical group instructions of 8086


microprocessor.

5. Write an assembly language program for 8086 to arrange the set of numbers
in ascending order and explain.

6. How are the 8086 instructions classified according to their functional


categories? Explain with an example for each.

7. Write an assembly language program for 8086 to multiply two 16 bit binary
numbers to generate a 32 bit result.

8. Explain with examples the following 8086 instructions

a) AAA

b) CBW

c) IMUL

d) INTO

9. Write an assembly language program for 8086 to sort the array of elements
in ascending order.

10. Write an assembly language program for 8086 to find the largest element in
an array.

11. Explain the 8086 bit manipulation instructions with an example for each.

12. Write an assembly language program for 8086 to convert BCD data to binary
data.

13. Explainthe various assembler directives in 8086 microprocessor


programming.

14. What is the function of the ASSUME, DB, EQU, EVEN assembler directives of
8086?

96
15. Explain the assembler directives ASSUME, EQU, DW, and EVEN with suitable
examples.

16. Explain the relative addressing mode and the implied addressing mode with
its syntax. Write an example for each.

17. Explain the operand addressing of 8086 with examples.

97
UNIT –III

MSP 430

INTRODUCTION

System: A system is an arrangement in which all its unit assemble work together according to a
set of rules. It can also be defined as a way of working, organizing or doing one or many tasks
according to a fixed plan.
For example, a watch is a time displaying system. Its components follow a set of rules to show
time. If one of its parts fails, the watch will stop working. So we can say, in a system, all its
subcomponents depend on each other.
Embedded System: As its name suggests, Embedded means something that is attached to another
thing. An embedded system can be thought of as a computer hardware system having software
embedded in it. An embedded system can be an independent system or it can be a part of a large
system. An embedded system is a microcontroller or microprocessor based system which is
designed to perform a specific task.
For example, a fire alarm is an embedded system; it will sense only smoke. An embedded system
has three components −
 It has hardware.
 It has application software.
 It has Real Time Operating system
RTOSRTOS that supervises the application software and provide mechanism to let the processor
run a process as per scheduling by following a plan to control the latencies. RTOS defines the
way the system works. It sets the rules during the execution of application program. A small
scale embedded system may not have RTOS.
So we can define an embedded system as a Microcontroller based, software driven, reliable,
realtime control system.
Characteristics of an Embedded System
Single functioned: − An embedded system usually performs a specialized operation and does
the samerepeatedly. For example: A pager always functions as a pager.
Tightly constrained − All computing systems have constraints on design metrics, but those on an

98
embedded system can be especially tight. Design metrics is a measure of an implementation's
features suchas its cost, size, power, and performance. It must be of a size to fit on a single chip,
must perform fast enough to process data in real time and consume minimum power to extend
battery life.
Reactive and Real time − Many embedded systems must continually react to changes in the
system's environment and must compute certain results in real time without any delay. Consider
an example of a car cruise controller; it continually monitors and reacts to speed and brake
sensors. It must compute acceleration or de-accelerations repeatedly within a limited time; a
delayed computation can result in failure to control of the car.
Microprocessors based − It must be microprocessor or microcontroller based.
Memory − It must have a memory, as its software usually embeds in ROM. It does not need any
secondary memories in the computer.
Connected − It must have connected peripherals to connect input and output devices.
HWSW systems − Software is used for more features and flexibility. Hardware is used for
performance and security.

ASIP and
ASIC Analog IO

Memory

Processor
Digital IO
Cores

Basic Structure of an Embedded System


The following illustration shows the basic structure of an embedded system –

99
Sensor − It measures the physical quantity and converts it to an electrical signal which can be
read by an observer or by any electronic instrument like an A2D converter. A sensor stores the
measured quantity to the memory.
AD Converter − An analog to digital converter converts the analog signal sent by the sensor
into a digital signal.
Processor & ASICs − Processors process the data to measure the output and store it to the
memory.
DA Converter − A digital to analog converter converts the digital data fed by the processor to
analog data
Actuator − An actuator compares the output given by the DA Converter to the actual Expected
expected output stored in it and stores the approved output.
APPLICATIONS
•Household appliances: Microwave ovens, Television, DVD Players & Recorders
•Audio players
•Integrated systems in aircrafts and missiles
•Cellular telephones
•Electric and Electronic Motor controllers
•Engine controllers in automobiles
•Calculators
• Medical equipments
•Videogames
•Digital musical instruments, etc.

100
FEATURES

Features of Embedded Systems?

Ø Embedded systems example the versatility of the embedded computer system lends itself to
utility in all kinds of enterprises, from the simplification of deliverable products to a reduction in
costs in their development and manufacture.

Ø Embedded Systems are the crucial components of the modern compacted devices with
multifunction capabilities. Embedded systems are specific computer programs that combine the
functions of specially designed software’s and hardware’s and are completely encapsulated by
the devices that they control.

101
Ø An embedded system has specific requirements and performs pre-defined tasks, unlike a
general-purpose personal computer. An embedded system is a programmed hardware device. A
programmable hardware chip is the platform and it is programmed with particular applications.
Embedded systems are a combination of hardware and software which facilitates mass
production and a host of applications.

Features of Embedded Operating System?

1- Embedded systems are designed to do some specific task, rather than be a general-purpose
computer for multiple tasks. Some also have real-time performance constraints that must be met,
for reasons such as safety and usability; others may have low or no performance requirements,
allowing the system hardware to be simplified to reduce costs.

2- Embedded systems are not always standalone devices. Many embedded systems consist of
small, computerized parts within a larger device that serves a more general purpose. For
example, the Gibson Robot Guitar features an embedded system for tuning the strings, but the
overall purpose of the Robot Guitar is, of course, to play music similarly, an embedded system in
an automobile provides a specific function as a subsystem of the car itself.

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

* Size & Weight : Microcontrollers are designed to deliver maximum performance for
minimum size and weight. A centralised on-board computer system would greatly outweigh a
collection of microcontrollers.

* Efficiency : Microcontrollers are designed to perform repeated functions for long periods
of time without failing or requiring service. Other computer systems are prone to software and
hardware failure as well as a whole host of other problems recognisable to the users of any home
computer. Above all other considerations, computer systems must be 100% reliable when trusted
to control such functions as braking in an automobile.

102
Embedded Systems Architecture Types
The 8051 microcontrollers work with 8bit data bus. So they can support external data
memory up to 64K and external program memory of 64k at best. Collectively, 8051
microcontrollers can address 128k of external memory.
When data and code lie in different memory blocks, then the architecture is referred as
Harvard architecture. In case data and code lie in the same memory block, then the architecture is
referred as Von Neumann architecture.
Von Neumann Architecture
The Von Neumann architecture was first proposed by a computer scientist John von
Neumann. In this architecture, one data path or bus exists for both instruction and data. As a
result, the CPU does one operation at a time. It either fetches an instruction from memory, or
performs read/write operation on data. So an instruction fetch and a data operation cannot occur
simultaneously, sharing a common bus.

103
Von-Neumann architecture supports simple hardware. It allows the use of a single, sequential
memory. Today's processing speeds vastly outpace memory access times, and we employ a very
fast but small amount of memory cache local to the processor.
Harvard Architecture
The Harvard architecture offers separate storage and signal buses for instructions and
data. This architecture has data storage entirely contained within the CPU, and there is no access
to the instruction storage as data. Computers have separate memory areas for program
instructions and data using internal data buses, allowing simultaneous access to both instructions
and data. Programs needed to be loaded by an operator; the processor could not boot itself. In a
Harvard architecture, there is no need to make the two memories share properties.

VonNeumann Architecture vs Harvard Architecture


The following points distinguish the Von Neumann Architecture from the Harvard Architecture .

Von-Neumann Architecture Harvard Architecture


 Single memory to be shared by both  Separate memories for code and data.

104
code and data  Single clock cycle is sufficient, as
 Processor needs to fetch code in a separate buses are used to access code
separate clock cycle and data in another and data.
clock cycle. So it requires two clock  Slower in speed, thus more time
cycles. consuming
 Higher speed, thus less time consuming  Complex in design.
 Simple in design.

CISC and RISC


CISC is a Complex Instruction Set Computer. It is a computer that can address a large
number of instructions. In the early 1980s, computer designers recommended that computers
should use fewer instructions with simple constructs so that they can be executed much faster
within the CPU without having to use memory. Such computers are classified as Reduced
Instruction Set Computer or RISC.
CISC vs RISC
The following points differentiate a CISC from a RISC –
CISC RISC

 Larger set of instructions. Easy to  Larger set of instructions. Easy to


program program
 Simpler design of compiler,  Complex design of compiler
considering larger set of instructions.  Few addressing modes, fix instruction
 Many addressing modes causing format
complex instruction formats.  Instruction length varies
 Instruction length is variable.  Low clock cycle per second
 Higher clock cycles per second.  Emphasis is on software.
 Emphasis is on hardware  Each instruction is to be executed
 Control unit implements large by hardware
instruction set using micro program  Faster execution, as each instruction is
unit. to be
 Slower execution, as instructions are to  executed by hardware

105
be read from memory and decoded by  Pipelining of instructions is possible,
the decoder unit. considering single clock cycle.
 Pipelining is not possible.

RAM (RANDOM ACCESS MODEL):


Random access model A memory-, a data byte, or a word, or a double word, or a quad
word may be accessed from or at all addressable locations with a similar process would be used
to access from all locations and there is would be equal access time for a read or for a write that
is independent of a memory address location. This mode differentiates from another model called
serial access mode Addresses Addresses Memory (both RAM and ROM) divided into a set of
storage locations, each of which can hold 1 byte (8 bits) of data. The storage locations are
numbered, and the number of a storage location (called its address) is used to tell the memory
system which location the processor wants to reference. Important characteristics of a computer
system is the width of the addresses it uses, which limits the amount of memory that the
processor can address. Most current computers use either 32-bit or 64-bit addresses, allowing
them to access either 232 or 264 bytes of memory. Simple model for RAM and ROM Both has
random-access model of memory All memory operations take the same amount of time
independent of the address of the byte or word at the memory. Simple model for RAM and ROM
Both has random-access model of memory All memory operations take the same amount of time
independent of the address of the byte or word at the memory.
Can be both read and, written, Hold the programs, operating system, and data required by the system.
Generally volatile, meaning that it does not retain the data stored in it when the system 's power is
turned off. A Data that needs to be stored while the system is off must be written to a permanent
storage device, such as a flash memory or hard disk. An example is as follows: A mobile phone has 128
kB or 256 kB of RAM to hold the stack and temporary variables of the programs, operating system, and
data.

ROM: The RAM can be both read and, written, and is used to hold the programs, operating system,
and data required by a computer system. In embedded systems, it holds the stack and temporary
variables of the programs, operating system, and data. RAM is generally volatile, does not retain the
data stored in it when the system 's power is turned off. Any data that needs to be stored while the
system is off must be written to a permanent storage device, such as a flash memory or hard

106
disk. Contents of the read-only memory cannot be modified by the computer but may be read. A
system has ROM unit(s) ─for bootstrap program(s), basic input-output system (BIOS) program(s) and for
vector addresses for the interrupts Used to hold bootstrap program that is executed automatically by
the system every time it is turned on or reset. Instructs the system to load its operating system off ROM
image holds the programs, operating system, and data required by the system.

MEMORY MAPS
Memory Maps A memory map for a processor defines how addresses get mapped to hardware. The
total size of the address space is constrained by the address width of the processor. A 32-bit processor,
for example, can address 232 locations, or 4 gigabytes (GB), assuming each address refers to one byte.
The address width typically matches the word width, except for 8-bit processors, where the address
width is typically higher (often 16 bits). An ARM CortexTM - M3 architecture, for example, has the
memory map shown in Figure 8.1. Other architectures will have other layouts, but the pattern is similar.
Notice that this architecture separates addresses used for program memory (labeled A in the figure)
from those used for data memory (B and D). This (typical) pattern allows these memories to be accessed
via separate buses, permitting instructions and data to be fetched simultaneously. This effectively
doubles the memory bandwidth. Such a separation of program memory from data memory is known as
a Harvard architecture. It contrasts with the classical von Neumann architecture, which stores program
and data in the same memory. Any particular realization in silicon of this architecture is constrained by
this memory map. For example, the Luminary Micro1 LM3S8962 controller, which includes an ARM
CortexTM - M3 core, has 256 KB of on-chip flash memory, nowhere near the total of 0.5 GB that the
architecture allows. This memory is mapped to addresses 0x00000000 through 0x0003FFFF. The
remaining addresses that the architecture allows for program memory, which are 0x00040000 through
0x1FFFFFFF are “reserved addresses,” meaning that they should not be used by a compiler targeting this
particular device. The LM3S8962 has 64 KB of SRAM, mapped to addresses 0x20000000 through
0x2000FFFF, a small portion of area B in the figure. It also includes a number of on-chip peripherals,
which are devices that are accessed by the processor using some of the memory addresses in the range
from 0x40000000 to 0x5FFFFFFF (area C in the figure). These include timers, ADCs, GPIO, UARTs, and
other I/O devices. Each of these devices occupies a few of the memory addresses by providing memory-
mapped registers. The processor may write to some of these registers to configure and/or control the
peripheral, or to provide data to be produced on an output. Some of the registers may be read to
retrieve input data obtained by the peripheral. A few of the addresses in the private peripheral bus
region are used to access the interrupt controller.

107
I/O HARDWARE
Embedded processors, be they microcontrollers, DSP processors, or general-purpose processors,
typically include a number of input and output (I/O) mechanisms on chip, exposed to designers

108
as pins of the chip. In this section, we review some of the more common interfaces provided,
illustrating their properties through the following running example.
The I/O ports are used to connect input and output devices. The common input devices for an
embedded system include keypads, switches, buttons, knobs, and all kinds of sensors (light,
temperature, pressure, etc). The output devices include Light Emitting Diodes (LED), Liquid
Crystal Displays (LCD), printers, alarms, actuators , etc. Some devices support both input and
output, such as communication interfaces including Network Interface Cards (NIC), modems,
and mobile phones.

TIMERS AND INTERRUPTS


Time and event management in embedded systems
• An introduction to timers
• Using the mbed Timer object
• Using multiple timers
• Using the mbed Ticker object
• Hardware interrupts
• External interrupts on the mbed
• Switch debouncing for interrupt control
• Extended exercises
Time and event management in embedded systems
• Many embedded systems need high precision timing control and the ability to respond urgently
to critical requests
• For example:
– A video camera needs to capture image data at very specific time intervals, and to a high
degree of accuracy, to enable smooth playback
– A automotive system needs to be able to respond rapidly to a crash detection sensor in order to
activate the passenger airbag
• Interrupts allow software processes to be halted while another, higher priority section of
software executes
• Interrupt routines can be programmed to execute on timed events or by events that occur
externally in hardware

109
• Routines executed by events that occur from an external source (e.g. a mouse click or input
from another program) can be referred to as ‘event driven’.
An introduction to timers
• Interrupts in embedded systems can be thought of as functions which are called by specific
events rather than directly in code.
• The simplest type of interrupt is one which automatically increments a counter at a periodic
interval, this is done behind the scenes while the software is operating.
• Most microcontrollers have built in timers or real-time-interrupts which can be used for this
purpose. • The main code can then be executed at specified time increments by evaluating the
counter value. • For example, we can set some pieces of software to operate every 10ms and
others to operate every 100ms. We call this scheduled programming.
Using the mbed Timer object
We can use the mbed Timer object to perform scheduled programming:

Using multiple timers


With scheduled programs we often need to execute different sections of code at different rates.
• Consider an automotive system:
– The engine spark, valve and fuel injection system needs to be controlled and executed at a
high speed, perhaps every 1 ms or less given that the engine revolves at anything up to 8,000
revs per minute.

110
– The fuel tank level monitoring system needs to report the fuel level less often, perhaps every
1000 ms is sufficient.
• There is no point in executing both the injection management and the fuel level management
systems at the same rate.
• For this reason we can use synchronous programs to improve efficiency
INTERFACING USING SYSTEM BUS
Interfacing of processor, memory and IO devices using memory system bus
System bus ─ interconnections for a simple bus structure has three sets of signals
System bus ─ defines by address bus, data bus, and control bus
A system-bus interfacing-design is according to the timing diagrams of processor signals, speed,
and word length for instructions and data.
Interconnections for a simple bus structure

Interfacing of processor, memory and IO devices using memory system bus


ADDRESS BUS: Processor issues the address of the instruction byte or word to memory system
through the address bus. Processor execution unit, when required, issues the address of data
(byte or word) to be read or written using the memory system through address bus. The address
bus of 32-bits used to fetch the instruction or data from an address specified by 32-bit number.
EXAMPLE

111
 Let a processor at the start reset the program counter at address 0. Then the processor
issues address 0 on the bus and the instruction at address 0 is fetched from memory on
reset
 Let a processor instruction be such that it needs to load register r1 from the memory
address M. The processor issues address M on the address bus and data at address M is
fetched.
DATA BUS: Data Bus • Instruction fetch─ Processor issues the address of the instruction, it gets
back the instruction through the data bus. • Data Read─ When it issues the address of the data, it
loads the data through data bus. • Data Write ─ When it issues the address of the data, it stores
the data in the memory through the data bus. A data bus of 32-bits fetches, loads, or stores the
instruction or data of 32-bits.
EXAMPLE
 Processor issues address m for an instruction, it fetches the instruction through data bus
from address m. [For a 32-bit instruction, word at data bus from addresses m, m + 1, m +
2, and m + 3.]
 Instruction executes for store of register r1 bits to the memory address M, the processor
issues address M on the bus and sends the data at address M through the data bus. [For
32-bit data, word at data bus sent to the memory addresses M, M + 1, M + 2, and M + 3.]
CONTROL BUS Control Bus Issues signals to control the timing of various actions during
interconnection. Signals synchronize all the subsystems. address latch enable (ALE)[ Address
Strobe (AS) or address valid, (ADV)], memory ‘read’ (RD) or ‘write’ (WR) or IO ‘read’
(IORD) or ‘write,’(IOWR) or ‘data valid’(DAV) Other control signals as per the processor
design.
Interrupts and DMA Control Signals Interrupts and DMA Control Signals Interrupt
acknowledge (INTA) [on a request for drawing the processor attention to an event] INT
(Interrupt) from external device interrupt to the system Hold acknowledge (HLDA) [on an
external hold request for permitting use of the system buses] HOLD when external device sends
a hold request for direct memory access (DMA).
Program memory access and data buses multiplexed for memory access in Harvard
Architecture
Address and data buses are multiplexed

112
Control signal PSEN active when accessing program memory using the address and data buses
Control signal Read or Write active when accessing data memory using the address and data
buses
Time division multiplexed (TDM) address and data bits for the memories
TDM ─ Different time slots, there are is a different set sets (channel) of the signals.
Address signals during one time slot t. and data bus signals in another time slot.
Interfacing circuit for the demultiplexing of the buses uses a control signal in such systems.
Control signal Address Latch Enable (ALE) in 8051, Address Strobe (AS) in 68HC11 and
address valid (ADV) in 80196. ALE or AS or ADV demultiplexes the address and data buses to
the devices
Interfacing Using System and IO 2. Interfacing Using System and IO Buses
System Bus and IO Bus
 System bus interconnects
 processor
 memory systems and subsystems
 Another set of signals called I/O bus
 Interfacing of processor with system bus at first level and IO bus at second level
Popular IO buses and wireless communication
PCI Bus interfaces to devices designed to meet the PCI standard.
USB interfaces to devices designed to meet the USB IOs
PCI Bus interfaces to devices designed to meet the PCI standard. USB interfaces to devices
designed to meet the USB IOs
Memory system bus and I/O bus interconnections in a bus structure

113
MSP430 FUNCTIONAL BLOCK DIAGRAM
On the left is the CPU and its supporting hardware, including the clock generator. The emulation,
JTAG interface and Spy-Bi-Wire are used to communicate with a desktop computer when
downloading a program and for debugging.

114
• The main blocks are linked by the memory address bus (MAB) and memory data
bus (MDB).
• These devices have flash memory, 1KB in the F2003 or 2KB in the F2013, and 128 bytes of
RAM.
• Six blocks are shown for peripheral functions (there are many more in larger devices). All
MSP430s include input/output ports, Timer_A, and a watchdog timer, although the details differ.
The universal serial interface (USI) and sigma–delta analog-to-digital converter (SD16_A) are
particular features of this device.
• The brownout protection comes into action if the supply voltage drops to a dangerous level.
Most devices include this but not some of the MSP430x1xx family.
• There are ground and power supply connections. Ground is labeled VSS and is taken to define
0V. The supply connection is VCC. For many years, the standard for logic was VCC =+5V but
most devices now work from lower voltages and a range of 1.8–3.6V is specified for the F2013.
The performance of the device depends on VCC. For example, it is unable to program the flash

115
memory if VCC < 2.2V and the maximum clock frequency of 16MHz is available only if VCC ≥
3.3V. TI uses a quaint notation for the power connections. The S stands for the source of a field-
effect transistor, while the C stands for the collector of a bipolar junction transistor, a quite
different device. The MSP430, like most modern integrated circuits, is built using
complementary metal–oxide–silicon (CMOS) technology and field-effect transistors. I doubt if it
contains any bipolar junction transistors except possibly in some of the analog peripherals.
There is only one pair of address and data buses, as expected with a von Neumann architecture.
Some addresses must therefore point to RAM and some to flash, so it is a good idea to explore
the memory map next.
BOARD FEATURES:
• MCU: MSP430FG4619 with 120K Bytes Program Flash, 256 Bytes data Flash, 4K Bytes
RAM
• NOKIA 6610 LCD 128x128 pixels 12 bit color LCD with backlight
• Joystick with 4 directions and push button function
• two buttons
• SD/MMC card connector
• MMA7620 3 axis accelerometer
• IrDA transceiver
• UEXT connector which allow other Olimex's modules to be connected like: MOD-MP3, MOD-
NRF24L01, etc.
• JTAG connector
• 32 768 Hz oscillator crystal
• 8Mhz crystal oscillator
• power supply voltage regulators and filtering capacitor
• extension headers for all uC pins
• Battery holder for 2 x 1.5 V “AA” batteries
• PCB: FR-4, 1.5 mm (0,062"), soldermask, white silkscreen component print
• Dimensions: 81.20 x 62.48 mm (3.20 x 2.46")

PROCESSOR FEATURES:
MSP430-4619LCD board use mixed signal microcontroller MSP430FG4619 from Texas
Instruments, with these features: −

116
Low Supply-Voltage Range, 1.8 V to 3.6 V
− Ultralow-Power Consumption:
− Active Mode: 350 μA at 1 MHz, 2.2 V
− Standby Mode: 1.1 μA
− Off Mode (RAM Retention): 0.3 μA
− Five Power Saving Modes
− Wake-Up From Standby Mode in less than 6 μs
− 16-Bit RISC Architecture, Extended Memory, 125-ns Instruction Cycle Time
− Three Channel Internal DMA
− 12-Bit A/D Converter With Internal Reference, Sample-and-Hold and Autoscan Feature
− Three Configurable Operational Amplifiers
− Dual 12-Bit D/A Converters With Synchronization
− 16-Bit Timer_A With Three Capture/Compare Registers
− 16-Bit Timer_B With Seven Capture/Compare-With-Shadow Registers
− On-Chip Comparator
− Supply Voltage Supervisor/Monitor With Programmable Level Detection
− Serial Communication Interface (USART1), Select Asynchronous UART or Synchronous SPI
by Software − Universal Serial Communication Interface
− Enhanced UART supporting auto
-baudrate detection
− IrDA Encoder and Decoder
− Synchronous SPI
− I2CTM − Serial Onboard Programming, No External Programming Voltage Needed
Programmable Code Protection by Security Fuse
− Brownout Detector
− Basic Timer with Real Time Clock Feature
− Integrated LCD Driver up to 160 Segments With Regulated Charge Pump
− 120KB+256B Flash Memory
− 4KB RAM

117
ARCHITECTURE
Introduction The types of devices such as microprocessor, microcontroller, processor, digital
signal processor (DSP), amongst others, in a certain manner, are related to the same device – the
ASIC (Application Specific Integrated Circuit). Each processing device executes instructions,
following a determined program applied to the inputs and shares architectural characteristics
developed from the first microprocessors created in 1971. In the three decades after the
development of the first microprocessor, huge developments and innovations have been made in
this engineering field. Any of the terms used at the beginning of this section are correct to define
a microprocessor, although each one has different characteristics and applications. The definition
of a microcontroller is somewhat difficult due to the constantly changing nature of the silicon
industry. What we today consider a microcontroller with medium capabilities is several orders of
magnitude more powerful, than the computer used on the first space missions. Nevertheless,
some generalizations can be made as to what characterizes a microcontroller. Typically,
microcontrollers are selected for embedded systems projects, i.e., control systems with a limited
number of inputs and outputs where the controller is embedded into the system. The
programmable SoC (system-on-chip) concept started in 1972 with the 4-bit TMS1000
microcomputer developed by Texas Instruments (TI), and in those days it was ideal for
applications such as calculators and ovens. This term was changed to Microcontroller Unit
(MCU), which was more descriptive of a typical application. Nowadays, MCUs are at the heart
of many physical systems, with higher levels of integration and processing power at lower power
consumption.
The following list presents several qualities that define a microcontroller:
Cost: Usually, the microcontrollers are high-volume, low cost devices;
Clock frequency: Compared with other devices (microprocessors and DSPs), microcontrollers
use a low clock frequency. Microcontrollers today can run up to 100 MHz/ 100 Million
Instructions Per Second (MIPS)
Power consumption: orders of magnitude lower than their DSP and MPU cousins; Bits: 4 bits
(older devices) to 32 bits devices;
Memory: Limited available memory, usually less than 1 MByte; Input/Output (I/O): Low to
high (8-150) pin-out count.
Main characteristics of a MSP430 microcontroller

118
Although there are variants in devices in the family, a MSP430 microcontroller can be
characterized by: Low power consumption:
 A for RAM data retention;
  A for real time clock mode operation;
 0.8  A/MIPS at active operation. 250 
Low operation voltage (from 1.8 V to 3.6 V).
1. 1 < s clock start-up.1
2. < 50 nA port leakage. Zero-power Brown-Out Reset (BOR).
3. On-chip analogue devices:
 10/12/16-bit Analogue-to-Digital Converter (ADC);
 12-bit dual Digital-to-Analogue Converter (DAC);
 Comparator-gated timers; Operational Amplifiers (OP Amps);
 Supply Voltage Supervisor (SVS).
16 bit RISC CPU:
 Instructions processing on either bits, bytes or words;
 Compact core design reduces power consumption and cost;
 Compiler efficient;
 27 core instructions;
 7 addressing modes;
 Extensive vectored-interrupt capability.
Flexibility:
 Up to 256 kB In-System Programmable (ISP) Flash;
 Up to 100 pin options;
 USART, I2C, Timers;
 LCD driver;
 Embedded emulation
The microcontroller’s performance is directly related to the 16-bit data bus, the 7 addressing
modes and the reduced instructions set, which allows a shorter, denser programming code for
fast execution. These microcontroller families share a 16-bit CPU (Central Processing Unit) core,
RISC1 type, intelligent peripherals, and flexible clock system that interconnects using a Von
Neumann2 common memory address bus (MAB) and memory data bus (MDB) architecture.

119
Figure 4-2. MSP430 architecture.

Address space
All memory, including RAM, Flash/ROM, information memory, special function
registers (SFRs), and peripheral registers are mapped into a single, contiguous address space as
shown in Figure 4−3. Note: See the device-specific datasheets for specific memory maps. Code
access is always performed on even addresses. Data can be accessed as bytes or words.
The MSP430 is available with either Flash or ROM memory types. The memory type is
identified by the letter immediately following “MSP430” in the part numbers. Flash devices:
Identified by the letter “F” in the part numbers, having the advantage that the code space can be
erased and reprogrammed. ROM devices: Identified by the letter “C” in the part numbers. They
have the advantage of being very inexpensive because they are shipped pre-programmed, which
is the best solution for high-volume designs.
Figure 4-3. Memory Map.

120
For all devices, each memory location is formed by 1 data byte. The CPU is capable of
addressing data values either as bytes (8 bits) or words (16 bits). Words are always addressed at
an even address, which contain the least significant byte, followed by the next odd address,
which contains the most significant byte. For 8-bit operations, the data can be accessed from
either odd or even addresses, but for 16-bit operations, the data values can only be accessed from
even addresses.
Interrupt vector table
The interrupt vector table is mapped at the very end of memory space (upper 16 words of
Flash/ROM), in locations 0FFE0h through to 0FFFEh (see the device-specific datasheets). The
priority of the interrupt vector increases with the word address.

121
Flash/ROM
The start address of Flash/ROM depends on the amount of Flash/ROM present on the device.
The start address varies between 01100h (60k devices) to 0F800h (2k devices) and always runs

122
to the end of the address space at location 0FFFFh. Flash can be used for both code and data.
Word or byte tables can also be stored and read by the program from Flash/ROM. All code,
tables, and hard-coded constants reside in this memory space.
Information memory (Flash devices only)
The MSP430 flash devices contain an address space for information memory. It is like an
onboard EEPROM, where variables needed for the next power up can be stored during power
down. It can also be used as code memory. Flash memory may be written one byte or word at a
time, but must be erased in segments. The information memory is divided into two 128-byte
segments. The first of these segments is located at addresses 01000h through to 0107Fh
(Segment B), and the second is at address 01080h through to 010FFh (Segment A). This is the
case in 4xx devices. It is 256 bytes (4 segments of 64 bytes each) in 2xx devices.
Boot memory (Flash devices only)
The MSP430 flash devices contain an address space for boot memory, located between addresses
0C00h through to 0FFFh. The “bootstrap loader” is located in this memory space, which is an
external interface that can be used to program the flash memory in addition to the JTAG. This
memory region is not accessible by other applications, so it cannot be overwritten accidentally.
The bootstrap loader performs some of the same functions as the JTAG interface (excepting the
security fuse programming), using the TI data structure protocol for UART communication at a
fixed data rate of 9600 baud.
RAM RAM always starts at address 0200h. The end address of RAM depends on the amount of
RAM present on the device. RAM is used for both code and data.
Peripheral Modules
Peripheral modules consist of all on-chip peripheral registers that are mapped into the address
space. These modules can be accessed with byte or word instructions, depending if the peripheral
module is 8-bit or 16-bit respectively. The 16-bit peripheral modules are located in the address
space from addresses 0100 through to 01FFh and the 8-bit peripheral modules are mapped into
memory from addresses 0010h through to 00FFh.
Special Function Registers (SFRs)
Some peripheral functions are mapped into memory with special dedicated functions. The
Special Function Registers (SFRs) are located at memory addresses from 0000h to 000Fh, and
are the specific registers for:

123
Interrupt enables (locations 0000h and 0001h);
Interrupt flags (locations 0002h and 0003h);
Enable flags (locations 0004h and 0005h);
SFRs must be accessed using byte instructions only. See the device specific data sheets for the
applicable SFR bits.
Central Processing Unit (MSP430 CPU)
The RISC type architecture of the CPU is based on a short instruction set (27 instructions),
interconnected by a 3-stage instruction pipeline for instruction decoding. The CPU has a 16-bit
ALU, four dedicated registers and twelve working registers, which makes the MSP430 a high
performance microcontroller suitable for low power applications. The addition of twelve
working general purpose registers saves CPU cycles by allowing the storage of frequently used
values and variables instead of using RAM. The orthogonal instruction set allows the use of any
addressing mode for any instruction, which makes programming clear and consistent, with few
exceptions, increasing the compiler efficiency for high-level languages such as C.
Figure 4-4. MSP430 CPU block diagram

124
125
Arithmetic Logic Unit (ALU)
The MSP430 CPU includes an arithmetic logic unit (ALU) that handles addition, subtraction,
comparison and logical (AND, OR, XOR) operations. ALU operations can affect the overflow,
zero, negative, and carry flags in the status register.
MSP430 CPU registers
The CPU incorporates sixteen 16-bit registers:
Four registers (R0, R1, R2 and R3) have dedicated functions;
There are 12 working registers (R4 to R15) for general use.
R0: Program Counter (PC)
The 16-bit Program Counter (PC/R0) points to the next instruction to be read from memory and
executed by the CPU. The Program counter is implemented by the number of bytes used by the
instruction (2, 4, or 6 bytes, always even). It is important to remember that the PC is aligned at
even addresses, because the instructions are 16 bits, even though the individual memory
addresses contain 8-bit values.
R1: Stack Pointer (SP)
The Stack Pointer (SP/R1) is located in R1. 1st: stack can be used by user to store data for later
use (instructions: store by PUSH, retrieve by POP); 2nd: stack can be used by user or by
compiler for subroutine parameters (PUSH, POP in calling routine; addressed via offset
calculation on stack pointer (SP) in called subroutine); 3rd: used by subroutine calls to store the
program counter value for return at subroutine's end (RET); 4th: used by interrupt - system stores
the actual PC value first, then the actual status register content (on top of stack) on return from
interrupt (RETI) the system get the same status as just before the interrupt happened (as long as
none has changed the value on TOS) and the same program counter value from stack.
R2: Status Register (SR)
The Status Register (SR/R2) stores the state and control bits. The system flags are changed
automatically by the CPU depending on the result of an operation in a register. The reserved bits
of the SR are used to support the constants generator. See the device-specific data sheets for
more details.

126
R2/R3: Constant Generator Registers (CG1/CG2)
Depending of the source-register addressing modes (As) value, six commonly used constants can
be generated without a code word or code memory access to retrieve them. This is a very
powerful feature, which allows the implementation of emulated instructions, for example, instead
of implementing a core instruction for an increment, the constant generator is used.

R4 - R15: General–Purpose Registers


These general-purpose registers are used to store data values, address pointers, or index values
and can be accessed with byte or word instructions.
Central Processing Unit (MSP430X CPU)
Main features of the MSP430X CPU architecture

127
The MSP430X CPU extends the addressing capabilities of the MSP430 family beyond 64 kB to
1 MB. To achieve this, there are some changes to the addressing modes and two new types of
instructions. One type of new instructions allows access to the entire address space, and the other
is designed for address calculations. The MSP430X CPU address bus is 20 bits, but the data bus
is still 16 bits. The CPU supports 8-bit, 16-bit and 20-bit memory accesses. Despite these
changes, the MSP430X CPU remains compatible with the MSP430 CPU, having a similar
number of registers. A block diagram of the MSP430X CPU is shown in the figure below:
Figure 4-5. MSP430X CPU block diagram.

128
Although the MSP430X CPU structure is similar to that of the MSP430 CPU, there are some
differences that will now be discussed. With the exception of the status register SR, all
MSP430X registers are 20 bits. The CPU can now process 20-bit or 16-bit data.
MSP430X CPU registers

129
R0 (PC) - Program Counter
Has the same function as the MSP430 CPU, although now it has 20 bits.
R1 (SP) - Stack Pointer
Has the same function as the MSP430 CPU, although now it has 20 bits.
R2 (SR) - Status Register
Has the same function as the MSP430 CPU, but still only has 16 bits.
Addressing modes
The MSP430 supports seven addressing modes for the source operand and four addressing
modes for the destination operand (see Table 4-5). The following sections describe each of the
addressing modes, with a brief description, an example and the number of CPU clock cycles
required for an instruction, depending on the instruction format and the addressing modes used.

130
Register Mode
Register mode operations work directly on the processor registers, R4 through R15, or on special
function registers, such as the program counter or status register. They are very efficient in terms
of both instruction speed and code space.
Description: Register contents are operands.
Source mode bits: As = 00 (source register defined in the opcode).

131
Destination mode bit: Ad=0 (destination register defined in the opcode).
Syntax: Rn. Length: One or two words.
Comment: Valid for source and destination.
Example 1: Move (copy) the contents of source (register R4) to destination (register R5).
Register R4 is not affected.
Before operation: R4=A002h R5=F50Ah PC = PCpos
Operation: MOV R4, R5
After operation: R4=A002h R5=A002h PC = PCpos + 2
The first operand is in register mode and depending on the second operand mode, the cycles
required to complete an instruction will differ. Table 4-7 shows the cycles required to complete
an instruction, depending on the second operand mode.

Indexed mode
The Indexed mode commands are formatted as X(Rn), where X is a constant and Rn is one of the
CPU registers. The absolute memory location X+Rn is addressed. Indexed mode addressing is
useful for applications such as lookup tables.
Description: (Rn + X) points to the operand. X is stored in the next word.
Source mode bits: As = 01 (memory location is defined by the word immediately following the
opcode).
Destination mode bit: Ad=1 (memory location is defined by the word immediately following the
opcode).

132
Syntax: X(Rn).
Length: Two or three words.
Comment: Valid for source and destination.
Example 2: Move (copy) the contents at source address (F000h + R5) to destination (register
R4).
Before operation: R4=A002h R5=050Ah Loc:0xF50A=0123h
Operation: MOV F000h(R5), R4
After operation: R4=0123h R5=050Ah Loc:0xF50A=0123h

Symbolic mode
Symbolic mode allows the assignment of labels to fixed memory locations, so that those
locations can be addressed. This is useful for the development of embedded programs.
Description: (PC + X) points to the operand. X is stored in the next word. Indexed mode X(PC)
is used.
Source mode bits: As = 01 (memory location is defined by the word immediately following the
opcode).
Destination mode bit: Ad=1 (memory location is defined by the word immediately following the
opcode).
Syntax: ADDR.
Length: Two or three words.
Comment: Valid for source and destination.
Example 3: Move the content of source address XPT (x pointer) to the destination address YPT
(y pointer).

133
Before operation: XPT=A002h Location YPT=050Ah
Operation: MOV XPT, YPT
After operation: XPT= A002h Location YPT=A002h

Absolute mode
Similar to Symbolic mode, with the difference that the label is preceded by “&”.
Description: The word following the instruction contains the absolute address. X is stored in the
next word. Indexed mode X(SR) is used.
Source mode bits: As = 01 (memory location is defined by the word immediately following the
opcode).
Destination mode bit: Ad=1 (memory location is defined by the word immediately following the
opcode).
Syntax: &ADDR.
Length: Two or three words.
Comment: Valid for source and destination.
Example 4: Move the content of source address XPT to the destination address YPT.
Before operation: Location XPT=A002h Location YPT=050Ah
Operation: MOV &XPT, &YPT
After operation: Location XPT= A002h Location YPT=A002h

134
Indirect register mode
The data word addressed is located in the memory location pointed to by Rn. Indirect mode is
not valid for destination operands, but can be emulated with the indexed mode format 0(Rn).
Description: Rn is used as a pointer to the operand.
Source mode bits: As = 10.
Syntax: @Rn.
Length: One or two words.
Comment: Valid only for source operand. The substitute for destination operand is 0(Rn).
Example 5: Move the contents of the source address (contents of R4) to the destination (register
R5). Register R4 is not modified.
Before operation: R4=A002h R5=050Ah Loc:0xA002=0123h
Operation: MOV @(R4), R5
After operation: R4= A002h R5=0123h Loc:0xA002=0123h

135
Indirect auto increment mode
Similar to indirect register mode, but with indirect auto increment mode, the operand is
incremented as part of the instruction. The format for operands is @Rn+. This is useful for
working on blocks of data.
Description: Rn is used as a pointer to the operand. Rn is incremented afterwards by 1 for byte
instructions and by 2 for word instructions.
Source mode bits: As = 11.
Syntax: @Rn+.
Length: One or two words.
Comment: Valid only for source operand. The substitute for destination operand is 0(Rn) plus
second instruction INCD Rn.
Example 6: Move the contents of the source address (contents of R4) to the destination (register
R5), then increment the value in register R4 to point to the next word.
Before operation: R4=A002h R5=050Ah Loc:0xA002=0123h
Operation: MOV @R4+, R5
After operation: R4= A004h R5=0123h Loc:0xA002=0123h

Immediate mode
Immediate mode is used to assign constant values to registers or memory locations.
Description: The word following the instruction contains the immediate constant N. Indirect
autoincrement mode @PC+ is used.

136
Source mode bits: As = 11.
Syntax: #N.
Length: Two or three words. It is one word less if a constant in CG1 or CG2 can be used.
Comment: Valid only for source operand.
Example 7: Move the immediate constant E2h to the destination (register R5).
Before operation: R4=A002h R5=050Ah
Operation: MOV #E2h, R5
After operation: R4= A002h R5=00E2h

Instruction Set
The instructions are thoroughly documented in the section “RISC 16-Bit CPU” of the family
user’s guides. The MSP430 has 27 native instructions, and a further 24 emulated instructions are
defined to make life easier for the programmer. These include common operations such as
“clear,” which is implemented as an ordinary move with a value of 0 provided by the constant
generator. I list all instructions for completeness but concentrate on the unusual features and
traps for the unwary. The instruction set is orthogonal with few exceptions, meaning that all
addressing modes can be used with all instructions and registers. I show the .w form for
operations that can use either bytes or words. Aside: It sounds as though the MSP430 has fewer
instructions than the PIC16 with 35, but trivial comparisons of radically different processors are
always misleading. It might be more accurate to say that the PIC has 28 instructions with up to
three addressing modes. For example, the operand for arithmetic and logic instructions can be a

137
literal value, taken from a register whose address is given explicitly, or in a register whose
address is specified indirectly in FSR.
Movement Instructions
There is only the one mov instruction to move data. It can address all of memory as either source
or destination, including both registers in the CPU and the whole memory map. This is an
excellent feature. Some processors have distinct instructions for loading a CPU register from
memory, storing it to memory, and memory-to-memory moves if these are available at all:

mov.w src ,dst ; move (copy) dst = src

Note the order of the operands, which is the opposite of the equivalent statement in C (and some
other assembly languages).
Peculiarity: The status bits are not affected by mov. Strings in C end with the null character \0
and other lists are often terminated by 0, so it would be helpful to detect this. The Z flag is
affected by the move itself in many processors but an explicit test must be used in the MSP430.
Stack Operations
These push data onto the stack and pop them off, as described in the section “Stack Pointer (SP)”
on page 120:
push.w src ; push data onto stack *--SP = src
pop.w dst ; pop data off stack dst = *SP++ emulated
The SP is fixed to be even, so a word of stack space is always consumed, even if only a byte is
added. The pop operation is emulated using postincrement addressing but push requires a special
instruction because predecrement addressing is not available.
Arithmetic and Logic Instructions with Two Operands
Binary Arithmetic Instructions with Two Operands
These are fairly standard. The carry bit should be interpreted as “not borrow” for subtraction:

138
The compare operation cmp is the same as subtraction sub except that only the bits in SR are
affected; the result is not written back to the destination. There are many examples of operations
on more than one word with the carry/borrow bit in Section 5.1 of Application Reports (slaa024).
Maxfield and Brown [37] give an entertaining account of binary arithmetic.
Arithmetic Instructions with One Operand
All these are emulated, which means that the operand is always a destination:

The test operation is the special case of comparison with 0. In many processors the clear
operation differs from a move with the value 0 because a move sets the flags but a clear does not.
This does not apply to the MSP430 because a move does not set the flags.
Decimal Arithmetic
These instructions are used when operands are binary-coded decimal (BCD) rather than ordinary
binary values. This means that the value of each nibble is restricted to the range of unsigned,
decimal integers 0–9 instead of the full hexadecimal range 0–F. BCD is often used for values to
be displayed in decimal form because it saves having to convert the binary value to a set of
decimal digits. This is useful in a clock, for instance, as we see in the section “Simple
Applications of the LCD” on page 264. Maxfield has several articles explaining why BCD is
important and how to use it—even signed BCD [60, 63]:

There is only one native instruction for decimal arithmetic, dadd. This adds its source plus the
carry bit decimally to its destination. The result is a BCD number provided that the operands
were valid BCD numbers themselves. Some processors have a “decimal adjust” instruction

139
instead, which converts the value in a register from binary to BCD. The emulated instruction
dadc adds only the carry bit decimally to the destination. The CPU itself provides no other
operations on nibbles, but there are routines for converting between BCD and binary numbers in
Section 5.5 of Application Reports (slaa024) and I show an example in the section “Conversion
from Binary to Binary-Coded Decimal” on page 270. Peculiarity: The mnemonic dadd is
misleading: It would better have been called daddc for “decimal add with carry.” Make sure that
you set or clear the carry bit before using dadd unless the carry has been determined by a
previous operation.
Logic Instructions with Two Operands
These are not quite the same as in many other processors:

The MSP430 has the usual and and exclusive-OR xor instructions but not an explicit inclusive-
OR. The and and bitwise test operations are identical except that bit is only a test and does not
change its destination.
Peculiarity: The Z bit is affected in the usual way by these operations and the carry bit is given
by C = ˜ Z. The idea of this is that the carry bit can subsequently be rotated into another register
to ease serial–parallel conversion.
The bit set bis and bit clear bic instructions are used with masks to set and clear bits. The bis
operation is very similar to inclusive-OR and bic mask is likewise related to and ˜ mask.
Peculiarity: The bis and bic operations do not affect the status bits. Therefore bis is not quite a
substitute for the usual inclusive-OR, which would be expected to affect SR. This is not a serious
loss because the effect of an inclusive-OR operation on the status bits is largely predictable. Bit
operations are called read–modify–write operations because the CPU cannot operate on bits
individually: It must read the register into the ALU, perform the operation, and write the result
back. This can have unwanted side effects with some special registers. One example is registers
associated with interrupts, where a read may automatically clear flags. Trouble can also arise
with input/output ports in some processors but this is not a problem on the MSP430 with its
separate input and output registers.

140
Logic Instructions with One Operand
There is only one of these, the invert inv instruction, also known as ones complement, which
changes all bits of 0 to 1 and those of 1 to 0:
inv.w dst ; invert bits dst = ˜dst emulated
It is emulated using xor and inherits its peculiarity C = ˜ Z. Its operand is a destination. It is not
the same as changing the sign of a number, which is the twos complement.
Byte Manipulation
These instructions do not need a suffix because the size of the operands is fixed:
swpb src ; swap upper and lower bytes (word only)
sxt src ; extend sign of lower byte (word only)
The swap bytes instruction swpb swaps the two bytes in a word; there is no corresponding swap
nibbles for the nibbles in a byte. The sign extend instruction sxt is used to convert a signed byte
into a signed word. It copies the value of bit 7, which gives the sign of the lower byte, into bits
8–15 and gives flags C = ˜ Z. The opposite operation, truncation from a word to a byte, can be
done with mov.b. Multiplication, if present in hardware at all, is performed by a peripheral—it is
not implemented in the ALU and does not appear in the instruction set. There are routines for
methods are given in the application note Efficient Multiplication and Division Using MSP430
(slaa329).
Operations on Bits in Status Register
There is a set of emulated instructions to set or clear the four lowest bits in the status register,
those that can be masked using the constant generator: multiplication in software in Section 5.1
of Application Reports (slaa024). Further

The carry bit should be set or cleared before instructions that take it as input unless it is a result
of a previous operation. This applies to adc, addc, sbc, subc, dadc, dadd (particularly easy to
forget because of the mnemonic), and the rotations rlc and rrc. The GIE flag affects only
maskable (general) interrupts; see the section “Interrupts” on page 186.

141
Shift and Rotate Instructions
Processors often offer three types of shifts and rotations as illustrated in Figure 5.4, although the
treatment of the carry bit varies. They differ in the treatment of the bits that are shifted out of and
into the register:
Logical shift inserts zeroes for both right and left shifts.
Arithmetic shift inserts zeroes for left shifts but the most significant bit, which carries the sign,
is replicated for right shifts.

Rotation does not introduce or lose any bits; bits that are moved out of one end of the register
are passed around to the other.
Usually the carry bit is included in rotations and it may gain the bit that is shifted out by
arithmetic or logical shifts.
The MSP430 has arithmetic shifts and rotations, all of which use the carry bit. The right-shifts
are native instructions but the left shifts are emulated, so the left- and right-shifts have different
addressing modes available:

Peculiarities: The mnemonics for the arithmetic shifts imply that they are rotations, which is
misleading. There are no logical shifts in the MSP430 but they have been added to the
MSP430X. A logical shift left is the same as an arithmetic shift left so there is no problem there.
A logical shift right can be emulated by first clearing the carry bit and making a rotation right.
The rotation operation is not available in C so assembly language may be needed if this
instruction is critical. Shifts in C are always logical for unsigned values but the nature of shifts
for signed values is undefined. They are arithmetic in EW430 to match the instruction set.

142
Multiword shifts can be constructed using the carry bit in much the same way as multiword
arithmetic.
Flow of Control
Subroutines, Interrupts, and Branches
These are mainly straightforward but there is a tricky point about addresses:

Peculiarity: Both br and call can use the full range of addressing modes for a source. The most
common elementary use of call is for a subroutine that begins at a particular label. This label is
translated by the assembler to the address of the first instruction in the subroutine: direct
addressing. This is the value that should be loaded into the PC to call the subroutine and is
therefore like immediate data. It must consequently be given the prefix # like any other
immediate value. For example, call #DelayTenths. This is very easy to forget.We used this in the
section “Automatic Control: Use of Subroutines” on page 99 and I will remind you of this pitfall
again. The behavior is easier to understand with br, which is emulated. The instruction br label is
translated into mov.w label,PC. This means that label is used as an absolute address so the
contents of the word whose address is label are fetched and loaded into PC. It is more likely that
we want to load the value label itself into the PC, which needs mov.w #label,PC. The call
instruction must be handled in the same way. There is no problem with the jump instructions
because they use offsets rather than full addresses and the compiler or assembler calculates these
automatically. The good side to this is that it is easy to select a branch or subroutine from a table
by using indexed, indirect, or even autoincrement addressing. The interrupt handling for
Timer_A is designed with this in mind. Be sure that subroutines end with ret and interrupt
service routines end with reti; the extra letter is crucial. The MSP430X uses calla and reta for
subroutines. The standard no-operation instruction nop is emulated to waste one cycle of the
processor. There are further suggestions in the family user’s guides for instructions to use more
cycles but their side effects may need care.
Jumps, Unconditional and Conditional
The unconditional jump instruction is less tricky:
jmp label ; unconditional jump

143
The target is a straightforward label: It does not have the peculiarity (or versatility) of br. The
difference between them is that:
jmp fits in a single word, including the offset, but its range is limited to about ±1KB from the
current location.
br can go anywhere in the address space and use any addressing mode but is slower and requires
an extra word of program storage.
The nomenclature varies between manufacturers; jump and branch have the opposite meaning in
Freescale processors, for instance. The symbol $ stands for the current value of the program
counter in the assembler so jmp $ is a concise way of getting an empty, infinite loop.
The conditional jumps are the “decision-making” instructions and test certain bits or
combinations in the status register. It is not possible to jump according to the value of any other
bits in SR or those in any other register. Typically a bit test instruction bit is used to detect the
bit(s) of interest and set up the flags in SR before a jump. Many branches have two names to
reflect different usage. For example, it is clearer to use jc if the carry bit is used explicitly—after
a rotation, for instance—but jhs is more appropriate after a comparison:

Both mnemonics jl and jlt are used. It is up to the programmer to select the correct instruction.
For example, suppose that two bytes contain 0x99 and 0x01. They are related by 0x99 > 0x01 if
the values are unsigned but 0x99 < 0x01 if they are signed, twos complement numbers because

144
0x99 is the representation of −0x67 Peculiarities: There are tests for the conditions < and ≥ but
not for ≤ nor >. It may be possible to choose the source and destination in a comparison to avoid
this problem. Unfortunately the asymmetric addressing modes often prevent this, particularly if
one value is immediate. Two tests may then be necessary.
Instruction Timing
The number of MCLK cycles required for most instructions is limited by access to memory. This
is a typical feature of a RISC-like CPU with a von Neumann architecture and also applies to the
ARM7, for instance. Values for typical instructions are listed in Table 5.1 but there are several
exceptions, including instructions that change the flow of control and those where the destination
is PC. The general principle for Format I instructions (two operands) is as follows. Most of these
must read the instruction and two operands from memory and write the result back. The duration
is set by the modes used to address memory for the operands.
 It takes one cycle to fetch the instruction word itself. This is all if both source and
destination are in CPU registers. Values from the constant generators are effectively in
registers.
 One more cycle is needed to fetch the source if it is given indirectly as @Rn or @Rn+, in
which case the address is already in the CPU. This includes immediate data.
 Alternatively, two more cycles are needed if one of the indexed modes is used. The first
is to fetch the base address, which is added to the value in a CPU register to get the
address of the source. A second cycle is necessary to fetch the operand itself. This
includes absolute and symbolic modes.

Two more cycles are needed to fetch the destination in the same way if it is indexed.
 A final cycle is needed to write the destination back to memory if required; no allowance
is needed for a register in the CPU.

145
These are illustrated in Figure 5.5. It is amusing that no dedicated cycles are needed for the
computation itself. A similar principle applies to the arithmetic operations with a single operand
but most instructions with Format II change the flow of control and have individual timings.
Jumps always use two cycles, whether conditional jumps are taken or not. There is no difference
in the timing between bytes and words so it is pointless to squeeze variables into bytes in the
hope of gaining speed. Of course it is an equally bad idea to waste memory by storing large
tables as words when the elements would fit into bytes.

A few instructions have been speeded up in the MSP430X. These include mov, which does not
need to fetch its destination, and bit and tst, which do not produce a result that needs to be
written back. The number of cycles for these instructions with addressing modes as in mov.w
Rs,D(Rd) has been reduced from four to three. The interfaces to subroutines and interrupt service
routines have also been made faster.

146
Machine Code
Occasionally you may need to decode the binary machine code to deduce the instruction to be
executed. This is an unfulfilling activity and fortunately is rarely needed with modern debuggers.
The layout of the bits within a Format I instruction (two operands) instruction is shown in
Figure 5.6, taken from the family user’s guide. These are the individual fields:
 opcode (4 bits) is the operation code. The highest 12 values are used for Format I
instructions, the remainder for jumps and Format II.
 S-Reg and D-Reg (4 bits each) specify the CPU registers associated with the source and
destination; the registers either contain the operands themselves or their contents are used
to form the addresses.
 As (2 bits) gives the mode of addressing for the source, which has four basic modes.
 Ad (1 bit) similarly gives mode of addressing for the destination, which has only two
basic modes.
 B/W (1 bit) chooses whether the operand is a byte (1) or a word (0).
Here is a trivial example of a move from register to register with the resulting machine
code:
mov.w R5 ,R6 ; 4506

The instruction can be broken into its fields of opcode = 4, S-reg = 5, Ad = 0, B/W = 0,
As = 0, D-reg = 6. What do these mean?
 The opcode of 4 represents a move.
 The bit B/W = 0 shows that the operand is a word.
 The addressing mode for the source is As = 0, which is register. The register is S-reg = 5,
which is R5 as expected.
 Similarly, the addressing mode for the destination is Ad = 0, which again means register.
The register is D-reg = 6 = R6.
Here is an addition rather than a move:
add.w R5 ,R6 ; 5506
The machine code is identical except for the opcode, which is now 5 rather than 4. The
specification of the operands is unchanged. This is because of the orthogonality: All instructions
use the same addressing modes. Let us move an immediate value instead of a register:

147
mov.w #5,R6 ; 4036 0005

Now there are two words. The fields of the instruction are opcode = 4, S-reg = 0, Ad = 0, B/W =
0, As = 3 = 11b, D-reg = 6. The difference is in the specification of the source, which means
autoincrement. The register is Sreg = 0, which is the PC. Autoincrement addressing on the PC is
the way in which immediate values are implemented. The value itself is contained in the second
word.
Next look at a value of 4 instead, which can be supplied by the constant generator. I use a byte
rather than a word for a change:

mov.b #4,R6 ; 4266

This breaks into opcode = 4, S-reg = 2, Ad = 0, B/W = 1, As = 2 = 10b, D-reg = 6. The B/W bit
flags a byte rather than a word. The source appears to have indirect register mode on
R2/SR/CG1, but this is translated by the constant generator into a value of 0x0004, as required.
Only a single word is needed for the instruction. Next, let us return to the first three active lines
of Listing 4.3, which were reviewed in the section “Machine Code”

These are a bit more complicated because the source is given as an absolute address rather than a
register. The first instruction breaks into opcode = 4, S-reg = 0, Ad = 1, B/W = 0, As = 3 = 11b,
D-reg = 2. The source has autoincrement addressing on PC, which means an immediate value.
The destination has Ad = 1, which means indexed. The register is Dreg = 0010b = R2/SR/CG1,
which means absolute addressing (the register acts like a base value of 0). The instruction is
followed by words for the immediate value and absolute address. The third line is very similar
but the B/W bit is set to indicate a byte rather than a word. The second line looks rather different
because the constant generator is used to provide the value of 4, as described earlier.
MSP430 Microcontroller Family
Introduction

148
The MSP430 is a 16-bit microcontroller that has a number of special features not commonly
available with other microcontrollers:
 Complete system on-a-chip — includes LCD control, ADC, I/O ports, ROM, RAM, basic
timer, watchdog timer, UART, etc.
 Extremely low power consumption — only 4.2 nW per instruction, typical
 High speed — 300 ns per instruction @ 3.3 MHz clock, in register and register
addressing mode
 RISC structure — 27 core instructions
 Orthogonal architecture (any instruction with any addressing mode)
 Seven addressing modes for the source operand
 Four addressing modes for the destination operand
 Constant generator for the most often used constants (–1, 0, 1, 2, 4, 8)
 Only one external crystal required — a frequency locked loop (FLL) oscillator derives all
internal clocks
 Full real-time capability — stable, nominal system clock frequency is available after
only six clocks when the MSP430 is restored from low-power mode (LPM) 3; — no
waiting for the main crystal to begin oscillation and stabilize
The 27 core instructions combined with these special features make it easy to program the
MSP430 in assembler or in C, and provide exceptional flexibility and functionality. For example,
even with a relatively low instruction count of 27, the MSP430 is capable of emulating almost
the complete instruction set of the legendary DEC PDP-11.
MSP430 Family
The MSP430 family currently consists of three subfamilies:
MSP430C31x
MSP430C32x
MSP430C33x
All three are described in detail in the MSP430 Family Architecture User’s Guide and Module
Library. The hardware features of the different devices are shown in Table 1, Figure 1, Figure 2,
and Figure 3.

149
MSP430C31x

MSP430C32x

150
Figure 1–2. MSP430C32x Block Diagram
MSP430C33x

151
MSP430 Application Operating Modes
MSP430 applications fall into two main classes, depending on the power supply:
 AC power-driven applications such as electricity meters and AC-powered controllers. In
these applications, the microcontroller needs to be active at all times. The low current
consumption of the MSP430 when active (900 A @ 5 V & fC = 1 MHz) puts it well

152
within the typical low-power category now (currently < 40 mA) and in the future as
tolerable current consumption diminishes.
 Battery-powered applications such as gas meters, water flow meters, heat volume
counters, data loggers, and other controller and remote metering tasks. For these
applications, power consumption is the key issue since operation from a single battery for
10 years or longer is often required. The average current drawn by the MSP430 needs to
be in the range of the self discharge current of the battery, approximately 1 A to 3 A.
MSP430 has six operating modes, each with different power requirements. Three of these
modes are important for battery-powered applications:
 Active mode — CPU and other device functions run all the time
 Low power mode 3 (LPM3) — the normal mode for most applications during 99% to
99.9% of the time. This mode is also called done mode or sleep mode
 Low power mode 4 (LPM4) — the mode typically used during storage. This mode is also
called off mode
Active Mode
Active mode is used for calculations, decision-making, I/O functions, and other activities that
require the capabilities of an operating CPU. All of the peripheral functions may be used,
provided that they are enabled. The examples shown in this document use the active mode.
Low Power Mode 3 (LPM3)
LPM3 is the most important mode for battery-powered applications. The CPU is disabled, but
enabled peripherals stay active. The basic timer provides a precise time base. When enabled,
interrupts restore the CPU, switch on MCLK, and start normal operation. Table 1–2 lists the
status of the MSP430 system when in LPM3.

153
Low Power Mode 4 (LPM4)
Low power mode 4 (LPM4) is used if the absolute lowest supply current is necessary or if no
timing is needed or desired (no change of the RAM content is allowed). This is normally the case
for storage preceding or following the calibration process. Table 3 lists the status of the MSP430
system when in LPM4

154
Once the MSP430 is waked from LPM4, the software has to decide if it is necessary to either
enter LPM4 again (if the wake-up was caused by EMI, for example), or to enter one of the other
operating modes. To ensure the correct decision is made, a code can be placed on a port that can
be checked by the MSP430 software. Then, the active mode is entered only if this code is
present. The start-up frequency of the DCO is approximately 500 kHz and may last up to 4
seconds until a stable MCLK frequency is reached. To enter the LPM4 the following code is
necessary:

The exit from LPM4 is principally the same as described for LPM3. Interrupt handler software
has to determine if the CPU stays active or if a return to a low power mode is necessary. When
entering the LPM4 the information in control registers SCFI0 and SCFI1 of the system clock
frequency integrator (SCFI) remains stored. If at this time the ambient temperature is high,
SCFI1 contains a relatively high value to compensate the negative temperature coefficient of the
DCO. If the LPM4 is later exited and the ambient temperature is very low, it is possible that the
resulting DCO frequency, based on the value in SCFI1, will be outside of the oscillator range. It
is therefore a good programming practice to set the SCFI control register to a low value before
entering LPM4.

155
TI's new MSP430F5xx generation allows for more scalability than ever
for MSP430 microcontrollers. The F5xx generation provides a broad
range of performance, memory, price, connectivity, and peripheral
options to suite your applications.

156
MSP430 generations:
There are six general generations of MSP430 processors. In order of development, they were the '3xx
generation, the '1xx generation, the '4xx generation, the '2xx generation, the '5xx generation, and the '6xx
generation. The digit after the generation identifies the model (generally higher model numbers are larger and
more capable), the third digit identifies the amount of memory on board, and the fourth, if present, identifies a
minor model variant. The most common variation is a different on-chip analog-to-digital converter.

The 3xx and 1xx generations were limited to a 16-bit address space. In the later generations this was expanded
to include '430X' instructions that allow a 20-bit address space. As happened with other processor architectures
(e.g. the processor of the PDP-11), extending the addressing range beyond the 16-bit word size introduced
some peculiarities and inefficiencies for programs larger than 64 kBytes.

In the following list, it helps to think of the typical 200 mA·Hr capacity of a CR2032 lithium coin cell as
200,000 μA·Hr, or 22.8 μA·year. Thus, considering only the CPU draw, such a battery could supply a 0.7 μA
current draw for 32 years. (In reality, battery self-discharge would reduce this number.)

The significance of the 'RAM retention' vs the 'real-time clock mode' is that in real time clock mode the CPU
can go to sleep with a clock running which will wake it up at a specific future time. In RAM retention mode,
some external signal is required to wake it, e.g. I/O pin signal or SPI slave receive interrupt.

MSP430x1xx series[edit]
The MSP430x1xx Series is the basic generation without an embedded LCD controller. They are generally
smaller than the '3xx generation. These flash- or ROM-based ultra-low-power MCUs offer 8 MIPS, 1.8–3.6 V
operation, up to 60 KB flash, and a wide range of analog and digital peripherals.

 Power specification overview, as low as:


 0.1 μA RAM retention
 0.7 μA real-time clock mode
 200 μA / MIPS active
 Features fast wake-up from standby mode in less than 6 µs.

 Device parameters
 Flash options: 1–60 KB
 ROM options: 1–16 KB
 RAM options: 128 B–10 KB
 GPIO options: 14, 22, 48 pins
 ADC options: Slope, 10 & 12-bit SAR

157
 Other integrated peripherals: 12-bit DAC, up to 2 16-bit timers, watchdog timer, brown-out
reset, SVS, USART module (UART, SPI), DMA, 16×16 multiplier, Comparator_A,
temperature sensor
MSP430F2xx series:
The MSP430F2xx Series are similar to the '1xx generation, but operate at even lower power, support
up to 16 MHz operation, and have a more accurate (±2%) on-chip clock that makes it easier to
operate without an external crystal. These flash-based ultra-low power devices offer 1.8–3.6 V
operation. Includes the very-low power oscillator (VLO), internal pull-up/pull-down resistors, and
low-pin count options.

 Power specification overview, as low as:


 0.1 μA RAM retention
 0.3 μA standby mode (VLO)
 0.7 μA real-time clock mode
 220 μA / MIPS active
 Feature ultra-fast wake-up from standby mode in less than 1 μs

 Device parameters
 Flash options: 1–120 KB
 RAM options: 128 B – 8 KB
 GPIO options: 10, 11, 16, 24, 32, and 48 pins
 ADC options: Slope, 10 & 12-bit SAR, 16 & 24-bit Sigma Delta
 Other integrated peripherals: operational amplifiers, 12-bit DAC, up to 2 16-bit timers,
watchdog timer, brown-out reset, SVS, USI module (I²C, SPI), USCI module, DMA, 16×16
multiplier, Comparator_A+, temperature sensor
MSP430G2xx series[edit]
The MSP430G2xx Value Series features flash-based Ultra-Low Power MCUs up to 16 MIPS with 1.8–3.6 V
operation. Includes the Very-Low power Oscillator (VLO), internal pull-up/pull-down resistors, and low-pin
count options, at lower prices than the MSP430F2xx series.

 Ultra-Low Power, as low as (@2.2 V):


 0.1 μA RAM retention
 0.4 μA Standby mode (VLO)
 0.7 μA real-time clock mode
 220 μA / MIPS active
 Ultra-Fast Wake-Up From Standby Mode in <1 μs

158
 Device parameters
 Flash options: 0.5–56 KB
 RAM options: 128 B–4 KB
 GPIO options: 10, 16, 24, 32 pins
 ADC options: Slope, 10-bit SAR
 Other integrated peripherals: Capacitive Touch I/O, up to 3 16-bit timers, watchdog timer,
brown-out reset, USI module (I²C, SPI), USCI module, Comparator_A+, Temp sensor
MSP430x3xx series[edit]
The MSP430x3xx Series is the oldest generation, designed for portable instrumentation with an embedded
LCD controller. This also includes a frequency-locked loop oscillator that can automatically synchronize to a
low-speed (32 kHz) crystal. This generation does not support EEPROM memory, only mask ROM and UV-
eraseable and one-time programmable EPROM. Later generations provide only flash memory and mask
ROM options. These devices offer 2.5–5.5 V operation, up to 32 KB ROM.

 Power specification overview, as low as:


 0.1 μA RAM retention
 0.9 μA real-time clock mode
 160 μA / MIPS active
 Features fast wake-up from standby mode in less than 6 µs.

 Device parameters:
 ROM options: 2–32 KB
 RAM options: 512 B–1 KB
 GPIO options: 14, 40 pins
 ADC options: Slope, 14-bit SAR
 Other integrated peripherals: LCD controller, multiplier

MSP430x4xx series[edit]
The MSP430x4xx Series are similar to the '3xx generation, but include an integrated LCD controller, and are
larger and more capable. These flash or ROM based devices offers 8–16 MIPS at 1.8–3.6 V operation, with
FLL, and SVS. Ideal for low power metering and medical applications.

 Power specification overview, as low as:


 0.1 μA RAM retention
 0.7 μA real-time clock mode
 200 μA / MIPS active

159
 Features fast wake-up from standby mode in less than 6 µs.

 Device parameters:
 Flash/ROM options: 4 – 120 KB
 RAM options: 256 B – 8 KB
 GPIO options: 14, 32, 48, 56, 68, 72, 80 pins
 ADC options: Slope, 10 & 12-bit SAR, 16-bit Sigma Delta
 Other integrated peripherals: SCAN_IF, ESP430, 12-bit DAC, Op Amps, RTC, up to 2 16-bit
timers, watchdog timer, basic timer, brown-out reset, SVS, USART module (UART, SPI),
USCI module, LCD Controller, DMA, 16×16 & 32x32 multiplier, Comparator_A,
temperature sensor, 8 MIPS CPU Speed
MSP430x5xx series[edit]
The MSP430x5xx Series are able to run up to 25 MHz, have up to 512 KB flash memory and up to 66 KB
RAM. This flash-based family features low active power consumption with up to 25 MIPS at 1.8–3.6 V
operation (165 uA/MIPS). Includes an innovative power management module for optimal power consumption
and integrated USB.[3]

 Power specification overview, as low as:


 0.1 μA RAM retention
 2.5 μA real-time clock mode
 165 μA / MIPS active
 Features fast wake-up from standby mode in less than 5 µs.

 Device parameters:
 Flash options: up to 512 KB
 RAM options: up to 66 KB
 ADC options: 10 & 12-bit SAR
 GPIO options: 29, 31, 47, 48, 63, 67, 74, 87 pins
 Other integrated peripherals: High resolution PWM, 5 V I/O's, USB, backup battery switch,
up to 4 16-bit timers, watchdog timer, Real-Time Clock, brown-out reset, SVS, USCI
module, DMA, 32x32 multiplier, Comp B, temperature sensor
MSP430x6xx series[edit]
The MSP430x6xx Series are able to run up to 25 MHz, have up to 512 KB flash memory and up to 66 KB
RAM. This flash-based family features low active power consumption with up to 25 MIPS at 1.8–3.6 V
operation (165 uA/MIPS). Includes an innovative power management module for optimal power consumption
and integrated USB.

160
 Power specification overview, as low as:
 0.1 μA RAM retention
 2.5 μA real-time clock mode
 165 μA / MIPS active
 Features fast wake-up from standby mode in less than 5 µs.

 Device parameters:
 Flash options: up to 512 KB
 RAM options: up to 66 KB
 ADC options: 12-bit SAR
 GPIO options: 74 pins
 Other integrated peripherals: USB, LCD, DAC, Comparator_B, DMA, 32x32 multiplier,
power management module (BOR, SVS, SVM, LDO), watchdog timer, RTC, Temp sensor

161
RF SoC (CC430) series[edit]
The RF SoC (CC430) Series provides tight integration between the microcontroller core, peripherals,
software, and RF transceiver. Features <1 GHz RF transceiver, with 1.8 V–3.6 V operation.

 Power specification overview, as low as:


 1 μA RAM retention
 1.7 μA real-time clock mode
 180 μA / MIPS active

 Device parameters:
 Speed options: up to 20 MHz
 Flash options: up to 32 KB
 RAM options: up to 4 KB
 ADC options: 12-bit SAR
 GPIO options: 30 & 44 pins
 Other integrated peripherals: LCD Controller, up to 2 16-bit timers, watchdog timer,
RTC, power management module (BOR, SVS, SVM, LDO), USCI module, DMA,
32x32 multiplier, Comp B, temperature sensor
FRAM series[edit]
The FRAM Series from Texas Instruments provides unified memory with dynamic partitioning and
memory access speeds 100 times faster than flash. FRAM is also capable of zero power state
retention in all power modes, which means that writes are guaranteed, even in the event of a power
loss. With a write endurance of over 100 trillion cycles, EEPROM is no longer required. Active power
consumption at less than 100μA/MHz.

 Power specification overview, as low as:


 320 nA RAM retention
 0.35 μA real-time clock mode
 82 μA / MIPS active

 Device parameters:
 Speed options: 8 to 24 MHz
 FRAM options: 4 to 128 KB
 RAM options: 0.5 to 2 KB
 ADC options: 10 or 12-bit SAR
 GPIO options: 17 to 83 GPIO pins

162
 Other possible integrated peripherals: MPU, up to 6 16-bit timers, watchdog timer,
RTC, power management module (BOR, SVS, SVM, LDO), USCI module, DMA,
multiplier, Comp B, temperature sensor, LCD driver, I2C and UART BSL, Extended
Scan Interface, AES, IR modulation
Low voltage series[edit]
The Low Voltage Series include the MSP430C09x and MSP430L092 parts. These 2 series of low
voltage 16 bit microcontrollers have configurations with two 16-bit timers, an 8-bit analog-to-digital
(A/D) converter, an 8-bit digital-to-analog (D/A) converter, and up to 11 I/O pins. For more
information, see Low Voltage Wiki.

 Power specification overview, as low as:


 1 μA RAM retention
 1.7 μA real-time clock mode
 180 μA / MIPS active

 Device parameters:
 Speed options: 4 MHz
 ROM options: 1–2 kB
 SRAM options: 2 kB
 ADC options: 8-bit SAR
 GPIO options: 11 pins
 Other integrated peripherals: up to 2 16-bit timers, watchdog timer, brown-out reset,
SVS, comparator, temperature sensor

Other MSP430 families[edit]


Additional families within MSP430 include Fixed Function, Automotive, and Extended
Temp parts.Fixed Function: The MSP430BQ1010 16-bit microcontroller is an advanced fixed-
function device that forms the control and communications unit on the receiver side for wireless
power transfer in portable applications. MSP430BQ1010 complies with the Wireless Power
Consortium (WPC) specification. For more information, see Contactless Power.

Automotive: Automotive MSP430 microcontrollers (MCUs) from Texas Instruments (TI) are 16-bit,
RISC-based, mixed-signal processors that are AEC-Q100 qualified and suitable for automotive
applications in environments up to 105 °C ambient temperature. LIN compliant drivers for the
MSP430 MCU provided by IHR GmbH.

Extended Temp: MSP430 devices are very popular in harsh environments such as industrial sensing
for their low power consumption and innovative analog integration. Some harsh environment

163
applications include transportation/automotive, renewable energy, military/space/avionics, mineral
exploration, industrial, and safety & security.

 Device Definitions:
 HT: -55 °C to 150 °C
 EP: Enhanced products -55 °C to 125 °C
 Q1: Automotive Q100 qualified -40 °C to 105 °C
 T: Extended temperature -40 °C to 105 °C applications

Note that when the flash size is over 64K words (128 KBytes), instruction addresses can no longer
be encoded in just two bytes. This change in pointer size causes some incompatibilities with
previous parts.

PART A

1. Explain the concept of system on chip


2. With a neat block diagram explain the working of Air Conditioner as embedded
system
3. With a neat block diagram explain the working of smart phone as embedded
system
4. Give the comparison between MSP 430 and 8051 micro controller
5. Compare various micro controllers with MSP 430

PART B

1. Explain the embedded systems with a neat block diagram


2. Explain the applications of the embedded systems
3. Differentiate between RAM and ROM
4. Discuss the concept of memory mapped I/O
5. What are the architectures of embedded systems and briefly discuss
6. Write about the micro controller MSP 430 block diagram
7. Give the instruction set of MSP 430
8. Design an application based on MSP 430
9. Briefly explain the bock diagram of MSP 430x5x

164
UNIT –IV

TIMERS
Most modern microcontrollers provide a range of timers and the MSP430 is no exception. All
devices contain two types of timer and some have five. Each type of timer module works in
essentially the same way in all devices. Timer_A is identical in almost all MSP430s, for instance,
except that a few have a different number of capture/compare channels.
Watchdog timer: Included in all devices (newer ones have the enhanced watchdog timer+). Its
main function is to protect the system against malfunctions but it can instead be used as an
interval timer if this protection is not needed.
Basic timer1: Present in the MSP430x4xx family only. It provides the clock for the LCD and
acts as an interval timer. Newer devices have the LCD_A controller, which contains its own
clock generator and frees the basic timer from this task.
Real-time clock: In which the basic timer has been extended to provide a real-time clock in the
most recent MSP430x4xx devices.
Timer_A: Provided in all devices. It typically has three channels and is much more versatile
than the simpler timers just listed. Timer_A can handle external inputs and outputs directly to
measure frequency, time-stamp inputs, and drive outputs at precisely specified times, either once
or periodically. There are internal connections to other modules so that it can measure the
duration of a signal from the comparator, for instance. It can also generate interrupts.We used a
few of its capabilities in earlier chapters and most of this chapter is devoted to Timer_A.
Timer_B: Included in larger devices of all families. It is similar to Timer_A with some
extensions that make it more suitable for driving outputs such as pulse-width modulation.
Against this, it lacks a feature of sampling inputs in Timer_A that is useful in communication.
The simplest way to generating a delay is to use a software loop as in the section “Automatic
Control Flashing Light by Software Delay” on page 91. This should be avoided wherever
possible in favor of one of the hardware timers because the timers are more precise and leave the
CPU free for more productive activities. Alternatively, the device can be put into a low-power
mode if there is nothing else to be done.We already saw that the MSP430 spends much of its
time asleep in many applications and is awakened periodically by a timer.

165
Watchdog Timer
The main purpose of the watchdog timer is to protect the system against failure of the software,
such as the program becoming trapped in an unintended, infinite loop. Left to itself, the
watchdog counts up and resets the MSP430 when it reaches its limit. The code must therefore
keep clearing the counter before the limit is reached to prevent a reset. The operation of the
watchdog is controlled by the 16-bit register WDTCTL. It is guarded against accidental writes by
requiring the password WDTPW = 0x5A in the upper byte. A reset will occur if a value with an
incorrect password is written to WDTCTL. This can be done deliberately if you need to reset the
chip from software. Reading WDTCTL returns 0x69 in the upper byte, so reading WDTCTL and
writing the value back violates the password and causes a reset.
The lower byte of WDTCTL contains the bits that control the operation of the watchdog timer,
shown in Figure 8.1. The RST/NMI pin is also configured using this register, which you must
not forget when servicing the watchdog—we see why shortly. This pin is described in the section
“Nonmaskable Interrupts” on page 195. Most bits are reset to 0 after a power-on reset (POR) but
are unaffected by a power-up clear (PUC). This distinction is important in handling resets caused
by the watchdog. The exception is the

WDTCNTCL bit, labeled r0(w). This means that the bit always reads as 0 but a 1 can be written
to stimulate some action, clearing the counter in this case. The watchdog counter is a 16-bit
register WDTCNT, which is not visible to the user. It is clocked from either SMCLK (default) or
ACLK, according to the WDTSSEL bit. The reset output can be selected from bits 6, 9, 13, or 15
of the counter. Thus the period is 26 = 64, 512, 8192, or 32,768 (default) times the period of the
clock. This is controlled by the WDTISx bits in WDTCTL. The intervals are roughly 2, 16, 250,
and 1000 ms if the watchdog runs from ACLK at 32 KHz. The watchdog is always active after
the MSP430 has been reset. By default the clock is SMCLK, which is in turn derived from the
DCO at about 1 MHz. The default period of the watchdog is the maximum value of 32,768

166
counts, which is therefore around 32 ms. You must clear, stop, or reconfigure the watchdog
before this time has elapsed. In almost all programs in this book, I take the simplest approach of
stopping the watchdog, which means setting the WDTHOLD bit. This goes back to the first
program to light LEDs, Listing 4.2. If the watchdog is left running, the counter must be
repeatedly cleared to prevent it counting up as far as its limit. This is done by setting the
WDTCNTCL bit in WDTCTL. The task is often called petting, feeding, or kicking the dog,
depending on your attitude toward canines. The bit automatically clears again after WDTCNT
has been reset. The MSP430 is reset if the watchdog counter reaches its limit. Recall from the
section “Resets” on page 157 that there are two levels of reset. The watchdog causes a power-up
clear, which is the less drastic form. Most registers are reset to default values but some retain
their contents, which is vital so that the source of the reset can be determined. The watchdog
timer sets the WDTIFG flag in the special function register IFG1. This is cleared by a power-on
reset but its value is preserved during a PUC. Thus a program can check this bit to find out
whether a reset arose from the watchdog. Listing 8.1 shows a trivial program to demonstrate the
watchdog. I selected the clock from ACLK (WDTSSEL = 1) and the longest period (WDTISx =
00), which gives 1s with a 32 KHz crystal for ACLK. It is wise to restart any timer whenever its
configuration is changed so I also cleared the counter by setting the WDTCNTCL bit. LED1
shows the state of button B1 and LED2 shows WDTIFG. The watchdog is serviced by rewriting
the configuration value in a loop while button B1 is held down. If the button is left up for more
than 1s the watchdog times out, raises the flag WDTIFG, and resets the device with a PUC.
This is shown by LED2 lighting.
Basic Timer1
Basic Timer1 is present in all MSP430xF4xx devices and is perhaps the most straightforward
module in the MSP430, as you might guess from its name. It provides the clock

167
for the LCD module (but not LCD_A) and generates periodic interrupts. A slightly simplified
block diagram is shown in Figure 8.2. Newer devices also contain a real-time clock driven by a
signal at 1Hz from Basic Timer1. The register BTCTL shown in Figure 8.3 controls most of the
functions of Basic Timer1 but there are also bits in the special function registers IFG2 and IE2
for interrupts. An unusual feature of this module is that BTCTL is not initialized by a reset: This
must be done by the user. It is not even specified whether the timer is running or not. The
counters are not initialized either and this should be done before the timer is started or the first
interval will be incorrect. There are two 8-bit counters in Basic Timer1, which can either be used
independently or cascaded for longer intervals:
BTCNT1: Takes its input from ACLK and provides the clock for the LCD module at frequency
fLCD. The two BTFRFQx bits select the value of fLCD, which can vary from fACLK/256 to
fACLK/32 in powers of 2. It is assumed that fACLK = 32 KHz.
This gives fLCD from 128 Hz to 1 KHz, which should be suitable for the LCD. The calculation
of fLCD is explained in the section “Driving an LCD from an MSP430x4xx” on page 256. The
LCD_A controller does not need a clock from BTCNT1, so the counter’s only function in this
case is as a prescaler for BTCNT2.
BTCNT2: Can be used independently of BTCNT1, in which case the BTSSEL bit selects the
clock from ACLK or SMCLK. For longer intervals, BTCNT2 can be clocked from the output of
168
BTCNT1 at a frequency of fACLK/256. Set the BTDIV bit to cascade the counters in this way.
Setting the BTHOLD bit stops BTCNT2, but stops
BTCNT1 only if BTDIV is also set.
BTCNT2 provides no output signals. Instead it raises the BTIFG flag at a frequency determined
by the BTIPx bits. The range goes from fCLK2/256 to fCLK2/2, where fCLK2 is the frequency
of the clock input to BTCNT2.With the counters cascaded this gives a period from about 16 ms
to 2s.
The BTIFG flag is in the IFG2 register. An interrupt also is requested if the BTIE bit is set in
IE2. The interrupt is maskable so GIE must also be set for the interrupt to be accepted. The
BTIFG flag is cleared automatically when the interrupt is serviced. Alternatively the flag can be
polled, in which case it must be cleared in software. We used Timer_A for many applications in
Chapters 4 and 6. It would have been better to have used Basic Timer1 for most of these
examples, except that it is restricted to the MSP430xF4xx family. The first instance was to flash
a light by polling the TAIFG flag in the section “Automatic Control: Flashing a Light by Polling
Timer_A” on page 105. This could be done in exactly the same way with Basic Timer1 and the
BTIFG flag. The only difference is that a restricted range of intervals is available, unlike
Timer_A in Up mode. Similarly, Listings 6.4 and 6.5 show how to do the same task using
interrupts. Basic Timer1 could again be used instead. This is a convenient way of generating a
real-time interrupt (RTI), which can be used as a “heartbeat” to wake a program periodically.
Again this was done using Timer_A in Listing 6.8 but Basic Timer1 is often a better choice.
REAL-TIME CLOCK
A Real-Time Clock (RTC) module has been added to recent devices in the MSP430xFxx family.
It counts seconds, minutes, hours, days, months, and years. Alternatively it can be used as a
straightforward counter, which I describe briefly at the end of this section, but for now I assume
that it is configured in calendar mode by setting RTCMODEx=11 in the control register
RTCCTL. The bits are shown in Figure 8.4. This register is initialized after

169
Figure 8.4: The Real-Time Clock control register RTCCTL.
a power-on reset, unlike BTCTL, and the RTCHOLD bit is set so that the clock does not run by
default.
The current time and date are held in a set of registers that contain the following bytes:
 Second (RTCSEC).
 Minute (RTCMIN).
 Hour (RTCHOUR), which runs from 0–23 (24-hour format).
 Day of week (RTCDOW), which runs from 0–6.
 Day of month (RTCDAY).
 Month (RTCMON).
 Year (RTCYEARL), assuming BCD format.
 Century (RTCYEARH), assuming BCD format.
The registers are arranged in pairs that can also be accessed as words. For example, RTCYEAR
= RTCYEARH:RTCYEARL and RTCTIM0 = RTCMIN:RTCSEC. Their values can be stored
either as normal binary numbers or as BCD. The latter is more convenient for driving a display
and is selected by setting the RTCBCD bit in RTCCTL. The registers that hold the date and time
are initialized when calendar mode is selected but the user will obviously need to store the
current values if “real” time is to be real. The module automatically accounts for the different
number of days in the months and allows for leap years during the current century. In principle it
could compute the day of week from the rest of the date but it does not: RTCDOW is effectively
an independent 0–6 counter, incremented daily. The user must initialize this appropriately and
decide which day is the start of the week. There is no provision for a 12-hour clock with
anAM/PM flag so this would have to be done in software.
The clock needs a 1 Hz input, which it takes from Basic Timer1. The RTC module therefore
takes control over Basic Timer1 and cascades the counters as if BTDIV=1. It remains possible to
take interrupts from BTCNT2 so the BTIPx bits are still useful. The Rea -Time Clock has an
interrupt flag RTCFG and corresponding enable bit RTCIE in RTCCTL. The flag is set every
minute, every hour, daily at midnight, or daily at noon depending on the RTCTEVx bits. The
interrupt vector is shared with Basic Timer1. It is maskable and can be used in two ways:

170
 Interrupts are generated by the Real-Time Clock module if RTCIE is set. Both the BTIFG
and RTCFG flags are set at an interrupt and cleared automatically when it is serviced.
The interval is determined by RTCTEVx.
 Interrupts come from Basic Timer1 as described earlier if RTCIE is clear. The interval is
determined by BTIPx. The Real-Time Clock sets its RTCFG flag according to RTCTEVx
but this does not request an interrupt. A program can poll the flag to check whether an
interval of time has elapsed and must clear RTCFG in software.
There is no alarm clock—an interrupt requested at a specified time and date—which seems a
curious omission. This must be implemented in software if desired. “Gotcha!” The flag is called
RTCFG, not RTCIFG as you might expect. Listing 8.3 shows the relevant functions from a
program to run a clock on the TI MSP430FG4618/F2013 Experimenter’s Board. The display
shows hours and minutes, separated by a colon that flashes at 1 Hz. An interrupt from Basic
Timer1 every 0.5s toggles the colon, polls RTCFG and updates the digits if a minute has passed.
The flag is cleared by software. The current version of the header file does not define bitfields
for BTCTL and RTCCTL so I have had to use masks instead. There are warnings in the user’s
guide about accessing the registers of the Real-Time Clock. The problem is that changes in these
registers are triggered by ACLK but reading or writing from a program is synchronized to
MCLK. It is therefore possible that you might try to read the registers while they are being
updated, in which case the result would be corrupted. This is a classic example of the issue
described in the section “The Shared Data Problem” on page 197. It should not be a problem in
Listing 8.3 because the interrupt is requested just after the clock has been updated, at which point
the values are stable for nearly 1s. The safest, general approach is to stop the clock while a
reading is taken but this could lose 1s if a tick is missed during the read. Alternatively the
registers can be read several times and a majority vote taken, which should discard any erroneous
values. Another solution is to copy the values from the module into a set of “shadow” registers in
RAM during interrupts from the Real-Time Clock. The shadow registers can be read safely from
the main program provided that interrupts are disabled during the read. This will not cause any
time to be lost because the Real-Time Clock is updated by hardware.
Timer_A

171
This is the most versatile, general-purpose timer in the MSP430 and is included in all devices. It
was introduced in the section “Automatic Control: Flashing a Light by Polling Timer_A” on
page 105 and its general features will be familiar if you have used a general-purpose timer in any
other modern microcontroller. There are two main parts to the hardware:
 Timer block: The core, based on the 16-bit register TAR. There is a choice of sources
for the clock, whose frequency can be divided down (prescaled). The timer block has no
output but a flag TAIFG is raised when the counter returns to 0.
 Capture/compare channels: In which most events occur, each of which is based on a
register TACCRn. They all work in the same way with the important exception of
TACCR0. Each channel can
 Capture an input, which means recording the “time” (the value in TAR) at which the
input changes in TACCRn; the input can be either external or internal from another
peripheral or software.
 Compare the current value of TAR with the value stored in TACCRn and update an
output when they match; the output can again be either external or internal.
 Request an interrupt by setting its flag TACCRn CCIFG on either of these events; this
can be done even if no output signal is produced.
 Sample an input at a compare event; this special feature is particularly useful if Timer_A
is used for serial communication in a device that lacks a dedicated interface.
Timer_A is modular and the number of capture/compare channels varies between devices. Most
have three channels but the smallest members of the MSP430F2xx family have only two and
some earlier devices had more. The number of channels is sometimes appended to the name as in
Timer_A3. Capture/compare channel 0 is special in two ways. Its register TACCR0 is taken over
for the modulus value in Up and Up/Down modes, so that it is no longer available for its usual
functions. It also has its own interrupt vector with a higher priority than the other interrupts from
Timer_A, which all share a common vector. Therefore channel 0 should be chosen for the most
urgent tasks if it is free.
It is important to realize that all channels within Timer_A share the same timer block: There is
only one TAR. This ensures that actions performed by the different channels are precisely
synchronized. The drawback is that they all work at the same fundamental frequency. Outputs

172
must be supervised by software rather than driven purely by hardware if you need them to
change at different frequencies or not to be periodic at all. A few devices have two Timer_A
modules, which operate with independent time bases. A general principle is to use the hardware
of Timer_A for the part of an event that needs precise timing and to reserve software for the less
critical parts. This means that signals to be timed should be connected directly to capture inputs
so that there is no delay. Outputs should be driven directly from the timer so that they change as
soon as a compare event happens. Of course this works only if suitable pins are available or there
is an internal connection to the peripheral concerned. Software can then respond to the event—
calculate the duration of an input or set up the next output—but the delay required for this does
not compromise the timing of the signals. Timer_A is well documented. There are extensive
application notes, some of which I mention later, and over 160 pages in Application Reports
(slaa024). Many of TI’s code examples illustrate its applications.

Figure 8.5 shows a simplified block diagram of the timer block and a typical capture/compare
channel. Many of the internal signals are omitted for clarity and it emphasizes different features
from Figure 4.7. The internal compare signal EQU0 from channel 0 is particularly important

173
because it plays an important role in the outputs from the other channels and controls the timer
itself in Up and Up/Down modes.
Timer Block
This contains the 16-bit timer register TAR, which is central to the operation of the timer. It is
controlled by the register TACTL shown in Figure 4.8. Remember that a timer is really no more
than a counter and has no direct concept of time (the Real-Time Clock is an exception). It is the
programmer’s job to establish a relation between the value in the counter and real time. This
depends essentially on the frequency of the clock for the timer. It can be chosen from four
sources by using the TASSELx bits:
 SMCLK is internal and usually fast (megahertz).
 ACLK is internal and usually slow, typically 32 KHz from a watch crystal but may be
taken from the VLO in the MSP430F2xx family
 TACLK is external.
 INCLK is also external, sometimes a separate pin but often it is connected through an
inverter to the pin for TACLK so that INCLK = TACLK.
TAR increments on the rising (positive) edge of the clock. The arrangement INCLK = TACLK
in many devices allows TAR to be clocked on the falling (negative) edge of the external clock if
required. An accurate, stable clock source is needed if the timer is to work in real time. This
generally requires a crystal, described in the section “Crystal Oscillators, LFXT1 and XT2” on
page 165. An alternative is to use the frequency of the AC mains if available. This is not
particularly stable over short times but power companies usually aim to keep the average
frequency accurate at 50 or 60 Hz over a day. See Section 6.3.8.7 of Application Reports
(slaa024). The frequency of the incoming clock can be divided down by 2, 4, or 8 if desired by
configuring the IDx bits. A slower clock reduces the resolution of the timer so that events are
timed less precisely. Against this, it increases the natural period of the timer before it overflows,
rolls over, and restarts from 0. It is not difficult to count the number of overflows for intervals
longer than the period but of course it is easier to avoid it. The trade-off between resolution and
period by choosing different clocks is shown in Table 8.1. The period of the timer can range
from 4ms with the fastest SMCLK to 16s with a 32 KHz ACLK and maximum division (even
longer with the 12 KHz VLO). I assume that SMCLK runs at the same frequency as MCLK but

174
it can also be divided in the MSP430x1xx and MSP430F2xx families, which allows longer
periods from SMCLK.

These periods all apply to the Continuous mode, in which TAR cycles through its full range. The
timer has four modes of operation, selected with the MCx bits:
Stop (MC = 0): The timer is halted. All registers, including TAR, retain their values so that the
timer can be restarted later where it left off.
Continuous (2): The counter runs freely through its full range from 0x0000 to 0xFFFF, at which
point it overflows and rolls over back to 0. The period is 216 = 65,536 counts. This mode is most
convenient for capturing inputs and is also used when channels provide outputs with different
frequencies or that are not periodic at all.
Up (1): The counter counts from 0 up to the value in TACCR0, the capture/compare register for
channel 0. It returns to 0 on the next clock transition. The period is (TACCR0+1) counts. For
example, if TACCR0 = 4, the sequence of counts is 0, 1, 2, 3, 4, 0, 1, . . . with period 5. Up mode
is usually used when all channels provide outputs at the same frequency, often for pulse-width
modulation.
Up/Down (3): The counter counts from 0 up to TACCR0, then down again to 0 and repeats. The
period is 2×TACCR0 counts. For example, if TACCR0=3, the sequence of counts is 0, 1, 2, 3, 2,
1, 0, 1, . . . with period 6. This is a specialized mode, typically used for centered pulse-width
modulation.
REAL TIME

CLOCK 1

175
Introduction

176
The MSP430 family of microcontrollers from Texas Instruments (TI) is a family of
ultralowpower, 16-bit RISC microcontrollers with an advanced architecture and a rich peripheral
set. The architecture uses advanced timing and design features, as well as a highly orthogonal
structure, to deliver a processor that is both powerful and flexible. The MSP430x1xx devices
consume less than 350 µA in active mode when operating at 1 MHz in a typical 3-V system, and
can wake up from a 2 µA standby mode to fully synchronized operation in less than 6 µs. These
exceptionally low current requirements, combined with the fast wake-up time, enable users to
build a system with minimum current consumption and maximum battery life. Additionally, the
MSP430 family has an abundant mix of peripherals and memory sizes enabling true system-on-
a-chip designs. The peripherals include 12- and 14-bit A/D converters, slope A/D, multiple
timers (some with capture/compare registers and PWM output capability), LCD driver, on-chip
clock generation, H/W multiplier, USART, Watchdog Timer, GPIO, and others. See
http://www.ti.com for the latest device information and literature on the MSP430 family.

Real-Time Clock Application

Real time clocks (RTC) are used in a variety of applications—from watches and clocks to time-
stamping events, to generating events. This report describes how to implement an RTC on an
MSP430F1121 device. In some applications, an MSP430 implementing a real-time clock can be
used to replace dedicated RTC devices, thus simplifying system design and reducing costs. This
report shows examples on the use of Timer_A and the Watchdog Timer to implement the RTC;
however, any other MSP430 timer can be used in a similar manner. All MSP430 devices can
implement an RTC. Additionally, system integration, power savings, and cost savings may be
achieved by leveraging some of the peripherals from the MSP430 family. For example, a ’33x
device could function as an RTC, a system supervisor, an LCD driver, and a UART, integrating
all four functions onto a single, ultralow-power device.

MSP430 Clock Generation

Internal clock generation is one of the most commonly misunderstood subjects by MSP430
users. The primary cause of confusion lies with how a stable system clock is produced. All
MSP430 devices contain both a digitally-controlled RC-type oscillator and a crystal oscillator.

177
The RC-type oscillator is typically used for the CPU clock and the crystal oscillator is typically
used for the peripherals. In the real-time clock application, the crystal oscillator is used as the
clock source for the timer/counter that serves as the time base (either Timer_A or the Watchdog
Timer in this application report). Therefore, the instability issues that are common to RC-type
oscillators are irrelevant.

Real-Time Clock Implementation The general implementation of the RTC is simple. It consists
of a timer/counter giving 1-second interrupts and a small CPU routine to count the interrupts.
The CPU can sleep or perform other functions between interrupts. This application report and the
code examples were developed using the MSP430F1121. The following sections describe the
design.

1. Clock Generation Setup

The clock setup for the RTC implementation uses the LFXT1 oscillator in LF mode with a
32768-Hz crystal. The output of the LFXT1 oscillator is selected to source ACLK. ACLK is then
selected as the clock source for the timer/counter that serves as the time base for the RTC. The
DCO generates the CPU clock, MCLK. The CPU actually runs asynchronously to the
timer/counter peripheral. Accuracy of the RTC is not affected as long as the CPU is able to
service each interrupt from the timer peripheral before the next interrupt arrives. See the
MSP430x1xx Family user’s guide [1] (available from http://www.ti.com/sc/msp430) and the
MSP430x11x1 data sheet [2] for more detailed discussions on the Basic Clock Module and its
setup requirements.

2. Timer Selection

The MPS430F1121 device contains two timers: Watchdog Timer and Timer_A. An example
showing the use of each of these timers is included at the end of this report. In both examples the
timer is configured to count continuously and give interrupts at exactly 1-second intervals. Since
the timer is configured to use ACLK as its clock source, and ACLK runs at exactly the crystal
frequency (32768 Hz), the timer simply counts up to 32767 and starts over at 0, giving an
interrupt each time it reaches 32767. The CPU then simply counts the interrupts to form the
RTC. Any timer capable of generating a 1-second interrupt can be used with the clock routine in
178
this application report. Furthermore, the clock routine can be adjusted to use any timer giving
periodic interrupts. For example, if a timer gives an interrupt exactly every 0.5 seconds, the CPU
can simply count two interrupts as one second, and so on.

3. External Interface The code in this application report does not provide an external interface
for the RTC. If the MSP430 implementation is being used to replace a dedicated RTC chip, there
are several interfaces to choose from, including I2C, parallel, UART, serial, etc. TI has code
modules to implement these interfaces on MSP430 devices already written and available for easy
integration. Building a complete RTC based on the MSP430 is simply a matter of choosing an
interface and integrating the applicable routine(s) with the RTC routine shown here. More
detailed discussions of some of the possible interfaces can be found in the MSP430 Family
Application Report Book [3] and in individual application reports.

4. Circuit Description

Figure 1 shows the circuit diagram of the RTC. Note that the only external component required
is the 32768-Hz crystal.

5. Current Consumption

179
The typical current consumption of the MSP430F11x1 in active mode is 300 A at 1 MHz and 3
V. Typical current consumption in low-power mode 3 (sleep mode) is 1.6 A at 3-V. The device
wakes from low-power mode 3 in less than 6 s, and the clock routine executes in roughly 130
s. Given the ultralow current consumption and the very short time in active mode, the ’F11x1
operating as an RTC consumes very little current over time, and therefore maximizes battery life.
6 Accuracy Issues
The accuracy of the RTC depends on the accuracy of the crystal chosen for the crystal oscillator.
This allows the user to purchase the appropriate crystal for the desired accuracy.
Crystal Accuracy and Selection
Crystal accuracy is affected primarily by two things: the crystal frequency tolerance, and the
specified load capacitance. The tolerance of the crystal is self-explanatory: the tighter the
tolerance on the crystal frequency, the more accurate the RTC will be. For example, an RTC
using a 30-ppm crystal is more accurate then one using a 200-ppm crystal.
The specified load capacitance of the crystal also affects the accuracy of the RTC. The load
capacitance of a crystal is the amount of capacitance required by the crystal, not the amount
provided by the crystal. The crystal requires the proper load capacitance to oscillate at its
specified frequency. The 32768-Hz oscillator on all MSP430 devices has integrated load
capacitors with a specified nominal capacitance of 12 pF. This provides an overall 6-pF load for
the crystal because the capacitors add serially. In addition, the stray capacitance of the board and
pins add in a parallel fashion, thus increasing the capacitive load seen by the crystal. For
example, 2 pF of stray capacitance is not uncommon on a circuit board. The addition of the 2 pF
to the 6 pF yields a total capacitive load for the crystal of 8 pF. In some cases, depending on
crystal specification and stray capacitances, parallel capacitors must be added to the circuit to
provide the proper capacitive load for the crystal.
Expandability
MSP430x11x devices are ultralow-power, inexpensive microcontrollers that can be ideally suited
to replace real-time clock devices. One of the key benefits of using an MSP430 as an RTC is the
expandability of the MSP430 over a dedicated RTC device. All MSP430x11x devices contain a
16-bit RISC CPU, 16-bit Watchdog Timer, 16-bit Timer_A (with 3 capture/compare registers
and analog comparator), a minimum of 128B RAM, a minimum of 2KB ROM, and a minimum

180
of 14 GPIO pins. Not all of this functionality is available simultaneously, but it becomes clear
that the device offers a great deal of flexibility over a dedicated RTC device. In addition, the
Timer_A module is capable of slope A/D conversion, PWM output, and UART operation up to
115,200 baud. The Watchdog Timer is capable of operating as a simple timer, and the GPIO pins
and all peripherals have extensive interrupt capability.

DATA ACQUISITION

Microcontrollers offer a complete signal-chain on a chip for a wide range of applications. One of
the most important interfaces between the microcontroller and the real word is the Analogue-to-
Digital Converter (ADC). This allows a digital representation of a physical signal to be
measured, usually an electrical signal and measured in volts. Typically, the low amplitude of
most analogue signals representing physical quantities, such as temperature, humidity, pressure,
velocity among others, require some form of signal conditioning. The first stage in this process is
often amplification of the analogue signal. This chapter starts by describing the operational
amplifiers built into the MSP430 family of devices, their architectures and operation. To convert
an analogue signal to a digital value, it is necessary to use an ADC. The Successive
Approximation Register (SAR) converter determines the digital word by approximating the input
signal using an iterative process. The Sigma Delta (SD) converter determines the digital word by
sampling and digital filtering. The on-board analogue comparator provided by the MSP430 is
configurable, which allows mapping of external pins by inputs or outputs, with interrupt
capabilities on either the rising or falling edges. Finally, at the end of the chapter there are
laboratory exercises, which develop applications that group together the use of the operational
amplifier and the ADC.
Data Acquisition Introduction
Nearly all engineering applications require some form of measuring, controlling, calculating,
communicating and recording of data. These operations, grouped or isolated, are inherent in
measurement instrumentation. If the equipment is to be used for the quantitative analysis of an
analogue signal, i.e., a naturally occurring signal, the following must be taken into consideration:
 Measuring method;
180
 Data recording method;
 Interaction between the different equipment and between the analogue signal source;
 Admissible error margin;
 Noise and interference influence;
 Measuring uncertainty;
 Type of control resulting from the measurement (analogue/digital);
 Method of communication with other equipment;
 Mathematical capacity;
The analogue signal to be measured may be temperature, pressure, humidity, velocity, flow rate,
linear motion, position, amongst others. This signal must be converted into an analogue electrical
signal, typically voltage or current, and then into a digital form that can be processed by an
electronic circuit. The first task requires sensors to convert the physical quantities into electrical
signals. Generally, sensors convert physical quantities into analogue electrical signal in the range
of millivolts or milliamps.
Figure 9-1. Data acquisition block diagram.

Signal conditioning relates to the operations required to convert the analogue electrical signal
measured by the sensor to the signal level supported by analogue-to-digital converter (ADC).
This typically involves operations such as signal filtering and amplification. Signal filtering may
reduce the signal level, but the amplification operation is linear, so that the output maintains all
its characteristics, being changed only in amplitude. When the analogue electrical signal is
conditioned to be compatible with the range of values supported by the ADC, the conversion
operation initiates a sample-and-hold function. This takes a snapshot of the continuously
changing input signal and holds on to it until the next sample is acquired. Note that the Sample-
and-hold is not necessary for Sigma-Delta (SD) converters, nor for slope converters, nor for all

181
flash converters and is automatically implemented as part of structure of capacitive Successive
Approximation Register (SAR) converters on the MSP430. The specifications of these
converters will be described in the following sections. The time interval between samples should
be based on the Nyquist theorem, so that the analogue signal is converted into a digital signal
that reproduces all its amplitude variations. This procedure requires a balance between the speed
of the conversion process and the sampling rate, in order to minimize the error between the true
input voltage and the ADC output voltage measured. The resolution of the ADC needs to be
sufficient to give the required digital signal accuracy. The output value of the sample-and-hold is
fed into the ADC, which generates a digital code that can be used by a digital processing system.
Several MSP430 devices include on-chip the signal conditioning and analogue-to-digital
converters. Additionally, some of the devices include an internal temperature sensor. The
following section describes the operational amplifier topologies and different types of ADC, as
contained in MSP430 devices, as well as their configurations and applications.
ANALOGUE-TO-DIGITAL CONVERTER (ADC)
The Analog-to-Digital Converter of the MSP430C32x
The analog-to-digital converter (ADC) of the MSP430 measures the voltage between its AVss
and SVcc connections with a resolution of 14 bits. The signed voltages coming from the current
and voltage interfaces are shifted into the unsigned range of the ADC by simple interfaces
described below. The MSP430 subtracts the measured or calculated offset value from every
measured current or voltage sample: this enables signed, offset corrected measurements.

Figure 4–4. Allocation of the ADC Range

182
Figure 4–4 shows the placement of the current and voltage coming from the voltage dividers and
the current interfaces into the analog-to-digital converter’s range. All calculations and proposals
base on a use of 90% of the ADC range for nominal (100%) values of current and voltage. This
means up to 111% of the nominal values are still measured correctly. This allocation may be
changed if necessary
Table 4–5 shows the influence of the analog-to-digital converter’s performance to the accuracy
of the measurement of the electric energy. Two influences are involved:
1) The deviation of the ADC from the linearity. Each one of the four ranges A, B, C and D has
calculated deviations up to 20 ADC steps compared to the two ranges bordering on it.
2) The saturation effect at the range limits: if the sample for the definition of the range is taken in
another range than the sample for the 12-bit conversion (36 ADCLKs later) than the result is
xFFFh for increasing input signals and x000h for decreasing input signals (x denotes the number
of the range where the range sample was taken). As the results show, the two saturation effects
compensate nearly to zero.
Note:The deviations of the analog-to-digital converter used with the examples below ( 20 steps)
are greater than the specified ones. These large deviations are used only to show the relative
independence of the overall accuracy from the ADC error. The actual, specified deviations are
10 steps. It is recommended not to use the exact midpoint of the supply voltage Vcc (Vcc/2) for
the common reference point. This is due to the possible slight slope deviation at the border of
two ADC ranges (here B and C). This may influence the accuracy for the lowest currents. Table
4–5 shows also the influence for some extreme deviations of the analogto- digital converter
characteristic. Figure 4–5 explains the meaning of the used graphics: it shows the second
deviation curve of Table 4–5 in detail.

183
The function shows the deviation at any point of the four ADC ranges. Due to the monotony of
the ADC the errors at the range limits are always equal. The errors shown in Table 4–5 were
calculated with a PASCAL program. The following steps were taken:
1) Measurement and calculation of the error at 5% of the nominal current.
2) Measurement and calculation of the error at 100% of the nominal current
3) Calculation of the slope and offset for the correction (calibration)
4) Simulation of voltage and current samples: any sample is modified with the ADC error
(exactly like during calibration).
5) Correction of all measured values with the calculated slope and offset
6) Calculation of the resulting error
The saturation effect at the range limits is always included. The first column of Table 4–5 with
an ideal ADC characteristic (zero deviation) shows only this effect and the finite ADC
resolution. This column can be used as a reference for the errors of the other five columns.
The calculations are made with the following conditions:
Virtual Ground location in the ADC range: 8190 steps (1FFEh) 49.98% of full ADC range
Measurement time for calibration points: 5s (calibration points are measured this time)
Measurement time for different loads: 9s
AC frequency: 50 Hz
Cosine : 1 (0_)
Sample frequency: 2048 Hz (488.3 s sample distance)
Voltage: 100% Vpp uses 90% of the ADC range
Current: 100% Ipp uses 90% of the ADC range
184
Note:
The drawings on top of the columns of Table 4–5 indicate the ADC error in dependence of the
ADC value. Figure 4–5 shows the drawing above the second column in a magnified form.
Table 4–5. Errors With One Current Range and Single Calibration Range

The large errors at 0.1% of the nominal current result from the relatively far distance from the
5% calibration point and from the missing resolution of the ADC at this small load. The peak-to-
peak value of the ADC result is only 14.7 steps. These errors can be reduced drastically by using
one of the following methods.
Methods to reduce the Error of the Energy Measurement
Three relatively simple methods are given to reduce the error of the energy measurement. In any
case, the values used for the correction are stored in the EEPROM and are loaded into the RAM
during the initialization.
Using a Second Hardware Range
This method is shown with all hardware examples. An analog switch like the TLC4016 switches
a second resistor in parallel to the one used for the low current range. Both ranges uses its own
set of calibration constants (slope and offset) that are measured during two independent
calibration runs for every phase. The advantage of this method is the real increase of resolution
for the low current range.
Using a Second Calibration Range

185
This method only uses a second set of calibration constants (slope and offset) without additional
hardware for the low current range (e.g., from 0.1% to 5% of the nominal current). This method
needs two calibrations per phase, but uses only three measurements (one measurement is used
for both ranges). Table 4–6 shows the enhancement of the accuracy when a second calibration
run is made for the low current range, 0.1% to 5% of the nominal value. The calculations are
made with the same conditions used with Table 4–5. The enhancement can be seen with a
comparison of the two tables. The errors, for the range 5% to 100% of the nominal current, are
the same as shown in Table 4–5.
Table 4–6. Errors With One Current Range and Two Calibration Ranges

Measurement of the ADCs Characteristic


This method uses the actual deviations of the ADC for a rough correction of the measurement
results. During a first run, the ADC characteristic is measured and correction constants are
calculated for any of 8 to 32 software subranges of the ADC. These correction constants are
written into the EEPROM and loaded into the RAM for use. For every subrange, one byte is
needed, which allows corrections up to 127 steps. The correction for the samples needs only
seven instructions per 14-bit value. The advantage of this method is the adaptation to the actual
deviation of the individual ADC. Figure 4–6 shows the correction with the ADC characteristic
using only 8 correction values. The deviations reduce to one quarter of the original ones. If the
correction shows a step near the virtual zero point like shown in Figure 4–6, the subranges B1
and C0 can be corrected in a way that omits this step. Chapter 2, The Analog-To-Digital
Converters gives more information.

186
Figure 4–6. Use of the Actual ADC Characteristic for Corrections (8 Subranges Used)
Dependence on the Voltage and the Phase Angle
Table 4–7 shows the dependence of the MSP430 using the Reduced Scan Principle on the load
current, the ac voltage and the phase angle, , between current and voltage. The ADC is
assumed to be error-free; the saturation effect at the range limits is included. Single calibration
with only one range is used. Nominal voltage is used for the load current dependence and
nominal current (100%) is used with the voltage dependence. The calculations are made with
the same conditions used for the calculations in Table 4–5. Table 4–7. Errors in Dependence on
Current, Voltage and Phase Angle

Derivation of the Measurement Formulas


The electronic meter equivalent of the meter constant of a Ferraris wheel meter (revolutions per
kWh) is the meter constant, CZ, that defines (ADC steps)2 per Ws. The corrected equation used
for the electric energy W is:

187
With the ADC results ADCi (current sample) ADCu (voltage sample) and ADC0u and ADC0i
(zero volt samples) the previous equation gets:

188
Analog Interfaces to the MSP430
This chapter describes some important topics that can affect the overall accuracy of the
electricity meter.
Analog and Digital Grounding
The following schematics are drawn in a simplified manner to make them easier to understand.
In reality, it is necessary to decouple the analog and the digital part as shown in Figure 4–7. This
is to avoid digital noise on the analog signals to be measured.

189
ADC Input Considerations
The ADC accurately operates up to 1.5 MHz. If the processor clock MCLK is higher than this
frequency, it is recommended that one of the prescaled ADC clocks (ADCLK) be used. The
possible prescaled frequencies for the ADCLK are MCLK, MCLK/2, MCLK/3 and MCLK/4.
The sampling of the ADC to get the range information takes 12 ADCLK cycles. This means, the
sampling gate is open during this time (12 s at ADCLK = 1 MHz). The input of an ADC
terminal can be seen as an RC low-pass filter, 2 k together with 42 pF. The 42-pF capacitor
must be charged during the 12 ADCLK cycles to the final value in order to be measured. This
means charged within 2–14 of this value. This time limits the internal resistance RI of the source
to be measured:

Solved for RI, the result is 27.4 k . This means, to get the full 14-bit resolution of the ADC, the
internal resistance of the input signal must be lower than 27.4 k . The given examples use lower
source resistances at the ADC inputs.
Offset Treatment
If the voltage and current samples contain offsets, the equation for the measured energy W is:
190
The terms (un Oi) and (in Ou) get zero when summed-up over one full period (the
integral of a sine curve from 0 to 2 is zero) but the term (Oi Ou) is added erroneously to
the sum buffer with each sample result. If one of the two offsets can be made zero then the error
term (Oi Ou) is eliminated: this is the case for all proposals. Two different ways are used:
Voltage representing 0V is measured (see Sections 4.1.4.4.1 and 4.1.4.4.2)
Summed-up ADC value for a full period is used for this purpose (see Section 4.1.4.4.3).
Adaptation to the Range of the Analog-to-Digital Converter
The analog-to-digital converter of the MSP430 is able to measure unsigned voltages ranging
from AVss up to the reference voltage applied to the input SVcc. If signed measurements, as for
electricity meters, are necessary then a virtual zero point must be provided. Voltages above this
zero point are treated as positive ones, voltages below it are treated as negative voltages. A few
possibilities are shown how to provide this virtual zero point. For more information see Section
3.8, Power Supplies for the MSP430.
Split Power Supply
To get a common reference voltage in the middle of the ADC’s voltage range, two voltage
regulators with output voltages of +2.5 V and –2.5 V can be used. In this case, the common zero
connection is the reference for all current and voltage measurements. This zero point is
connected to one of the analog inputs (A0 in Figure 4–8). The measured ADC value of this
reference voltage is subtracted from every voltage and current sample. This way signed, offset
corrected measurement values are generated. The schematic is shown in Figure 4–8.

191
Use of a Virtual Ground IC
A virtual ground IC can be used to get a measurement reference in the middle of the ADC range.
The TLE2426 is used for this purpose. All current and voltage inputs are referenced to the virtual
ground output of this circuit. The main advantage is the ability to measure the ADC value of this
reference without the need to switch off the voltage and current inputs. The measured value (at
analog input A0), is subtracted from every measured current or voltage sample, which generates
signed, offset corrected results (see Figure 4–9).
 Typical electrical characteristics of the TLE2426:
 Supply Current 170 A No load connected
 Output Impedance 0.0075
 Output Current Capability 20 mA For sink and source
 Power Rating at 25C 725 mW For the Small Outline Package
 Derating Factor above 25C 5.8 mW/C

192
Resistor Interface (Software Offset)
This method uses the fact that the integral of a sine curve is zero, if integrated over the angle 2 .
Two counters add up the ADC results separately for each voltage and current signal. These
counters contain the two offsets (in ADC steps) after a full period of the ac frequency. These
offsets are subtracted from the appertaining ADC samples. The results are signed, offset
corrected samples. The current and voltage signals are shifted into the middle of the ADC range
by simple voltage dividers or with the help of the internal current source.
Without A Current Source
The necessary shift of the signed voltage and current signals is made by resistor dividers. The
resistor divider of the voltage part is also used for the adaptation of the ac voltage to the ADC
range. The current part allows two (or more) current ranges. With the closed range switch, high
currents can be measured. With the switchopen, a better resolution for the low currents is
possible. No dc flows through the current transformer due to the high input resistance of the
ADC inputs

193
Figure 4–10. Resistor Interface Without Current Source
With A Current Source
Four ADC inputs can be used with the internal current source. A current, defined by an external
resistor Rex, is switched to the ADC input and the voltage drop at the external circuitry is
measured with the ADC. This current is relative to the reference voltage SVcc and delivers
constant results also with different values of SVcc. If a second current range is needed, a reed
relay is needed to switch the second load resistor of the current transformer.
Note:
The signal at the current transformer has a negative going part—outside of the ADC voltage
range—therefore a TLC4016 cannot be used). The current Ics flows through the current
transformer’s secondary windings. This will need to be checked to see if it is usable.

194
Figure 4–11.Resistor Interface With Current Source
Note:
If the current source is used, only ADC ranges A and B can be used. This is because of the
supply voltage the current source needs for operation. The resolution is therefore only one-half
of the normal value. The midpoint of the ADC range is then 01000h.
4.1.4.5 Current Measurement
The main problem of the current measurement is the large dynamic range of the input values;
ranging from 0.1% up to 1000% of the nominal value. The common methods used to solve this
problem are shown in Figure 4–12 and are explained in the following text. If range switches are
used, it is recommended that a hysteresis for the range selection criteria be used.
Shunt
The load current IL flows through a resistor Rshunt (0.3 m to 3.0 m ) and the voltage drop of
this resistor (shunt) is used for the current measurement. Due to the small voltage drop,
especially with low currents, it is necessary to amplify this voltage drop with an operational
amplifier. This operational amplifier can have only a very small phase shift (0.1) to get the
needed accuracy. The out put voltage VOut, which is proportional to the current IL, is measured
by the
MSP430. The amount of VOut is:

195
Advantages
_ Resistive behavior
_ Simple
_ More than one range possible with switches
Disadvantages
_ High losses with high currents
_ Very low output voltage with small currents (amplifier necessary)
_ Only usable with single-phase meters

196
Advantages
_ Isolation from ac
_ High accuracy for the magnitude of the current (0.1% reachable)
Disadvantages
_ Sensible to dc current: may lead to saturation
_ Costly
Ferrite Core
The load current Iload flows through a ferrite core with a single winding. The ferrite core has a
small air gap. The magnetic flux crossing this air gap goes through an air-core coil, which is not
loaded. The small output voltage Vfc of this coil is amplified, integrated, and measured by the
MSP430. The voltage gain of the preamplifier is used for the range switching. The ferrite core
behaves as an inductivity L i.e. the output voltage Vfc is:

This means, the voltage Vfc has a leading phase shift of 90_ compared to Iload. This phase shift
can be corrected by two methods:

197
1) Software shift: All current samples are delayed by the time representing 90_ of the ac
frequency. This is possible with a circulating buffer and a
carefully chosen sampling frequency.
2) Analog shift: An integrator combined with a pre-amplifier is used as shown in Figure 4–13.
The value ki [A/step], used for the calculation of the meter constant CZ (see
Section 4.1.3.3) is :

The formula is valid only if R2 >> R1 (normal case).


Advantages
_ Isolation from the ac
_ No saturation possible by dc parts of the load current due to the air gap
Disadvantages
_ Low output voltage due to loose coupling
_ Output voltage leads 90_ compared to load current
Fast load current changes cause relatively high output voltages (di/dt)
Circular buffering or amplification and integration necessary

Compensated Ferrite Core

198
The load current Iload flows through a closed ferrite core with a primary winding wprim
(normally a single winding). The magnetic flux created by the primary winding is sensed by the
sensor winding wsense. The voltage of the sense winding is amplified and the output current of
the amplifier is sent through the secondary winding wsec in a way that compensates the primary
flux to (nearly) zero. This means that the driving of the resistor Rsec is made by the amplifier
and not by the ferrite core. The compensated ferrite core shows only negligible errors. It is only
necessary to distribute the two windings in a very equable way over the entire core (not as it is
shown in Figure 4–13 for simplicity). Additional current ranges are possible with switched
resistors in parallel with Rsec. The output voltage Vout is:

The term wsense Rsec/v Rsense is the remaining error of the compensated ferrite core.
The value ki [A/step], used for the calculation of the meter constant CZ (see Section 4.1.3.3) is
(the error term is not included due to its low value):

Advantages
_ Isolation from ac
_ Nearly complete compensation of the ferrite core’s hysteresis and
nonlinearity errors
Disadvantages
_ Amplifier necessary
_ Difficulties to stabilize feedback loop

199
Resistor Divider
The ac voltage Vac is adapted to the range of the ADC by a simple resistor divider. All of the
examples given use this method. The amount of Vsec is:

The value ku [V/step], used for the calculation of the meter constant CZ (see Section 4.1.3.3) is:

Voltage Transfomer
A voltage transformer is used if the ac voltage is very high or if galvanic isolation is needed.
Protection (PR) at the secondary side is needed, due to the low output impedance of the voltage
transformer. The amount of Vsec is:

The value ku [V/step], used for the calculation of the meter constant CZ (see Section 4.1.3.3) is:

200
Comparator_A
As shown in the previous section, the comparator_A module is primarily designed to support
precision slope analogue-to-digital conversions, battery-voltage supervision, and monitoring of
external analogue signals. It is included in the FG4618 device fitted to the Experimenter’s board.
Features of Comparator_A include:
Inverting and non-inverting terminal input multiplexer;
Software selectable low-pass filter (RC) for the comparator output;
Outputs:
Timer_A capture input;
Interrupt (one interrupt vector with enable);
External.
Software control of the port input buffer;
Selectable references internally (reference voltage generator: VCAREF = 0.25 VCC; 0.5 VCC;
~0.55 V –diode-) and externally;
Comparator and reference generator can be powered down.
Figure 9-67.Comparator_A block diagram.

201
9.4.1 Comparator
The comparator compares the analogue voltages at the + and – input terminals, respectively CA0
and CA1 for a non-inverting topology.
The comparator output:
CAOUT = 1:
CA0 > CA1.
CAOUT = 0:
CA0 < CA1;
CAON = 0 (comparator switched off).

202
203
204
REMOTE CONTROLLER OF AIR CONDITIONER USING MSP430

205
System Description
This board demonstrates an ultra-low power, general purpose, infrared remote controller
solution. The board uses a FRAM-based MCU MSP430FR4133, which supports features such as
real time clock, button scan, infrared encoding, LED backlight, and LCD display.
MSP430FR4133
The MSP430FR4133 is a FRAM-based ultra-low power mixed signal MCU. With the following
features, the
MSP430FR4133 is highly suitable for portable device applications.
• 16-bit RISC architecture up to 16 Mhz
• Wide supply voltage range from 1.8 V to 3.6 V
206
• 64-Pin/56-Pin/48Pin TSSOP/LQFP package options
• Integrated LCD driver with charge pump can support up to 4x36 or 8x32 segment LCD
• Optimized 16-bit timer for infrared signal generation
• Low power mode (LPM3.5) with RTC on:0.77 uA
• Low power mode (LPM3.5) with LCD on: 0.936 uA
• Active mode: 126 uA/MHz
• 10^15 write cycle endurance low power ferroelectric RAM (FRAM) can be used to store data
• 10-channel, 10-bit analog-to-digital converter (ADC) with built-in 1.5 V reference for battery
powered system
• All I/Os are capacitive touch I/O
Circuit Design
The highly-integrated mixed signal processer MSP430FR4133 has a small amount of
components necessary to realize a fully-functional air conditioner remote controller.
Refer to Figure 1 for the design block diagram.

207
A 4x28 segment LCD is directly connected to the MSP430FR4133 LCD driver pins. Designers
can swap the COM and SEG pins to simplify the PCB layout. A 4x4 matrix is used to detect 15
buttons. The matrix columns are connected to interrupt-enabled GPIOs (P1) to wake up the
MSP430FR4133 from low power mode. MCU internal pull up/pull down resistors are used as
button scan matrix pull up resistors. No external resistor is needed for button detection, and no
external circuit is needed for battery voltage detection. The function is also realized by the MCU
ADC module without any external component.
A 32.768 KHz watch crystal serves as the MCU FLL and RTC clock source. Two chip
capacitors, C4 and C6, are used as the crystal loading capacitor. Designers must choose C4 and
C6 values carefully according to crystal specification. Cautious PCB layout design for the crystal

208
is strongly recommended, to secure system clock robustness. Figure 2 illustrates an example of
the crystal PCB design.

3 Software Description
The software implements an interrupt-driven structure. In the main loop, the MCU stays in
LPM3.5 mode. Interrupts from the button, RTC, and timer wake up the MCU for task
processing. Inputs from the button are processed in task KeyProcess (), which handles system
status and generates the content for the LCD display and infrared signal. RTC generates a 3S
interval interrupt to inform the system of battery voltage measurement.

209
Infrared Signal Generation
There are several kinds of infrared modulation protocols in the industry. This design illustrates
pulse distance protocol with data frame format, the most commonly-used format for air
conditioner remote controllers. As shown in Figure 4, each bit is composed of a carrier-
modulated pulse and a space. The space’s width distinguishes logic 1 and logic 0 respectively.
The carrier-modulated pulse width is constant. In this design, space length for 1 is 1690 uS, and
560 uS for digit 0. Modulated pulse width is 560 uS.

210
TA1 is used to generate an envelope waveform, and each pair of carrier-modulated pulse and
space must update the CCR0 and CCR2 once. The CCR0 depends on the carrier-modulated pulse
period plus the space period, while the CCR2 depends on the carrier-modulated pulse period. For
instance, if TA1 sources from SMCLK of 4 MHz and uses default divider configuration, CCR0
and CCR2 are individually configured as 54,000 and 36,000, to generate the leading code (9 ms
carrier modulated pulse paired with 4.5 ms space), and updated to 9,000 and 2,240 for logic 1
(see Figure 6). To send one full data frame, CCR0 and CCR2 must be updated 34
(1+8*2+8*2+1) times, which is achieved in the TA1 interrupt routine.

211
To generate 38 kHz carrier with ¼ duty, CCR0 and CCR2 of TA0 are configured according to
SMCLK. For example, with a 4 MHz SMCLK, CCR0 and CCR2 are individually configured to
be 105 (4,000/38) and 26 (4,000/38/4). Figure 7 shows how the duty setting works.

Figure 7. Pulse Distance Protocol, TA0 in Carrier Generation


Test Setup and Results
Power and Infrared Code Test
2 AAA batteries power the board. By pressing the button pads with conductors, the user can
observe the contents on the LCD. Typical air-conditioner working modes and parameters can be
configured. A microampere meter is inserted in the power path to monitor the board power
consumption as shown in Figure 8. Table 2 shows the sample board test results. To observe the
212
infrared signal, use P1.0 with an oscilloscope. Figure 9 shows the infrared driving signal,
typically 38 KHz PWM carriers, 30% duty.
DATA TRANSFER USING DMA.
Some devices in the MSP430 family support a multi-channel Direct Memory Address (DMA)
controller that can move data from one location to another, without CPU intervention. This
increases the throughput of peripheral modules and also allows the CPU to remain in a low-
power mode, without needing to wake up to perform the data transfer. This gives the benefit of
reduced power consumption. Data transfers to/from peripherals can be initiated by external and
internal events, using triggers.
1 Direct Memory Access (DMA) capability
The MSP430 is well suited to low-power applications, and DMA is a very useful facility to have
in order to achieve this. The following devices in the MSP430 family support DMA: 5xxx,
FG4xx(x), F261x, F16x(x) and F15x. The Experimenter’s Board uses the MSP430FG4618.
When a low power application requires data handling, the direct memory access (DMA)
capability automatically handles data without CPU intervention, lowering the power
consumption because the CPU remains sleeping. The objective of DMA is to move functionality
from the CPU to peripherals (see Figure 11-1) because:
 Peripherals use less current than the CPU;
 Performing operations directly between peripherals allows the CPU to shut down, saving
system power;
 “Intelligent” peripherals are the most capable, providing more opportunity for CPU
shutoff;
 DMA can be enabled for repetitive data handling, increasing the throughput of peripheral
modules; Minimal software requirements and CPU cycles.
Figure 11-1. DMA data handling example.

213
The TI webpage gives some application notes, which explain the use of the DMA controller for
different applications, with the objective of reducing power consumption:
Streamlining the mixed-signal path with the signal-chain-onchip MSP430F169 <slyt078.pdf>
 An integrated signal chain contains a variable resistance that generates a voltage level
sampled by the ADC. The conversion result is processed and used to determine the
update rate of the DAC and consequently, the analogue output signal frequency. The
DAC output frequency adjustment is made by interrupting the DMA instead of the CPU,
freeing up CPU resources for other tasks.
 Interfacing the MSP430 with MMC/SD Flash Memory Cards <slaa281b.pdf>
 The MSP430F161x microcontroller is used to communicate with an MMC or SD flash
memory card via a serial peripheral interface (SPI). The DMA module is used for data
transmission between the MSP430 and the MMC card, resulting in higher communication
speed and less CPU load.
 Digital FIR Filter Design Using the MSP430F16x <slaa228.pdf>
 A FIR filter is implemented using the MSP430F16x family of devices. The complete
filter algorithm is executed by the 3- channel DMA peripheral and the hardware
multiplier peripheral. The 3-channel DMA peripheral is used to handle the required data,
coefficients and movement of results between the memory and the multiply-and-
accumulate (MAC). This dramatically improves the efficiency of the computation of the
real-time FIR filter algorithm running onchip,
 without the intervention of the CPU.
 Using the USCI I2C Master <slaa382.pdf>
 Use of the I2C master function, for MSP430 devices with the USCI module. These
functions can be used by the MSP430 master device to ensure proper initialization of the

214
USCI module and provide I2C transmit and receive functionality. The DMA module
manages the loading of seven data bytes that need to be sent, because during the
transmission, the CPU is in Low Power Mode 0.
DMA configuration and operation
The direct memory access (DMA) controller (see block diagram in Figure 11-2) allows
movement of data from one memory address to another, across the entire address range, without
CPU intervention. Three DMA channels are implemented on the MSP430FG4618 device on the
Experimenter’s board.
Figure 11-2. DMA block diagram

215
DMA controller features:
 Three independent transfer channels;

216
 Configurable (with the ROUNDROBIN bit) DMA channel priorities (default:
DMA0−DMA1−DMA2);
 DMA Transfer cycle time:
 Requires only two MCLK clock cycles per transfer;
 Each byte/word transfer requires two MCLK cycles after synchronization, and one cycle
of wait time after the transfer.
 Byte or word and mixed byte/word transfer capability:
 Byte-to-byte;
 Word-to-word;
 Byte-to-word (upper byte of the destination word is cleared when the transfer occurs);
 Word-to-byte (lower byte of the source word transfers).
 Block sizes up to 65535 bytes or words;
 Configurable selection of transfer trigger (see Table 11-1);

217
218

Selectable edge or level-triggered transfer (DMALEVEL bit);
 Four addressing modes (see Figure 11-3) for each DMA channel independently
configurable (DMASRCINCRx and DMADSTINCRx control bits):
 Fixed address to fixed address;
 Fixed address to block of addresses;
 Block of addresses to fixed address;
 Block of addresses to block of addresses

219
Figure 11-3. DMA addressing modes.

Six transfer modes. Each channel is individually configurable by the DMADTx bits (see Table
11-2).
Table 11-2. DMA transfer modes.

System interrupts

220
DMA transfers are not interruptible by system interrupts, but system interrupt service routines
(ISRs) may be interrupted by DMA transfers. Only non-maskable interrupts (NMIs) can be
configured to interrupt the DMA controller, if the ENNMI bit is set. If it is not set, system
interrupts remain pending until the completion of the transfer.
DMA controller interrupts
Each DMA channel has its own DMAIFG flag, which is set when the corresponding DMAxSZ
register counts to zero (all modes). If the corresponding DMAIE and GIE bits are set, an
interrupt request is generated.
The MSP430FG4618 device implements the interrupt vector register DMAIV. In this case, all
DMAIFG flags are prioritized and combined to source a single interrupt vector. The interrupt
vector register DMAIV is used to determine which flag requested an interrupt.
USCI_B I2C module with DMA
Two trigger sources for the DMA controller;
Triggers a transfer when new I2C data is received and when data is needed for transmit.
ADC12 with DMA
Automatically moves data from any ADC12MEMx register to another location;
DAC12 with DMA
Automatically moves data to the DAC12_xDAT register;
Flash memory with the DMA
Automatically moves data to the flash memory;
Supports word/byte data transfers to the flash memory;
The write timing control is performed by the flash controller;
Write transfers to the flash memory succeed if the flash controller set-up is prior to the DMA
transfer and if the flash is not busy.
All these DMA transfers occur without CPU intervention and independently of any low-power
modes. This increases throughput of the modules and enhances low-power applications by
allowing the CPU to remain off while data transfers occur.

221
PART A

1. Compare the MSP 430 ADC with that of ARM7


2. Compare the timing generation of MSP 430 with SHARC processor
3. Explain the applicability of MSP 430 PWM control with an example
4. Explain the importance of device drivers in embedded systems?
5. Write about interrupt service routines?
6. Explain the concept of interrupt programming in RTOS?
7. Give the architecture of RTOS?

PART B

1. Explain the concept of on chip peripherals


2. What are interrupts? explain the concept of interrupt programming based on
MSP 430
3. Write about I/O ports pull up and pull down registers
4. Explain the operation of MSP 430 in low power mode
5. Draw the architecture of FRAM? Briefly explain FRAM
6. What are timers? Explain the real time clock in MSP 430
7. Explain about PWM control and timing generation?
8. Write about the remote controller using MSP 430
9. Explain the process of data acquisition using ADC and comparator
10.Write about data transfer using Direct Memory Access

222
UNIT -5

SERIAL COMMUNICATIONS
• Many fewer lines are required to transmit data. This is requires fewer pins, but adds
complexity.

Synchronous communications requires clock. Whoever controls the clock controls


communication speed.
• Asynchronous has no clock, but speed must be agreed upon beforehand (baud rate).
Asynchronous Serial (RS‐232)
• Commonly used for one‐to‐one communication.
• There are many variants, the simplest uses just two lines, TX (transmit) and RX (receive).
• Transmission process (9600 baud, 1 bit=1/9600=0.104 mS)
– Transmit idles high (when no communication).
– It goes low for 1 bit (0.104 mS)
– It sends out data, LSB first (7 or 8 bits)
– There may be a parity bit (even or odd – error detection)
– There may be a stop bit (or two)

223
RS232 Voltage levels
• From processor side, 0V=logic 0, 3.3V=logic 1
• In a “serial” cable +12→+3V=logic 0, ‐3→‐12V=logic 1

RS232 – Handshaking
• Some RS232 connections using handshaking lines between DCE (Data Communications
Equipment) and DTE (Data Terminal Equipment).
224
– RTS (Ready To Send)
• Sent by the DTE to signal the DCE it is Ready To Send.
– CTS (Clear To Send)
• Sent by the DCE to signal the DTE that it is Ready to Receive.
– DTR (Data Terminal Ready)
• Sent to DTE to signal the DCE that it is ready to connect
– DSR (Data Set Read)
• Sent to DC to signal the DTE that it is ready to connect
• In practice if these handshaking lines are used it can be difficult to set up the serial
communications, but it is quite robust once working.
• There is also software handshaking (XON/XOFF)
• DTE and DCE have different connector pinouts.

MSP430 USCI in UART mode


(also USART peripheral)
UART mode features include:
• 7‐ or 8‐bit data; odd, even, or non‐parity
• Independent transmit and receive
•LSB‐first or MSB‐first data
•Receiver start‐edge detection for autowake up from LPMx modes
•Independent interrupt capability for receive and transmit
• Status flags for error detection and suppression
•Built‐in idle‐line and address‐bit communication protocols for multiprocessor systems
• Status flags for address detection

225
SPI (SERIAL PERIPHERAL INTERFACE ‐ MOTOROLA)

• Two types of devices, masters and slaves.


226
• We’ll consider only one master, but multiple slaves.
• Signals
– SCLK: Serial CLocK, set by Master
– MOSI: Master Out, Slave In
– MISO: Master In, Slave Out
– ~SS: Slave Select
• Each slave gets its own slave select (other lines are shared)
• Pulling line low selects slave

SPI and the clock (intro)


• Pull slave select line low to select device.
• First bit of data gets put on MISO and MOSI (so a byte goes both ways)
• Data gets shifted out (typically 8 bits, but not necessarily)
– The data gets put on bus on falling edge of clock.
– The data gets read on the rising edge of clock.

227
SPI and SCI
SPI mode features include:
• 7‐ or 8‐bit data length
• LSB‐first or MSB‐first data
• Master or slave modes
• Selectable clock polarity and phase control
• Programmable clock frequency in master mode
• Independent transmit and receive
• Continuous transmit and receive
• Independent interrupt capability for receive and transmit
• Slave operation in LPM4

228
I2C or I2C ( Inter‐Integrated Circuit – Philips)
• As with SPI a masterslave system.
• Also called a 2‐wire bus.
It Has only clock and data, with pull‐up resistors (Rp in diagram).
• Lines can be pulled low by any device, and are high when all devices release them.
• There are no “slave‐select” lines – instead the devices have “addresses” that are sent as part of
the transmission protocol.

229
• Four max speeds (100 kbS (standard), 400 kbS (fast), 1 MbS (fast plus), and 3.4 MbS
(high‐speed)

I2C Write a Single Byte

1. All: allow SDA, SCL start high


2. Master: SDA low to signal start
3. Master: Send out SCL, and 7 bit address followed by 0 (~W) on SDA
4. Slave: Pull SDA low to signify ACKnowledge
5. Master: Send out 8 data bits on SDA
6. Slave: Ack
7. All: allow SDA to go high when SCL is high (stop)
• For “Read”,
3. Master: Address following by 1 (R) on SDA
5. Slave: Send out 8 data bits on SDA
6. Master: Ack

Other Features
• You can transfer multiple bytes in a row

230
At end of transfer, slave can hold SCL low to slow transfer down (called “clock‐stretching”)

Any device that malfunctions can disable bus. I2C and SCI

The I2C features include:


• Compliance to Philips I2C specification
• Slave receiver/transmitter mode
• Standard mode up to 100 kbps and fast mode up to 400 kbps support
• Programmable UCxCLK frequency in master mode
• Designed for low power
• Slave receiver START detection for auto‐wake up from LPMx modes
• Slave operation in LPM4

231
Serial Peripheral Interface
The serial peripheral interface was introduced by Motorola and is the simplest synchronous
communication protocol in general use. Its versatility led to widespread adoption in a much
wider range of applications than straightforward communication. The only problem is that it is
not a fixed standard like I²C. There are plenty of options within “standard” SPI and innumerable
variations that go beyond this. You must always read the data sheet closely for a device that uses
SPI and ensure that you understand the details of the protocol precisely. This will emerge as we
explore the details. In the absence of a firm specification I have taken the behavior of the SPI
232
modules in Freescale (formerly part of Motorola) microcontrollers as the definition of ideal SPI.
The data sheet for the MC9S08GB60 is particularly clear. The concept of SPI is shown in Figure
for the minimal system of two devices. I chose a particular configuration for the interface
and explain the myriad options later. One device is the master and the other the slave.
The master provides the clock for both devices and a signal to select (enable) the slave,
but the path followed by the data is identical in each. In its full form SPI requires four
wires (plus ground, which is essential but never counted) and transmits data
simultaneously in both directions (full duplex) between two devices. Motorola’s
nomenclature for the two data connections is “master in, slave out” (MISO) and “master
out, slave in” (MOSI). This is admirably clear and makes the functions

unambiguous. The two MISO pins should be connected together and likewise the two MOSI
pins. Other terms are widely used, such as SDI, SI, or DIN for serial data in and SDO, SO, or
DOUT for serial data out. In this case you connect an input on one device to an output on the
other. There is similar variety in the names for the clock signal including SCLK (most popular),
SPSCK, and SCK. The final signal selects the slave. This is usually active low and labeled SS for
slave select (Motorola), CS for chip select, or CE for chip enable. A slave should drive its output
only when SS is active; the output should float at other times in case another slave is selected. In
some modes of SPI, the first bit should be placed on the output when SS becomes active to start a
new transfer. The concept of SPI is based on two shift registers, one in each device, which are
connected to form a loop. The registers usually hold 8 bits. Each device places a new bit on its
output from the most significant bit (msb) of the shift register when the clock has a negative edge
233
and reads its input into the lsb of the shift register on a positive edge of the clock. Thus a bit is
transferred in each direction during each clock cycle. After eight cycles the contents of the shift
registers have been exchanged and the transfer is complete. Transmission and reception are
clearly inseparable: You cannot do one without the other, at least in principle. Thus a byte must
be transmitted in order to receive a byte. One byte is the most common length of a transfer but
any number of bits can be transmitted and a word of 16 bits is natural with the MSP430. Many
data converters also use SPI with 16-bit transfers. The JTAG interface, which is used to program
and debug the MSP430, is based on SPI and transfers thousands of bits. Data are transferred in
both directions with the full SPI but many systems do not use the complete interface. For
example, an external DAC configured as an SPI slave may never need to return digital data to a
microcontroller so there is no need for the MISO connection. However, the same steps always
take place internally: The only difference is that the output of the DACs shift register never
leaves the chip. This contrasts with asynchronous communication, where transmission and
reception are independent. The SS line can sometimes be omitted if only two devices are
connected, in which case the slave’s SS pin should be tied to ground so that it is enabled
permanently. This is not always permitted, depending on the function of SS. Reading and writing
are triggered by edges of the clock and the timing is usually straightforward. The clock need not
have a particular frequency and nothing goes wrong if different cycles vary in duration, provided
that minimum setup and hold times are observed. These are usually so short that the MSP430 has
trouble violating them. An exception to this rule is the time between SS becoming active and the
first clock transition. The reason is that SS often has more significance than merely the start of
transmission: It may stimulate a new conversion in an ADC, for instance. Another reason for the
SS signal is that the clock alone does not provide quite enough time points for a complete
transaction. Supposed that we wanted to send only a single bit. This requires three steps:
1. Put data on output.
2. Read data from input.
3. Remove data from output.
A single cycle of the clock provides stimuli for only two of these so the third is taken from SS. It
can either start or end the transmission and this option is specified by the clock phase bit, CPHA
in Motorola’s notation:

234
CPHA = 0: A transition on SS starts the transaction and causes the first bit of data to be placed
on the outputs. The inputs are read and clocked into the shift register on the leading (first) edge
of the first clock pulse. The second bit is put on the output at the trailing (second) edge of the
first clock pulse and this continues until the last bit is read on the leading edge of the last clock
pulse. The outputs are removed after the trailing edge of the last clock pulse or when SS becomes
inactive. In summary, data are
Read on the leading edge of each clock pulse.
Written on the trailing edge of each clock pulse.

It is essential that SS goes inactive between transfers because the first output is stimulated by SS
becoming active.
CPHA = 1: The first bit of data is placed on the output following the leading edge of the first
clock pulse. It is read on the trailing edge of the pulse. This continues until the last bit has been
read on the trailing edge of the last clock pulse. Thus data are
Written on the leading edge of each clock pulse.
Read on the trailing edge of each clock pulse.
The outputs are removed when SS becomes inactive. Thus SS is needed only to control when the
slave should drive its output, not to provide any timing. If there is only one slave, whose output
can remain active at all times, the SS signal need not be used. Thus CPHA controls whether
writing and reading take place on the leading and trailing edges of the clock pulses or vice versa.
This is the first of many options that control the configuration of SPI. A related option is the
clock polarity, selected with the CPOL bit:
CPOL = 0: Clock idles low between transfers.
CPOL = 1: Clock idles high between transfers.
There is no fundamental difference between these two polarities: One is just the complement of
the other. Combinations of the two bits CPOL and CPHA give four standard modes for the clock
in SPI, which are listed in Table 10.1. Modes 0 and 3 seem to be the most widely used. The data
are read on rising edges and written on falling edges in both of these, which is consistent with
Figure 10.1. Warning: Motorola’s notation CPHA and CPOL is used almost universally but not
in the documents for the MSP430. The user’s guides use the following names instead:

235
CKPL = CPOL for the polarity.
CKPH = CPHA for the phase, which is inverted.
Table 10.1: The four standard modes
for the clock in SPI.

The second definition is a particular nuisance because of the inversion. The user’s guides also
use SIMO and SOMI instead of MOSI and MISO, which is quaint but less troublesome. Figures
and 10.3 illustrate complete waveforms for a 4-bit transfer in modes 0 and 3. These show
the different relations between the clock and SS. In both cases SS becomes active one
half cycle before the first edge on the clock and is released to the inactive level one half
cycle after the last edge on the clock. The slave may show spurious data on its

236
output at either the start or end of the transmission, shown by the “?”, but there are no rising
edges that would cause these values to be read so they have no practical impact. I mentioned
earlier that the output from the slave (MISO) goes to a high-impedance state when SS is inactive.
This is shown by the “floating” level on the diagrams. It is not important if only two devices are
connected but becomes vital if more than one slave shares a bus. That is not the end of the
options. Here are two more. You can see why it is important to study the data sheet to check the
format used by a device.
The data in SPI are usually shifted with the most significant bit (msb) first but it can be the
other way; the bidirectional three-wire variant uses lsb first.

237
The slave select signal (or whatever it is called for the particular device) is usually active low
but occasionally active high.
Some devices use extra signals. There may be read/write lines for memories, “start conversion”
for ADCs, interrupts, alerts, and so on. I described how SPI is used to connect a single slave to a
master. It is not really a bus because it lacks protocols to control and acknowledge transactions
but can be extended to handle more than one slave. There are two ways of doing this, shown in
Figure 10.4.

In both cases the master provides the clock to all the slaves. Slaves can be addressed individually
in the first configuration. All the MOSI pins are connected together, as are the MISO pins, but
each slave’s SS pin is connected to a separate pin on the master. Slaves must ignore data on
MOSI when their SS pin is idle, despite the activity on the clock, and must leave their MISO pins
in a high-impedance state. In other words, the MISO pins must have three-state outputs. The
alternative is to connect all the devices in a “daisy chain,” as shown in Figure 10.4(b). In this
configuration the MOSI pins are not all connected together, nor the MISO pins, but rather the
MISO pin of a slave is connected to the MOSI pin of the next slave in the chain. The MOSI pin
of of the final slave is connected to MOSI on the master. Effectively all the shift registers inside
each device are connected into a single, long loop. In principle the master needs to contain a shift
register whose length is the sum of the lengths of the registers in all the slaves but in practice this

238
is mimicked in software. The slaves must allow data to be clocked through them transparently
while SS is held active and react to the new data only when SS is released. It is not possible to
update an individual slave; data must be written to the complete chain. JTAG works like this and
discrete shift registers are often daisy-chained to form a large input/output port. SPI is sometimes
called a four-wire bus. You may also encounter Microwire, which is a similar interface
introduced by National Semiconductor. It is also based on the concept of a shift register but only
one data line is active at a time—it is not full-duplex. A disadvantage of SPI is that it uses four
precious pins and a three-wire bus is sometimes used to save a pin. Usually this means that the
two lines for data, MOSI and MISO, are multiplexed onto a single, bidirectional line for serial
data (SDA). This abandons the full-duplex nature of SPI and a protocol is needed to ensure that
the master and slave do not attempt to transmit simultaneously. The clock usually uses mode 0
and data are transmitted with the lsb first. Having said that, the term three-wire is also used to
describe SPI without the SS line, which is entirely different. The MSP430 user’s guides employ
three-wire or three-pin SPI in this sense. SPI is straightforward and easy to use, once you are
sure of the configuration, because there are no complicated protocols to observe. A disadvantage
is that there is no built-in acknowledgment unless the master checks the data returned by the
slave. It is fast because the data and clock lines are always driven actively, unlike I²C, and can
run at tens of megahertz (but not on a MSP430). The clock does not need a precise or stable
frequency because everything is triggered by edges. It rapidly becomes clumsy for multiple
slaves but is the simplest serial interface for connecting a single device to a microcontroller.
Many devices are available in versions with either an SPI or an I²C interface but SPI is preferred
when large volumes of data must be transferred. Examples of this include
Large memories, particularly removable flash memory such as MultiMedia or Secure Digital
cards. See the application note Interfacing the MSP430 with MMC/SD Flash Memory Cards
(slaa281).
Graphical displays, such as some LCDs.
Interfaces to fast networks such as ethernet, CAN, and USB.
As an opposite example, SPI can also be used to connect simple shift registers such as the
74HC164 or ’165 to the MSP430. This is an economical way of adding extra input and output
pins and is illustrated in the code examples. The simplicity of SPI makes it straightforward to bit-

239
bang a master and the application note Implementing a Direct Thermocouple Interface with
MSP430x4xx and ADS1240 (slaa125) illustrates this for a sigma–delta ADC that uses SPI. A
slave is a little more difficult and speed may be a serious problem.
ASYNCHRONOUS SERIAL COMMUNICATION
A decade ago, every personal computer had serial ports to connect extra equipment such as
keyboards, mice, and modems. They have now been displaced by the universal serial bus in
consumer applications but old-fashioned serial communication remains popular for connecting
embedded systems. The main reason is simplicity. Asynchronous serial communication can be
managed in hardware by a peripheral called a universal asynchronous receiver/transmitter, which
is not complicated and is therefore built into many microcontrollers. Even if this is not available,
it can be emulated with a timer assisted by software. USB is much more difficult to handle. In
practice it is not a big problem to use an asynchronous serial link to a personal computer because
USB–serial converters are readily available. They provide “virtual COM ports” underWindows,
which appear much like the real hardware on older machines. There is an abundance of
information on this and other aspects of serial ports in Axelson’s book [55]. This was recently
updated to a second edition, which shows the enduring nature of the serial port. Asynchronous
serial communication usually requires only a single wire for each direction plus a common
ground. Most general-purpose connections are full duplex, meaning that data can be sent
simultaneously in both directions. These act independently, unlike SPI. There are usually no
further control lines, nor is there anything like the protocol required to run a I²C bus; characters
are simply sent when required. It really is straightforward, which explains its continuing
popularity. Issues such as the detection and correction of errors are usually handled by the
application that supervises the communication. For example, a block of data may be followed by
a checksum to confirm that it has been received correctly. Asynchronous links usually connect
only two pieces of equipment but a few buses use asynchronous communication.
Format of Data for Asynchronous Transmission
I described the usual format of asynchronous data in the section “Operation of Timer_A in the
Sampling Mode” on page 352. Data are sent in short frames, each of which typically contains a
single byte. Two examples are shown in Figure 10.18. The line idles high and each frame
contains
240
One low start bit (ST).
Eight data bits, usually lsb first.
One high stop bit (SP).
The bits are either high or low and have no gaps between them, a format known as non-return to
zero (NRZ). They are usually sent with lsb first, which is the reverse order compared with I²C or
the usual sequence on SPI. The format of the frame is called 8-N-1 because there are 8 bits of
data, no parity bit, and 1 stop bit. You may occasionally encounter other formats. For example,
the basic ASCII code has only 128 values so 7 bits of data were often sent in the past. The eighth
bit was sometimes used for parity as a simple check for errors in transmission. Aparity bit may
also be added to 8-bit data and the MSP430 bootstrap loader uses this format.
A minimum of 1 stop bit is needed to separate each frame and provide a high level before the
falling edge of the next stop bit. Slower systems may specify more stop bits, often 1.5 or 2, so
that they can keep up with the flow of data but this is now rare. The baud rate gives the
frequency at which bits are transmitted on the line. It is the inverse of the bit period and the name
is used to distinguish it from the rate at which useful data

are communicated. Each 8 bits of data are accompanied by a start and stop bit so the maximum
data rate is only 8/10 of the baud rate. A common speed for embedded systems is 9600 baud but
both higher and lower rates are also used. No clock is transmitted in asynchronous
communication so the transmitter and receiver must run independently at nearly the same baud
rates. How close do they have to be? Here is a reminder of the basic procedure for receiving a
frame in a UART, which was sketched in Figure 8.15.
1. Start timing at the falling edge that begins a start bit.
2. Sample the input after half a bit period to confirm a valid start bit.
3. Sample the input after a further complete bit period to read the first bit (lsb).
4. Repeat this until all 8 bits have been received, finishing with the msb.
241
5. Wait a further bit period and check that the input is high as expected for the stop bit. A
framing error occurs if this bit is low.
The final sample is taken 9½ bit periods after the initial falling edge and must lie within the stop
bit. The permissible error is therefore about ±0.5 bit period in 9.5 periods or ±5%. The baud rates
of the receiver and transmitter must be the same within this tolerance. There may be errors in
both rates, which add together in the worst case, so each should be accurate to within about ±2%.
Figure 10.18 shows 2 bytes, one of which is easy to receive and the other is difficult. The first
carries the value 0x55 (lsb first), which gives the maximum number of transitions within the
frame. An advanced receiver can resynchronize to these transitions, which makes it easy to
match the frequency of the transmitter. In fact a byte of 0x55 is used in a local interconnect
network so that a receiver can synchronize its clock to that of the transmitter. I say a little about
LIN later. In contrast, the byte of 0xFF has no transitions at all after the rising edge of the start
bit. The receiver is on its own and accurate frequencies in the UARTs are essential. It is often
awkward to generate accurate frequencies that match standard baud rates. We might like to use
ACLK at 32 KHz from a crystal as a reference, for instance. Unfortunately 32K/9600 = 3.41 so
simple division of ACLK does not work for 9600 baud. The USCI_A includes features to get
around this problem as we see in the next section. A crystal with a special frequency may be
needed for very high baud rates, where division of MCLK or ACLK is inaccurate.

242
The clock in the receiver must run faster than the baud rate so that it can start timing promptly
when a falling edge arrives to signal a new frame. This is because the start bit can arrive at any
time, with no relation to the clock inside the receiver. Typically the receiver uses a clock at 16
times the baud rate, which is illustrated in Figure 10.19. The frequency of the bit clock is the
same as the baud rate and this clock is started when a falling edge at the beginning of a start bit is
detected. This edge may have occurred at any time during the preceding cycle of the sampling
clock so there is a synchronization error of up to ½ a period of the sampling clock. The input is
sampled half-way through the bit. Only one sample is needed in principle but most UARTs take
more to reduce the impact of noise, which may cause brief incorrect values. Often three samples
are used, separated by periods of the sampling clock. Ideally all three values should be the same.
If they differ, the value shared by two is taken and the different, single value is rejected (there are
only two possible values). This is called a majority vote. Sometimes a noise flag is set if the
majority vote is needed. The exact position of the samples relative to the start of the bit depends
on the synchronization error and I have shown the signals for the two extreme cases in Figure
10.19. In both cases all the sampling points are well inside the bit and it should be received
correctly. Suppose that the clock in the receiver runs at twice the baud rate.Would this work, if
you allow for the different times at which the falling edge of the start bit may arise? If it does
work, how accurate would the frequency need to be? Only one nonstandard frame is commonly
used in asynchronous communication. This is the break character, which is a sequence of 10 or
more low bits. The length is chosen so that it cannot be mistaken for a valid byte: A byte of 0x00
contains a 0 start bit and 8 data bits of 0, giving 9 bits of 0, but the next bit is the stop bit of 1. A
break is typically used to gain attention in the same way as an interrupt. It starts a LIN
transaction, for example.
The bootstrap loader that is built into most variants of the MSP430 uses half-duplex,
asynchronous serial communication. Each character contains 8 data bits and an even parity bit.
Transmission starts at 9600 baud but this can be raised to increase the speed of programming.
Details are in the application notes Features of the MSP430 Bootstrap Loader (slaa089) and
Application of Bootstrap Loader in MSP430 with Flash Hardware, Software Proposal (slaa096).
Interface Standards and RS-232

243
Sometimes you can connect two devices directly for asynchronous communication, which may
be called TTL RS-232. The signal voltages are close to VSS for 0 and VCC for 1 as for SPI and
I²C. This works correctly provided that both devices run from the same supply voltage or are at
least compatible. However, asynchronous communication is usually used between separate
pieces of equipment. In this case the connection must obey established standards and be
protected against common faults. Therefore an interface is needed between the UART in the
microcontroller and the outside world. This is where RS-232 comes in.
RS-232 is an ancient standard, originally intended for connecting equipment such as a teletype
(data terminal equipment) to a modem (data communication equipment). For many years it was
officially RS-232-C, published in 1969, but the current version is ANSI/TIA/EIA-232-F, which
is maintained by the Telecommunication Industry Association. I am lazy and continue to call it
RS-232. RS-232 specifies the following voltages for the signals, which may come as an
unpleasant surprise:
 Logical 1 is represented by a voltage between −15 V and −3 V. This is also called mark.
 Logical 0 is represented by a voltage between +3 V and +15 V, also called space.
 The crossover region between ±3 V does not correspond to valid data.
 Connections must be resistant to short circuits and to voltages of ±25 V.
Clearly this presents problems for the MSP430, whose natural range of voltages lies wholly
within the crossover region. The original recommendation was for signals to be at ±12 V but
many systems now use lower voltages, often ±5 V. This is closer to the voltages used for digital
electronics but the negative voltage is problematic. External circuits for a transmitter and
receiver or transceiver are therefore needed to connect the MSP430 or any other microcontroller
to an RS-232 port. There are several ways in which they can be implemented:
Special transceiver ICs are available that generate the voltages needed for RS-232
transmission and provide interfaces between the external and internal signals, including isolation
and protection. Perhaps the best known family is the MAX232 and descendants. The original
MAX232 was intended for 5V systems but newer devices work from lower voltages. Typically
they include charge pumps to produce voltages of ±2VCC, which provide the RS-232 levels.
Three or four capacitors are needed for the charge pumps, which is a painless way of gaining the
extra voltage. The SoftBaugh demonstration board shown in Figure 3.3 includes a

244
MAX3221 for its RS-232 interface.
If this is too expensive, numerous simple circuits use a couple of transistors and a few
passive components for the receiver and transmitter. They “steal” the voltage needed for RS-232
from the line driven by the other transmitter, which must therefore come from a full-strength
port. This should be true for a computer but not necessarily for another embedded system—two
thieves cannot steal the voltage from each other. This approach is used in the Olimex 1121STK.
An opto-isolator can be used to provide greater separation between the microcontroller
and the RS-232 circuits. The input to the opto-isolator drives an
LED, which shines onto a phototransistor that provides the output. Thus there is no electrical
connection between the two sides. The TI MSP430FG4618/F2013 Experimenter’s Board has an
opto-isolated RS-232 connection. Circuits are still needed to drive the lines and this board takes
its power from the other transmitter. There is no universally agreed physical connection for RS-
232 although many systems use the nine-way D-type connector introduced with the IBM PC/AT.
This offers plenty of pins beyond the two signals and ground needed for the data alone. The extra
wires were used to control the interface between the teletype and modem in the days when
equipment had trouble keeping up with a signal at 110 baud. They have names like Request to
Send and Clear to Send but are now rarely used for these purposes. Many systems ignore them
and others use them for nonstandard purposes. Axelson [55] explains how to deal with
equipment that needs the extra signals. Improvements and extensions to RS-232 have been made
over the years. A weakness of RS-232 is that it relies on single-ended signals, which means the
voltage between a single wire and ground. RS-422 uses balanced or differential signalling,
where the signal is the difference in voltage between a pair of wires. For example, the voltages
on the two lines might be (+3V, −3V) for a 0 and (−3V, +3V) for a 1. This enables reliable
communication over a longer distance than RS-232 or a higher baud rate at short distances. The
serial ports on the Apple Macintosh used RS-422 before the days of USB. Differential signaling,
is also employed in USB, CAN, and many other interfaces. Up to 10 receivers are permitted on
RS-422 but only a single transmitter. RS-485 is a further extension to multiple transmitters,
which makes the system into a bus. It is used in industrial control and other applications that
require long networks but do not demand great speed. Axelson [55] covers RS-485 as well and
the analog aspects are described in the application note 422 and 485 Standards Overview and

245
System Configurations (slla070). I already mentioned the local interconnect network. This is a
low-cost network based on standard asynchronous communication, which is designed so that
nodes do not need accurate clocks and crystals. Frames start with a break followed by a
synchronization byte of 0x55, which each receiver uses to match its baud rate to that of the
transmitter. The rest of the frame is a sequence of bytes sent in the usual asynchronous format. It
resembles a read or write transaction in I²C but includes a checksum. LIN was originally
intended for automotive applications, where it complements faster but more demanding buses
such as the controller area network, but has been adopted elsewhere because it needs little more
than a UART in each node. Full information is on the Web at www.lin-subbus.org.

A LOW-POWER BATTERY LESS WIRELESS TEMPERATURE AND HUMIDITY


SENSOR WITH PASSIVE LOW FREQUENCY RFID

Introduction
Several applications require hermetically sealed environments, where physical parameter
measurements such as temperature, humidity, or pressure are measured and, for several reasons,
a battery-less operation is required. In such applications, a wireless data and power transfer is
necessary. This application report shows how to implement an easy-to-use low-power wireless
humidity and temperature sensor comprising a SHT21 from Sensrion, a MSP430F2274
microcontroller, and a TMS37157 PaLFI (passive low-frequency interface). The complete power
for the wireless sensor and the MSP430F2274 is provided by the RFID base station (ADR2)
reader included in the eZ430-TMS37157 demo kit.
The application is divided in four steps:
• Charge phase: Generate an RF field of 134.2 kHz from the ADR2 reader to the wireless sensor
module to charge the power capacitor.
• Downlink phase: Send command or instruction to wireless sensor to start measurement.
• Measurement and recharge phase: Trigger measurement of temperature, recharge the power
capacitor on the sensor device, and trigger humidity measurement.
• Uplink phase: Send measurement results via RF interface (134.2 kHz) back to ADR2 reader.
Hardware Description
Device Specifications

246
MSP430F2274
The MSP430F2274 is a 16-bit microcontroller from the 2xx family of the ultra-low-power
MSP430™ family of devices from Texas Instruments.[2] The supply voltage for this
microcontroller ranges from 1.8 V to 3.6 V. The MCU is capable of operating at frequencies up
to 16 MHz. It also has an internal very-low-power low-frequency oscillator (VLO) that operates
at 12 kHz at room temperature. It has two 16-bit timers (Timer_A and Timer_B), each with three
capture/compare registers. An integrated 10-bit analog-to-digital converter (ADC10) supports
conversion rates of up to 200 ksps. The current consumption of 0.7 mA during standby mode
(LPM3) and 250 mA during active mode makes it an excellent choice for battery-powered
applications.
TMS37157 PaLFI
The TMS37157 PaLFI is a dual interface passive RFID product from Texas Instruments. The
device can communicate via the RF and the SPI (wired) interfaces. It offers 121 bytes of
programmable EEPROM memory. The complete memory can be altered through the wireless
interface, if the communication/read distances between the reader antenna and the PaLFI antenna
are less than 10 cm to 30 cm (depending on the antenna geometry and reader power). For
wireless memory access, a battery supply is not required. A microcontroller with a SPI interface
has access to the entire memory through the 3-wire SPI interface of the TMS37157. In addition,
the TMS37157 can pass through received data from the wireless interface to the microcontroller
and send data from the microcontroller back over the wireless interface. If the TMS37157 is
connected to a battery, it offers a battery charge function and a battery check function without
waking the microcontroller. If connected to a battery, the TMS37157 has an ultralow power
consumption of about 60 nA in standby mode and about 70 μA in active mode. The PaLFI can
completely switch off the microcontroller, resulting in an ultralow power consumption of the
complete system. This application report does not cover this. Further information can be found in
the application report TMS37157 Passive Low-Frequency Interface IC Performance With Neosid
Antennas (SWRA382).
SHT21 Humidity and Temperature Sensor
The extremely small SHT21 digital humidity and temperature sensor integrates sensors,
calibration memory, and digital interface on 3x3 mm footprint. This results in cost savings,

247
because no additional components are need and no investments in calibration equipment or
process are necessary. One-chip integration allows for lowest power consumption, thus enabling
energy harvesting and passive RFID solutions. The complete over-molding of the sensor chip,
with the exception of the humidity sensor area, protects the reflow solderable sensor against
external impact and leads to an excellent long term stability.
About Sensirion
The Swiss sensor manufacturer Sensirion AG is a leading international supplier of CMOS-based
sensor components and systems. Its range of high-quality products includes humidity and
temperature sensors, mass flow meters and controllers, gas and liquid flow sensors, and
differential pressure sensors. Sensirion supports its international OEM customers with tailor-
made sensor system solutions for a wide variety of applications. Among others, they include
analytical instruments, consumer goods, and applications in the medical technology, automotive
and HVAC sectors. Sensirion products are distinguished by their use of patented CMOSens®
technology. This enables customers to benefit from intelligent system integration, including
calibration and digital interfaces. Contact: www.sensirion.com, support@sensirion.com, Tel. +41
44 306 40 00, Fax +41 44 306 40 30
Interfaces from MSP430F2274 to TMS37157 and SHT21
Interface Between MSP430F2274 and TMS37157 PaLFI
Figure 1 shows the interface between MSP430F2274 and TMS37157. The TMS37157 is
connected to the MSP430F2274 through a 3-wire SPI interface. To simplify communication
between the MSP430F2274 and TMS37157, the BUSY pin of the TMS37157 is connected to the
MSP430. The BUSY pin indicates the readiness of the TMS37157 to receive the next data byte
from the MSP430F2274. The PUSH pin is used to wake up the PaLFI from standby mode so that
the MSP430F2274 can access the EEPROM of the PaLFI. CLKAM is used for the antenna
automatic tune feature of the PaLFI target board.

248
Interface Between MSP430F2274 and SHT21
Figure 2 shows the interface between MSP430F2274 and SHT21. I2C is used to connect both
devices. The MSP430F2274 contains two communication modules. One is used as UART
connection to a host PC, the other one is used to communicate to the TMS37157. Therefore, the
I2C interface has been implemented completely in software.

Hardware Changes to Original PaLFI Board


Several changes were made to the standard PaLFI board to implement the wireless sensor
application. The most important change is to use an external DC/DC converter attached to VCL
to generate a VBAT/VCC voltage out of the 134.2-kHz RF field. Figure 3 shows the basic
principle of this circuit.

249
The input of the dc/dc converter TPS71433 is connected to VCL via diode D1. D1 prevents the
resonance circuit (consisting of LR and CR ) from any disturbances coming from the dc/dc
converter. Capacitor CBAT stores the energy derived from the RF field. Using an external dc/dc
converter instead of the internal of the TMS37157 overcomes two issues. The first advantage of
an external dc/dc converter is that it can provide higher output currents in comparison to the
internal regulator (80 mA compared to 5 mA). The second advantage using an external regulator
is the simpler flow for the application and the firmware (see Table 1).

250
251
2.4.2 Layout

4.4.5 Software and Firmware Description

252
This section describes the Windows GUI and the MSP430F2274 firmware used for this
application report. The Windows software used in this application report is based on the software
that is supplied with the eZ430-TMS37157. An additional tab was inserted to control the
wireless sensor application. Prior to using this application report, make sure that you have the
right firmware, corresponding to this application report, loaded onto your PaLFI Wireless Sensor
target board. The related software can be downloaded from http://www.ti.com/lit/zip/swra395.
Windows Software
Prior to using the Wireless Sensor tab, make sure that you have selected the correct COM port on
the Expert Mode tab (see Figure 6).
1. Go to the Expert Mode tab.
2. Connect the ADR2 reader to the PC, and click Refresh to view a list of available COM ports.
3. Select the COM port of the ADR2 reader.
In the Expert Mode tab, every free configurable user page of the PaLFI EEPROM can be read,
written, or locked.
Figure 6. Expert Mode Tab
8 A Low-Power Battery-Less Wireless Temperature and Humidity Sensor for the SWRA395–
November 2011 TI PaLFI Device

253
Figure 7 shows the PaLFI demo software of the eZ430-TMS37157 with active Wireless Sensor
tab. To start a single measurement, click Single. To start continuous measurements, click Loop.
To stop the measurements, click Stop. To clear the graph, click Reset.

254
MSP430F2274 Firmware
Use the zip file provided with this application report (http://www.ti.com/lit/zip/swra395) and
import the project either into a Code Composer Studio workspace or an IAR Embedded
Workbench workspace.
Program Flow
Figure 8 shows the main program flow for the firmware.

255
Figure 8. Main Program Flow of MSP430F2274 Software

256
After reset and initialization of the microcontroller (including ports, timers, SPI, and I2C), it
enables interrupts for the PUSH and BUSY pins. Then it enters LPM3, waiting for a PUSH
button interrupt or a BUSY interrupt.
A press on the PUSH button (see Figure 9) activates the PaLFI, reads the PCU state and page 2.
If page 2 is 0x00, the autotrim routine is executed to trim the resonance circuit of the PaLFI to
134.2 kHz (see Figure 11). If page 2 is 0x01, nothing is done, and the microcontroller returns to
LPM3. In case of a BUSY interrupt, an MSP Access Command is executed (see Figure 10). In
this case, the 6 bytes transmitted from the reader to TMS37157 are read via SPI command. This
is followed by temperature and humidity measurements.

257
Figure 9. PUSH Interrupt Service Routine

258
Figure 10. BUSY Interrupt Service Routine
259
Figure 11. Autotrim Routine

4 Application
Description of Analog Signals

260
Figure 12 shows the complete telegram of the application. The telegram includes the following
phases.
1. Charge Phase
2. Downlink Phase
3. Measurement Phase
4. Uplink Phase

Figure 12. Overview of Complete Telegram

Charge Phase
Figure 13 shows the charge up phase. During this phase the capacitors at VBAT and VCL are
charged. The blue line shows the linear rising VBAT voltage. During time period 1 VCL is
almost flat as the DC/DC regulator (TPS74133) drains the maximum available power out of the

261
RF field until voltage Uin is equal or higher than Uout (see Figure 14). Current consumption is
lower and VCL is rising again during time period 2. When the capacitors connected to VBAT are
charged, current consumption again decreases and VCL is charged to its end voltage of
approximately 6 V (time period 3).

Figure 13. Charge-Up Phase

262
Figure 14. UIN and UOUT Voltage at DC/DC Regulator

Downlink and Measurement Phase


Figure 15 shows the end of the downlink phase and the beginning of the measurement phase.
During downlink the reader sends commands (here the MSP Access command) amplitude
modulated to the PaLFI. Upon receive of a valid MSP Access command PaLFI is activated
indicated by setting VBATI (light blue line) to VBAT level. At the same time a short
BUSY=HIGH pulse is issued to wake the MSP430F2274 (see Figure 10). The ripples that can be
seen on the VCL voltage after rising VBATI are due to activating the MSP430F2274 and the
SHT21 and starting the measurement.

263
Figure 15. Downlink and Measurement Phase

Uplink Phase
Figure 16 shows the end of the measurement phase (time 1) and the uplink phase (3). At the end
of time period 1 measurement data is shifted from MSP430F2274 to TMS37157 via MSP Access
Data Out command. After finishing this command PaLFI is deactivated indicated by setting
VBATI=LOW. Switching off the reader causes the PaLFI to start the uplink. During this phase
the measurement results are sent to the ADR2 reader. At the end of the uplink phase a discharge
of the CL capacitor is performed to proper reset the device.

264
Figure 16. Uplink Phase

265
Functional Block Diagram
Figure 5-1 shows the functional block diagram of the CC3100 SimpleLink Wi-Fi solution

Wi-Fi Network Processor Subsystem


The Wi-Fi network processor subsystem includes a dedicated ARM MCU to completely offload
the host MCU along with an 802.11 b/g/n radio, baseband, and MAC with a powerful crypto
engine for a fast, secure WLAN and Internet connections with 256-bit encryption. The CC3100
device supports station, AP, and Wi-Fi Direct modes. The device also supports WPA2 personal
and enterprise security and WPS 2.0. The Wi-Fi network processor includes an embedded IPv4
TCP/IP stack.
Applications and Implementation
Application Information
Typical Application – CC3100 Wide-Voltage Mode
Figure 6-1 shows the schematics for an application using the CC3100 wide-voltage mode

266
PART A

1. Define serial communication


2. What is SPI
3. What is I2C
4. What is USB
5. What is Embedded Wi-Fi
6. Draw the architecture of Internet of Things

PART B

1. Write down the differences between serial and parallel communication


2. Explain the UART protocol and I2C protocol
267
3. Explain the concept of Serial Peripheral Interfacing
4. What are applications of Universal Serial Bus
5. Interface SPI with MSP 430
6. Write a program to interface USB with MSP 430
7. Using interface protocols interface humidity sensor with passive low
frequency RFID
8. Explain the architecture of Internet of Things
9. Give the concept of embedded Wi-Fi
10.Give the concept of Application programming Interfaces
11. Explain the user APIs for wireless and networking applications
12. Write about the applicability of embedded systems in wireless
communications

268

You might also like