You are on page 1of 138

INTRODUCTION

TO
MICROPROCESSORS

LECTURE NOTES
Gzde Bozda Akar
Cneyt F. Bazlamac
M. Mete Bulut
lkay Ulusoy
2012
Release v3.2
Middle East Technical University
Department of Electrical and Electronics Engineering

Contents
Chapter 1:
Microprocessor, Microcontroller and Programming Basics ..1
Chapter 2:
Programming Model, Addressing Modes and Instruction Set .14
Chapter 3:
Programming Examples ...22
Chapter 4:
The Stack, Subroutines, Interrupts and Resets .29
Chapter 5:
Clocked Operation, Bus Concepts, Address Decoding ...40
Chapter 6:
Interfacing Concepts ....51
Chapter 7:
Parallel Input/Output ....68
Chapter 8:
Serial Input/Output ...88
Chapter 9:
Analog to Digital Conversion ..98
Chapter 10:
Programmable Timer Subsystem ...110
Bibliography
.....125
Appendix:
M68HC11 Instruction Set ..127

Chapter 1
Microprocessor, Microcontroller and Programming Basics
Course objectives

to develop an in-depth understanding of


o the operation of microprocessors and microcontrollers
o machine language programming
o microprocessor interfacing techniques
to be able to use Motorola 68HC11 microcontroller competently
to be able to design and implement microprocessor-based systems in both hardware and
software
to be able to apply this knowledge to more advanced structures

Common computer organization


ALU (Arithmetic Logic Unit) is a circuitry, which is capable of doing various operations (for example
ADD, SHIFT, AND, OR, etc) on certain on-chip registers.
CPU (Central Processing Unit) is the combination of the control logic, associated registers and the
arithmetic logic unit.

Computer buses
Address bus: carries the address of a unique memory or input/output (I/O) device

Data bus: carries data stored in memory (or an I/O device) to the CPU or from the CPU to the
memory (or I/O device)
Control bus: is a collection of control signals that coordinate and synchronize the whole system

Block diagram of a typical CPU

CPU structure
The main functions are
data transfer
arithmetic and logic operations
decision making (instructional flow control)
The register array consists of at least one accumulator, program counter and stack pointer.
The control unit controls all the operations in a CPU and basically it puts the CPU in one of the fetch
and execution phases.

Memory
The memory in a computer system stores the data and instructions of the programs.

Main memory types

ROM (read-only memory)


o programmed permanently at the factory, cannot be altered

RAM (random-access memory)


o read and write memory

EPROM (erasable programmable ROM)


o nonvolatile, written electrically but erased optically

EEPROM (electrically ROM)


o nonvolatile, both written and erased electrically

Operation of the CPU

Fetch cycle (phase):


o The CPU puts the address of the instruction to be executed on the address bus. The
address information comes from the program counter (PC) maintained by the control
unit.
o The control bus holds the information for reading the memory location and the data
bus holds the instruction from the memory which is stored into the instruction register
(IR)
o PC is updated to point to the next instruction.
Execute cycle (phase):
o Instruction in the IR is decoded
o The required data transfer and the required logical and arithmetic operation are
performed
o The result is written back either to one of the registers or memory or I/O device
Common operations performed in ALU are:
o addition, subtraction,
o logical AND, OR, XOR, NOT
o increment, decrement, shift, clear, etc.

Microcomputer
o
o
o
o
o
o
o

CPU on a single IC
microprocessor (P).
The terms CPU, P and MPU (microprocessor unit) are synonymous
CPU is the combination of the ALU and control unit of any computer.
When the CPU is a single IC; it is called a P and is also referred to as the MPU.
When the MPU is connected to memory and I/O, the arrangement becomes a
MICROCOMPUTER.
Many different MPUs are produced by many different IC vendors (e.g., Motorola, Intel,
Texas Instruments, Zilog, National Semiconductors, etc.).
Major differences are in
o word size,
o the number and types of instructions that can be performed,
o the types of external control signals available,
o the amount of memory that can be addressed.

Microcontroller
o
o
o

A microcontroller unit (MCU) contains an MPU, memory, and I/O circuitry on a single chip.
Such a chip can perform control operations without the need for any external circuitry.
e.g. Motorola MC68HC11 (also a microprocessor in the expanded multiplexed mode)e.g.
Intel 8051

Microprocessors vs microcontrollers
o

Microprocessors: high performance, general purpose brains for PCs and workstations
o Instruction decode and control, arithmetic/logic operations, registers, timing, external
control
o Typical cost: $75 -- $500, Annual demand: 10s of millions
Microcontrollers: devices with high levels of integration for embedded control
o Microprocessor functions plus on-chip memory and peripheral functions (e.g. ports,
timers)
o "Swiss army knife" of microprocessor technology
o Typical cost: $1-- $25, Annual demand: billions!

o
Microprocessor
o Includes memory management unit, lots of cache
o Performance is the most important feature (cost is important, but secondary)
o Used mainly in desktop machines
Microcontroller
o Integrated RAM and ROM, no cache
o Includes lots of peripherals
o Used mainly in embedded applications and often involves real-time control
o Important features include: low cost, low power consumption, number of integrated
peripherals, interrupt response time, amount of RAM and ROM

Bottom-up view of microcontroller systems

Microcontroller applications
o
o
o
o
o
o
o
o
o
o
o
o
o

Pocket pagers (low-power, interprets characters, user interface)


Cameras (low-power, exposure and focus control, user interface)
"Levelmeter (measures angle, audible and visual user interface)
Keyboard controllers (scanning, debounce, autorepeat, diagnostics)
Modems (one for data transmission, on for command processing)
Plotters (command interpretation, encoders, motor control)
Color copiers (paper positioning, color exposure, sensors)
Charge card pay phones (card reading, dialing, carrier access)
Lawn sprinkler controller (timer, valve control, user interface)
Instrumentation (user interface, GPIB interface, compute values)
Closed-loop engine control (fuel/air mixture, ignition, pressure sensing, etc.)
Antilock braking system control (monitors traction, controls brake)
Dynamic ride control (adjusts suspension)

Block Diagram of a Motorola M68HC11 Based Applications Example: An Emergency


Control System

Comparison of some popular microcontrollers

Motorola HC11
The HC11 family includes a large number of variations, ranging from single-chips to
larger micros with bank-switching support.
Motorola HC12

The HC12 family is the next step up from the HC11, offering better performance, better
memory management, and more features.
Motorola 6805
The 6805 family is the next step down from the HC11, with more single-chip variations,
smaller packages, and lower cost.
Microchip PIC
The devices are readily available, reasonably priced, very fast, and come in lots of
variations, however, with small memory maps and poor support for compilers.
Intel 8051
The 8051 was one of the first microcontroller families, and remains one of the most
commonly used. The devices are available from multiple sources, are cheap, have decent
tools, and offer a nice upgrade path to larger and more capable part.

What is EE447 about?

MC68HC11 is the MPU choice in EE447


You will be studying
o how it is combined with memory and I/O devices to produce a 68HC11 based
microcomputer, and
o how it is programmed to perform various operations
Most of what you learn about the 68HC11 can be applied to any other MPU or
microcomputer you may encounter later.

Major features of Motorola M68HC11

HCMOS Technology (low power / high speed)


On- chip RAM, ROM, EEPROM
Basic core functions of MC6801 improved instruction set functionality
2 operating modes and 2 test modes
On-chip counter / timer
On-chip analog- to- digital conversion
On-chip parallel and serial ports
Improved interrupt capabilities than earlier products -- supports 21 interrupt vectors
Some fault detection capability for major errors (power, illegal instruction, hung processor)
Available in at least 25 different versions
o Different pin counts and packaging
o Different amounts/ types of memory
RAM size (192 to 1.25K bytes)
ROM size (4K to 32K bytes)
EEPROM (512 to 2K bytes)
ROM, EPROM, or EEPROM program memory
Memory maps vary from version to version!
o Different I/ O capabilities (number of timers, chip selects, DMA channels, A/ D
types, etc.)

Modes of operation
2 operating modes and 2 test modes
Operating modes

Single chip
o No external address and data bus functions

CPU can only access on-chip memory


Ports B and C are general purpose parallel I/ O
All software needed to control MCU must be in internal memory
On reset, execution begins at address $E000
Located in ROM
Expanded multiplexed
o External memory and peripheral devices can be accessed by time-multiplexed
address- data bus
o Port B used for high byte of address (output)
o Port C provides low byte of address (output) and 8-bit data (bi-directional)
o External address latch is required
o Execution begins at address $E000
o
o
o

Single chip mode

Expanded multiplexed mode

Test modes

Special bootstrap
o On power up or reset, the program in the bootstrap ROM is executed
o CPU waits for a 256-byte program segment to be downloaded through the serial link
and stored starting at address $0000
o Execution then begins at address $0000
o Permits wide variety of programs to be downloaded
Special test
o Primarily a testing mode for the manufacturer
o Overrides some automatic protection mechanisms -- risky!

I/O Ports
o
o
o
o
o

Port A (8 bits)
o Also used for timer
Port D (6 bits)
o Also used for asynchronous (SCI) and synchronous serial (SPI) I/O
Port E (8 bits)
o Also used for A/D converter
Port B (8 bits)
o Also used as address in expanded mode
Port C (8 bits)
o Also used as data/ address in expanded mode

MC68HC11 detailed block diagram

Programming languages
o

Application programs
o User runs an existing software package, Limited flexibility outside intended
application
o Examples: Excel, Netscape, Word, . . .

High-level language (HLL)


o User writes programs to perform task(s)
o Very flexible, easy to use (once language is learned!)
o Examples: C, C++, Java, Fortran

Assembly language
o Harder to use than HLLs
o Machine and configuration dependent
o Requires detailed knowledge of the P itself and its instruction set
o Still used where extremely high performance, short programs are required

Machine code
o Native language of the processor itself
o Programs are the actual bytes as stored in memory
o Not intended for human consumption

Programming procedure

What features of the processor are most important to the assembly-language


programmer?
o
o
o
o

Register set
Memory organization
Instruction set
Addressing modes

10

Register set

Memory Organization
o

On chip memory
o ROM (12K bytes)
Factory programmed, Special bootstrap ROM
o RAM (512 bytes)
Data, stack
Can be used for downloaded code
Low-power standby mode
o EEPROM (512 bytes)
Programmed and erased on-chip
Calibration storage, diagnostic log, critical data logging, security data
Can also be used for downloaded code
Off-chip memory
o EPROM
For prototype development
Windowed and one-time programmable versions

11

Instruction set
o
o

o
o

The instruction set specifies the kinds of data transfers and transformations that can occur in
the machine
Instructions can be grouped into 5 broad categories
o Data transfers: instructions that move data to and between registers
o Logical: instructions that perform logic operations on data -- AND, OR, etc.
o Arithmetic: addition, subtraction, increment, etc.
o Flow control: instructions that change the sequence of execution of a program -conditional and unconditional branches, stack operations, etc.
o Input / Output operations
An instruction generally consists of an opcode and some operand(s)
HC11 instructions are of different lengths (1-5 bytes)

Opcodes
1-byte opcodes
o Most opcodes use just 1 byte
o Downward compatible with 6800
2-byte opcodes
o Most 2- byte instructions deal with register Y, which was not present in the 6800
processor
o It takes longer to fetch and execute 2- byte opcodes
o New instructions use a "pre- byte", which signals that another opcode byte follows:
$18, $1A, or $CD
o Ex:
INX $08
INY $18 $08
Instruction format
o
o
o
o

An instruction is made up of an opcode and a set of operands


o Opcode may be one or two bytes
o Instructions may use 0, 1, 2, or 3 operands
Operands may be 1 or 2 bytes
Instruction lengths range from 1 to 5 bytes
Example (assume this is stored at address $E000):
LDAA #$ FF; load ACCA with the value $FF

12

Machine code:
$E000 $86
$E001 $FF

Fetch/execute operation

Addressing modes
An instruction specifies the location of the data that it is going to process by using one of the existing
addressing modes. M68HC11 has the following six different addressing modes, which are discussed
in detail in Chapter 2:
o
o
o
o
o
o

Inherent addressing
Immediate addressing
Extended addressing
Direct addressing
Indexed addressing
Relative addressing

13

Chapter 2
Programming Model, Addressing Modes and Instruction Set
An assembly language programmer should at least be familiar with the following features of the
processor:

Register set
Instruction set
Addressing modes
Memory organization

CPU Registers
An MPUs programming model shows only those internal registers that the programmer can directly
control via the MPUs instruction set.

Programming Model of the 68HC11


Accumulators A,B and D:
- There are two 8-bit accumulators (ACCA and ACCB)
- Each may be a source or destination operand for 8-bit instructions.
- ACCD is the concatenation of A and B and instructions that modify ACCD actually modify
ACCA and ACCB.
e.g.

LSLA

b7 .....................b0

ACCA

LSLD

b7 .....................b0
ACCA

14

b7 .....................b0
ACCB

Index registers X and Y: The two 16-bit index registers are used primarily for indexed addressing
(will be studied in addressing modes). There are also some arithmetic instructions involving
the index registers.
e.g. INX (increments the contents of index register X, i.e., (IX) (IX)+$0001)
Stack pointer (SP): The 16-bit stack pointer maintains a program stack (will be studied later in detail)
in RAM and must be initialized to point to RAM area before use.
Program counter (PC): Although it is shown in the programming model, the programmer does not
have direct control over it like the other registers. It is usually given to show the amount of
memory that can be directly addressed by the processor (the number of bits in the PC indicate
the address range).
Condition code register (CCR): The 8-bit condition code register consists of individual bits, called
flags, with different meanings. Each flag is used to indicate the status of a particular MPU
condition and the logic value of the flags can be examined under program control to
determine what sequence of instruction to follow. The flags in CCR are carry, overflow, zero,
negative, interrup mask, half-carry, X-interrupt mask and stop disable.
e.g. Zero flag indicates whether the result of the previous operation is zero or not
CLRA instructions clears ACCA and sets the zero (Z) flag.

Instruction Set
An MPU instruction usually has two parts, the opcode and the operand.
-

the opcode tells the CPU what operation to perform


the operand tells the CPU what data to operate on
e.g.

86 5A (LDAA #$5A in assembly language)

opcode

operand

In 8-bit microprocessors, the instructions usually have one-byte opcodes but in 68HC11 there are also
two byte opcodes (called the prebyte system) for increasing the number of possible instructions
(because of having an additional 16-bit IY register).
e.g.,

instruction
increment X
increment Y

mnemonic
INX
INY

machine code
$08
$18 $08

operation
(IX) (IX)+$0001
(IY) (IY)+$0001

Addressing Modes
An addressing mode specifies how to find/locate the data. The addressing modes available for the
68HC11 are; inherent, immediate, direct, extended, indexed and relative modes.
Inherent addressing mode: used by instructions that do not need to access memory or I/O addresses
(since all data for the instruction is within the CPU).
The operand is obvious from the instruction mnemonic (assembly language representation).
e.g.,

instruction
clear ACCA

mnemonic
CLRA

machine code
$4F

15

operation
(A) $00

increment X
set carry flag
add B to A
transfer A to B

INX
SEC
ABA
TAB

$08
$0D
$1B
$16

(IX) (IX)+$0001
C1
(A) (A)+(B)
(B) (A)

Immediate addressing mode: actual data follows the opcode.


- used to initialize the registers with constants known at the time the program is written
- requires a # prefix in the assembly language
- can have both 8 or 16-bit operands
e.g.,

instruction
load Acc.A with 64
load Acc.A with $64
add Acc.B $02
load X with #$01FF

mnemonic
LDAA #64
LDAA #$64
ADDB #$02
LDX #$01FF

machine code
$86 $40
$86 $64
$CB $02
$CE $01 $FF

operation
(A) $40 (decimal 64)
(A) $64 (hexadecimal 64)
(B) (B)+$02
(IXHIGH) $01, (IXLOW) $FF

Direct addressing mode (also known as base-page addressing mode): single-byte data following the
opcode is not the actual data but the address of the operand.
- 2 byte instructions (one byte opcode + one byte address) enables one to address only the first 256
locations between $00 and $FF (base-page)
e.g.,

memory location
$E000
$E001
:
$0064

machine code
$96
$64

mnemonic
LDAA $64

operation
(A) ($64)

$C5

When executed ACCA contains $C5


The above instruction is executed as follows:
-

PC contains the $E000 (the address of the location where the opcode is stored).
The opcode $96 is fetched from memory first.
The instruction is then decoded as a direct mode one and another byte is read from the memory
loc. $E001 as the address of the operand.
When the address information $64 is read from the memory, full address information $0064 is
formed in the memory address register.
Another memory read operation is performed from the address location $0064.
The contents of the corresponding location, i.e, $C5, is then stored in ACCA.

Extended addressing mode: similar to direct addressing but uses two bytes as the address of the
operand
- 3 byte instructions (one byte opcode + two bytes address) enables one to address the entire
64Kbyte (216 = 65,536 = 64K) address space between $0000 and $FFFF.
e.g.,

memory location
$E000
$E001
$E002
:
$6400

machine code
$B6
$64
$00

mnemonic
LDAA $6400

$F5

When executed ACCA contains $F5.

16

operation
(A) ($6400)

e.g.,

memory location
$0000

machine code ($)


FC 12 34

$0003

FF 12 34

:
$1234
$1235

$F5
$00

mnemonic
operation
LDD $1234
ACCD ($1234:$1235)
{ ACCA ($1234), ACCB ($1235) }
STX $1234
($1234:$1235) IX
{ ($1234) IXHIGH, ($1235) IXLOW) }

When executed with


ACCA=$FF, ACCB=$FF and IX=$2345,
the register and memory contents will change as follows
ACCA=$F5, ACCB=$00, IX=$2345, ($1234)=$23, ($1235)=$45
Indexed addressing mode: makes it easy to handle tables and blocks of data in memory.
- an indexed instruction format is as follows:
Operation

(e.g. LDAA $05,X)

Offset, Index_register

where Offset is an unsigned 8-bit value and Index_register is either X or Y.


-

the effective address of the operand in indexed mode is calculated by the CPU as the sum of the
offset and the contents of the IX or IY register. i.e.,
operand address = (IX) + offset

e.g.,

machine code ($)


A6 05

opcode

or

operand address = (IY) + offset

mnemonic
LDAA $05,X

comment
effective address = (IX) + $05

offset

if (IX) = $C500 then the effective address (address of the operand) is $C505 and
A ($C505)
Contents of memory location $C505 is loaded into ACCA
Examples:

17

Relative addressing mode: is used for branch instructions.


- Branch instructions often do not jump very far from the current location.
- M68HC11 branch instructions use relative addressing while jump instructions use extended
addressing.
- a relative addressing mode instruction adds the offset to PC to find the address of the next
instruction to execute.
e.g.,

(extended mode jump instruction)


address

0100
0101
0102
0103
0104

0200
0201

e.g.,

ADDA
$50
JMP
$02
$00
.
.
.
LDAB
$40

After this instruction is executed, PC is updated to


have $0200, which is the address of the next
instruction to be executed.

(relative mode branch instruction) (forward jump)


address
opcode

0100
0101
0102
0103
0104

0107

ADDA
$50
BRA
$03
.
.
.
STAA
$20

offset

PC points to $0104 after the fetch cycle and also the


operand fetch. Following the execution, $03 is added
to the PC and the next instruction to be executed
becomes the one located at address $0107.
jump forwards

Since it is designed to branch in either direction, the 8-bit address byte (offset) is interpreted as a
signed 8-bit value (in 2s complement). Hence the branching range is;
(PC + 2) 128 Destination (PC + 2) +127
PC 126 Destination PC+129
Location of the current instruction

Location of the instruction to jump

18

Effectively, one can branch to locations between 126 bytes backwards and 129 byte forwards relative
to the address of the branch instruction.
e.g.,

(relative mode branch instruction) (backward jump)


address

0100
0101
0102
0103
0104

0107

ADDA
$50
BRA
$FC

jump backwards
PC points to $0104 after the fetch cycle and the
operand fetch. Following the execution, PC is
updated and $FC (-4) is added to the low byte of PC
and the next instruction to be executed becomes the
one located at address $0100.

.
.
.
STAA
$20

Instruction Set
68HC11 has 329 instructions but counting only the different operations there are 153 instructions,
which can further be categorized into 14 different sets.
Learning a new instruction set is easier if one first learns the categories of instructions and then learns
what instructions are in each category.
1) Load registers
(10 instructions)

e.g.,

LDAA
LDAB
LDX

(A) (M)
(B) (M)
(IX) (M:M+1)

2) Store registers
(10 instructions)

e.g.,

STAA
STAB
STY

(M) (A)
(M) (B)
(M:M+1) (IY)

3) Transfer registers
(8 instructions)

e.g.,

TBA
TAB
TSX
XGDY

(A) (B)
(B) (A)
(IX) (SP)
(D) (IY)

4) Decrement/Incremen t
(12 instructions)

e.g.,

DEC
DECA
INX

(M) (M) - 1
(A) (A) - 1
(IX) (IX) + 1

5) Clear/Set
(5 instructions)

e.g.,

CLR
CLRA
BSET

(M) 0
(A) 0
set bits (M)

6) Arithmetic
(21 instructions)

e.g.,

ABA
ABX
SUBA

(A) (A) + (B)


(IX) (IX) + (B)
(A) (A) - (M)

19

MUL
NEGA

(D) (A) * (B)


(A) 2s complement of (A)

7) Logic
(9 instructions)

e.g.,

ANDA
EORB
COMB

(A) (A) AND (M)


(B) (B) XOR (M)
(B) 1s complement of (B)

8) Rotates/Shifts
(21 instructions)

e.g.,

RORA
LSR

rotate right A
logic shift right (M)

9) Data test
(11 instructions)

e.g.,

TSTA
CMPA
CPX

test if (A) = 0
(A) (M)
(X) (M:M+1)

10) Conditional branch


(16 instructions)

e.g.,

BMI
BEQ
BCC

branch if minus
branch if equal to zero
branch if carry clear

11) Jump and branch


(9 instructions)

e.g.,

JMP
BRA
JSR

unconditional jump
unconditional branch (short jump)
jump to subroutine

12) Condition code


(6 instructions)

e.g.,

CLC
CLV
TAP
TPA

(C) 0
(V) 0
(CCR) (A)
(A) (CCR)

13) Interrupts
(5 instructions)

e.g.,

CLI
SEI
RTI
SWI
WAI

(I) 0
(I) 1
return from interrupt
software interrupt
wait for interrupt

14) Misc.
(3 instructions)

e.g.,

NOP
STOP
TEST

no operation
stop clocks
special test mode

Load register instructions

20

Note that it is possible to use the same instruction in different addressing modes.
e.g., use of LDAA instruction in different addressing modes
Code
86 40
96 40
B6 40 00
A6 40
18 A6 40

Mnemonic
LDAA #$40
LDAA $40
LDAA $4000
LDAA $40,X
LDAA $40,Y

Addressing Mode
immediate
direct
extended
indexed
indexed

Operation
(A) $40
(A) ($40)
(A) ($4000)
(A) ((IX) + $40)
(A) ((IY) + $40)

Note that these instructions affect the Z and N flags according to the value that is loaded, reset the V
flag and do not effect the C flag in the condition code register (CCR).
Note: At this stage it is helpful to study the full instruction set of the 68HC11 (Appendix A)

21

Chapter 3
Programming Examples
Example 1: (simple addition) Write a program which adds the contents of memory locations $0040
and $0041 and stores the sum to memory location $0042. Start the program from location
$0020.
machine
location
code ($)
mnemonic
comments
0020
0021
0022
0023
0024
0025
0026
0027
0028

96
40
9B
41
97
42
7E
00
26

LDAA $40

Get operand 1

ADDA $41

Add operand 2

STAA $42

Store result

JMP $0026

Loop forever

Example 2: (nibble seperation) Write a program which takes the contents of location $40 and stores
the four least significant bits (LSBs) in location $41, i.e., separate the low order nibble. Start
the program from location $0010.
machine
location
code ($)
mnemonic
comment
$0010
96
LDAA $40
get the operand
$0011
40
$0012
84
ANDA #$0F mask off the most significant nibble
$0013
0F
$0014
97
STAA $41
store the result
$0015
41
$0016
7E
JMP $0016
loop forever
$0017
00
$0018
16
Accumulator B can also be used alternatively.
machine
location
code ($)
mnemonic
$0010
D6 40
LDAB $40
$0012
C4 0F
ANDB #%00001111
$0014
D7 41
STAB $41
$0016
7E 00 16
JMP $0016

# : immediate addressing
$ : hexadecimal
%: binary

Example 3: (disassembly of a word) Write a program which places the four LSBs of location $0040 in
location $0041 and four MSBs of location $0040 in location $0042 as the four LSBs of the
corresponding destination locations. Start the program from $0060.
machine
location
m. code ($)
mnemonic
comment
cycle
0060
96
LDAA $40
Get data
3
0061
40
0062
84
ANDA #$0F
Mask off 4 MSBs
2
0063
0F

22

0064
0065
0066
0067
0068
0069
006A
006B
006C
006D
006E
006F
0070

97
41
96
40
44
44
44
44
97
42
7E
00
6E

STAA $41

Store LSBs

LDAA $40

Get data

LSRA
LSRA
LSRA
LSRA
STAA $42

Convert MSBs
to LSBs

2
2
2
2
3

JMP $006E

Loop forever

Store MSBs

Total number of cycles: 22. With 2 MHz clock the execution time of the program: 11 sec.

Example 4: (addition of an array of n numbers) Memory location $41 contains the length (0) of a set
of numbers. The set starts at memory location $42. Write a program that stores the sum (less
than 256) of numbers in $40. Start the program at $0060.
START

COUNT=($41)
SUM=0
POINTER=$42

SUM=SUM+(POINTER)
POINTER=POINTER+1
COUNT=COUNT-1

No

IS
COUNT
0?
Yes
($40)=SUM
STOP

location label
$0060
$0061
$0063
$0066
$0068
$0069

mnemonic
CLRA
LDAB $41
SUMD

comment
SUM=0
COUNT=Length of array
acc. B will be used as counter
LDX #$0042
IX will be used as pointer
ADDA $00,X
SUM=SUM+element from the array
INX
update the pointer
DECB
update the counter

23

$006A
$006C
$006E

BNE SUMD
FOREVER

STAA $40
JMP FOREVER

if, not and of array (Z=0), go on


adding numbers
store SUM

Calculation of offset for label SUMD:


Target address = $66

= current instruction + 2 + relative address (offset)


= $6A+2+offset
offset = $66-$6A-2 = -6

In 2s complement form, offset = $FA


Hence the machine codes at memory locations $006A and $006B should be $26 and $FA.

Example 5: (data transfer) The length of the data array is in memory location $40, the data originally
starts in memory location $41, and the destination area for the data starts in memory location
$51. Write a program to transfer the data. Start the program at $0020.
location label
0020
0022
0025
0027
0029
002A
002B
002D

mnemonic
LDAA $40
LDX #$0041
LOOP
LDAB $00,X
STAB $10,X
INX
DECA
BNE LOOP
STOP
JMP STOP

Example 6: (condition code register) Assume ACCA contains the following data before HC11
executes the NEGA instruction. What is the result in ACCA and the N, Z, V, and C bits for
the negation of each byte?
ACCA: $00, $7F, $01, $FF, $80
Before
ACCA
$00
$7F
$01
$FF
$80

After
ACCA
$00
$81
$FF
$01
$80

NZVC
0100
1001
1001
0001
1011

Comment
Negating 0 gives us 0
Negating +127 gives -127
Negating +1 gives -1
Negating -1 gives +1
Negating -128 gives overflow

Note that NEGA means ($00-A) at the same time. That is why C (interpreted as borrow in this case) is
set in all negations except $00.

Example 7: (maximum value) Length (0) of a memory array, which contains unsigned numbers, is in
$41 and the array starts at $42. Write a program that places the maximum value in the array in
$40. Start the program at $0100.

24

START

MAX=($42)
PTR=43
COUNT=($41)-1
IS
MAX
(PTR)
?
Yes

No

MAX = (PTR)

PTR=PTR+1
COUNT=COUNT-1

IS
COUNT
0?
Yes

No

($40)=MAX
STOP

location
$0100
$0102
$0103
$0105
$0108
$010A
$010C
$010E
$010F
$0110
$0112
$0114

label

CONT

NOCHG

STOP

mnemonic
LDAB $41
DECB
LDAA $42
LDX #$0043
CMPA $00,X
BCC NOCHG
LDAA $00,X
INX
DECB
BNE CONT
STAA $40
BRA STOP

CMPA: compare (A) and (M)

comment
initialize the counter
set MAX to first number
initialize the pointer
compare acc.A contents with the value
pointed by IX (i.e. (A)-(M) is performed)
if AccA is greater go on with NOCHG
otherwise update the MAX value
update the pinterter
update the counter
if it is not end of array CONTinue
otherwise save the maximum value

means, perform (A)-(M) and change the CCR accordingly


Z = 1 if (A) and (M) are equal
C = 1 if (M) (A)

Relative address calculations:


$10E = $10A + 2 + offset for label NOCHG offset = $02
$108 = $110 + 2 + offset for label CONT offset = -10 = $F6 (in 2s complement)
$114 = $114 + 2 + offset for label STOP offset = -2 = $FE (in 2s complement)
Assume the initial values as ($41) = $03; ($42) = $37; ($43) = $F2; ($44) = $C6, a trace example for
the above program is as follows:
I

25

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

instruction
LDAB $41
DECB
LDAA $42
LDX #$0043
CMPA $00,X
BCC NOCHG
LDAA $00,X
INX
DECB
BNE CONT
CMPA $00,X
BCC NOCHG
INX
DECB
BNE CONT
STAA $40
BRA STOP
BRA STOP

B
03
02
02
02
02
02
02
02
01
01
01
01
01
00
00
00
.......
.......

A
x
x
37
37
37
37
F2
F2
F2
F2
F2
F2
F2
F2
F2
F2

IX
x
x
x
0043
0043
0043
0043
0044
0044
0044
0044
0044
0045
0045
0045
0045

C
x
x
x
x
1
1
1
1
1
1
0
0
0
0
0
0

Z
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1

($40)
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
F2

no branch

branch
branch
no branch

Example 8: (multiple precision arithmetic) Two n-byte numbers will be added. The number of bytes
in the numbers is given in location $0040. First number starts (LSByte first) at $0041 and the
second number at $0051. The sum is to replace the first number.
Ex:

n1
n2

=
=

50 A4 29
28 37 FB

sum

78 DC 24

0040
0041
0042
0043
...
0051
0052
0053

Before
03
29
A4
50
...
FB
37
28

START

After

C=0
COUNT = ($40)
PTR1 = 41

24
DC
78

(PTR1)=(PTR1)+(PTR1+$10)+C

PTR1 = PTR1 + 1
COUNT = COUNT - 1
No

IS
COUNT
0?
Yes
STOP

Use a counter (ACCB) to control the number of bytes


Use ACCA to hold the current sum.
Use IY as the pointer

26

location
$0100
$0101
$0103
$0107
$010A
$010D
$0110
$0112
$0113
$0115

label

mnemonic
CLC
LDAB $40
LDY #$0041
LOOP LDAA $00,Y
ADCA $10,Y
STAA $00,Y
INY
DECB
BNE LOOP
STOP BRA STOP

comment
clear carry
initialize the counter
initialize the pointer
get 8 bits of number 1
add the corresponding bits of number 2
store the result
update the pointer
update the counter

For the relative address LOOP:


0107 = 0113 + 2 + offset => offset = F2

(= -14)

Please note that the same program can be written using IX consuming less storage space in the
program memory.
Decimal arithmetic
Ex:

$0006+$0007 = $000D  (BCD correction)  13

After ADCA $10,Y insert DAA instruction and correct the BNE address accordingly.
DAA: Decimal Adjust ACCA, is used after the instructions
ABA
(add ACCB to ACCA)
ADDA
(add (M) to ACCA)
ADCA
to correct ACCA contents for BCD.

Example 9: (square from a lookup table) Write a program to find the square of a 3-bit binary number
from a lookup table. The table starts at SQTAB, location $40 contains the number whose
square is required and the result will be saved in location $41.
Assume that SQTAB contains 0, 1, 4, 9, 16, 25, 36, 49
label

CONT

FOUND
STOP

mnemonic
LDX #SQTAB
LDAA $40
BEQ FOUND
INX
DECA
BNE CONT
LDAA $00,X
STAA $41
BRA STOP

comment
load the base address of the table
get the input data
if it is zero, stop searching and goto FOUND
otherwise; point to the next table entry
decrement A
and repeat for ($40) times
get the corresponding table entry
store the result

Example 10: (character manipulation) Determine the length of a string of ASCII characters starting at
$41 and ending with period .. Store the length of the string to location $40. ASCII
equivalent of . is $2E. Start the program at $20.

27

e.g.
0041
0042
0043
0044
0045
0046
0047
0048
0049
location
$0020
$0021
$0023
$0026
$0028
$002A
$002B
$002C
$002E
$0030

54
4F
4F
20
4C
41
54
45
2E

T
O
O
L
A
T
E
.

label

NPER

DONE
STOP

mnemonic
CLRB
LDAA #$2E
LDX #$0041
CMPA $00,X
BEQ DONE
INCB
INX
BRA NPER
STAB $40
BRA STOP

comment
initialize the counter
hold the trailer value
initialize the pointer
compare data with the trailer
stop if period is found (if Z=1)
otherwise update the counter
update the pointer
go on with checking
save the string length

Relative address calculations:


$2E = $28 + 2 + offset for label DONE offset = $04
$26 = $2C + 2 + offset for label NPER offset = -8 = $F8 (in 2s complement)

Example 11: (pattern comparison) Two ASCII strings start in memory locations $42 and $52,
respectively. Memory locations $41 contains the length (0) of the strings. Write a program
that compares these two strings. If they are equal, the program will place zero to location $40,
otherwise $FF will be placed to $40.
label

CONCHK

DONE

mnemonic
LDAA #$FF
STAA $40
LDAB $41
LDX #$0042
LDAA $00,X
CMPA $10,X
BNE DONE
INX
DECB
BNE CONCHK
CLR $40
BRA DONE

comment
initially the strings are assumed not to be
equal to each other
initialize the counter
initialize the pointer
get an element from string1
compare with the corresponding element
of string2
if they are not equal branch to stop
update the pointer
update the counter
if not end of the strings go on checking
otherwise write the result, save the string length

28

Chapter 4
The Stack, Subroutines, Interrupts and Resets
In many computers, memory is divided into three distinct areas:
program area
data area
stack
The stack is an area of memory used for the temporary storage of information. Subroutines and
interrupts make use of the stack. The stack has a top and a bottom. The top part of stack
memory has a lower address. The bottom of the stack is fixed, but the top can change, moving
up or down.
The stack pointer (SP) is a register within the P that contains the address of the next location
available for the stack.
The Ps internal logic causes the SP to decrement automatically when data is stored in the stack and
to automatically increment when it is removed. Therefore, the SP must initially be set to the
highest address in the stack area (the bottom of the stack).
e.g., if the stack is to occupy locations $0200 to $02FF then use LDS #$02FF instruction as
initialization before using the stack.
SP instructions are:
- DES
SP - 1 SP
- INS
SP + 1 SP
- LDS
M:M + 1 SP (in immediate, direct, extended and indexed modes)
- STS
SP M:M + 1 (in direct, extended and indexed modes)
- TXS
IX - 1 SP
- TSX
SP + 1 IX
- TYS
IY - 1 SP
- TSY
SP + 1 IY
PUSH and PULL Instructions
The push (PSH) and pull (PUL) instructions store and load data to and from the stack.
PSHA (or B or X or Y) instruction writes the contents of the specified register in the stack at the SP
location (at the location whose address is contained in SP) and then decrements the SP once (for
PSHA and PSHB) or twice (for PSHX and PSHY) because the original stack location is no longer
vacant but contains the pushed data.
PULA (or B or X or Y) instruction first increments the SP once to point to the last item that has been
inserted into the stack and then transfers the contents of the stack appropriately to the specified
register.
Note that once the contents of a stack location have been pulled, the location is considered vacant,
although the data is still there. It will be overwritten by the next PUSH or other use of the stack. Also
note that the stack acts as a Last-In-First-Out (LIFO) structure. A pull instruction retrieves the
information that was pushed last onto the stack.

29

(b) Pull data from stack

Stack structure and stack operations


Subroutines
When the same function is required more than once in a program, it is frequently written as a
subroutine, that is, a subprogram that can be used any number of times by the main program. This
capability is provided by the following three instructions;
o
o
o

JSR (jump to subroutine)


BSR (branch to subroutine)
RTS (return from subroutine)

The following figure illustrates the use of the same subroutine by two different parts of the main
program. The subroutine located at $0200 can be entered from either location $0011 or $00CC by
placing a JSR (opcode = $BD) instruction at these addresses followed by the subroutine address
($0200).

30

JSR $0200 has the machine code BD 02 00 in the extended addressing mode. After the subroutine
is completed (i.e., when a return from subroutine RTS instruction is executed), the program resumes
from the instruction following the location where it called the subroutine. The example shows that in
the first jump (a), the program returns back to $0014 when it executes the RTS and in the second
jump (b), the program returns back to $00CF following the execution of the RTS. Because the
subroutine must return to one of several locations, depending on which one caused it to be entered,
the original contents of the PC must be preserved so that the subroutine knows where to return.

IX + K

Note that JSR instruction has both indexed and extended modes. With the complete execution of JSR,
the address of the next instruction to be executed (the one following the JSR) is stored automatically
in the stack and the PC is changed appropriately according to the addressing mode used for JSR i.e.,
the PC is changed to have the address of the first instruction in the subroutine.

31

BSR branch to subroutine has only the relative addressing mode and the subroutine start address is
calculated by the CPU by using the offset value provided in the program memory after the opcode of
the BSR.
Each subroutine must have RTS (return from subroutine) as the last instruction of the subroutine.
With the execution of the RTS, the CPU restores the PC from the stack automatically and therefore
the program returns back to the instruction where it has left (next instruction after the jump or branch
to the subroutine instruction). The following example is for the extended case in the above figure:

...
[n +3] H

39 = RTS

[n +3] L

Action of the RTS instruction


Nested subroutines: Since PC saving and recovery is automatic by the use of stack, it is possible to
execute nested subroutines as follows.

Note that the stack state in the figure corresponds to the time at which the processor executes
instructions within the second subroutine.
Also note that if the stack is used for register savings in a subroutine, the recovery should be done in
the reverse order and in a balanced fashion, otherwise the return address cannot be recovered properly
into the PC. For example, if a subroutine uses accumulators A and B and the CCR, how can the main
program preserve the contents of these registers?

32

The first four instruction of the subroutine may be


Opcode

Mnemonic

36
37
07
36

PSHA
PSHB
TPA
PSHA

which puts A, B and CCR on the stack as follows:

Contents of the stack after entering the


subroutine and executing the first four
instructions

Before returning to the main program, these registers should be restored in the subroutine in the
reverse order before the RTS instruction as follows:
Opcode

Mnemonic

32
06
33
32
39

PULA
TAP
PULB
PULA
RTS

Example: Solve example 9 (square from a lookup table) as a subroutine and use it in a main program
to calculate the square of two numbers stored in locations $41 and $42. Pass the input and the
output parameters using accumulator A only. Store the results in $43 and $44 respectively.
label
SQR

CONT

FOUND

MAIN

END

mnemonic
LDX #SQTAB
TSTA
BEQ FOUND
INX
DECA
BNE CONT
LDAA $00,X
RTS

comment
load the base address of the table (SQTAB)
check the input number
if it is zero, stop searching and go to FOUND
otherwise; point to the next table entry
decrement A
repeat for a number of times (until A becomes zero)
get the corresponding table entry
return from subroutine

LDAA $41
JSR SQR
STAA $43
LDAA $42
JSR SQR
STAA $44
BRA END

get the input data


find the square by using the subroutine
store the first result
get the other input data
find the square by using the subroutine
store the second result
loop forever

33

Example: Write an M68HC11 program, which performs the following task:

There is a data array which starts in the memory location $0500. The length of the array is given
in the memory location $0040.

Some of the elements of the given array will be placed to another area in the memory starting at
location $0900. Each element of the original array will be checked whether it is a 2-digit valid
BCD number or not and will be placed in the new array by reversing its bit order if it is valid, i.e,
if the content of the memory location $0500, for example, is a valid 2-digit BCD number
X7X6X5X4X3X2X1X0 then X0X1X2X3X4X5X6X7 will be stored to the memory location $0900. If
the number is not a valid 2-digit BCD number, then it will not be stored. At the end, the memory
location $0041 will hold the total number of bytes in the new array.

Write the BCD checking part of your code as a subroutine.

Solution: (write comments for the program as an exercise)


MAIN

CONT

VALID
CONTSHIFT

CONT2

END

CHKBCD

LDS #STACKBASE
LDX #$0500
LDAB $40
STAB BYTECOUNT
LDY #$0900
CLR $41
LDAA $00,X
JSR CHKBCD
BNE CONT2
LDAB #$08
LSLA
ROR $00,Y
DECB
BNE CONTSHIFT
INY
INC $41
INX
DEC BYTECOUNT
BNE CONT
BRA END

TAB
ADDA #$00
DAA
CBA
RTS

34

Example: You are required to write a program that quantizes an NxM ( N<10 and M<10) matrix A
by given number Q where 0<Q<9. The matrix A is in memory locations starting from $0013 and the
quantized matrix Aq should be stored in memory locations starting from $00E3. N,M and Q are in
memory locations $0010,$0011,$0012, respectively.
Aq(i,j) = round(A(i,j)/Q)
As an example if the following data are given
Mem. Loc
$10
$11
$12
$13
$14
$15
$16
$17
$18

Data
$02
$03
$03
$05
$0A
$0F
$0B
$01
$07

N
M
Q

Matrix A

The program output will be


$E3
$02
$E4
$03
$E5
$05
$E6
$04
$E7
$00
$E8
$02
** round(.) should be written as a subroutine
Solution:

COUNT
EQU $A000
DUM1
EQU $A001
DUM2
EQU $A002
ORG
$B000
MAIN
LDX #$0013 ; initialize pointer
LDAA $10 ; read N
LDAB $11
; read M
MUL
; NxM in ACCD
STAB COUNT
; since NxM can be represented in 1 byte ACCD is the counter
L1
LDAB $12
; read Q
LDAA $00,X ; read the data from matrix A
JSR RND
; go to the subroutine for quantization
STAA $D0,X ; quantized value is returned in ACCA, store it
INX
;
DEC COUNT ;
BNE L1
;
WAI
;
ORG $C000

35

RND PSHX
PSHB
PSHA
CLRA
XGDX
CLRA
PULB
IDIV

;
;
;
;
; IXH=$00, IXL=(ACCB)
;
; ACCB= data from Matrix A
; D/IX -> IX; rem -> D, since rem can be represented by 8 bits it is in
; ACCB
PULA
; ACCA=Q
LSLB
; ACCB=rem*2
CBA
; check if Q>2*rem
BEQ AD1
; if Q=2*rem, result should be incremented by 1
BCC CONT ; if Q>2*rem, result should be as it is, otherwise should be incremented
; by 1
AD1 INX
;
CONT STX DUM1 ; store the quantized value (2 bytes but only the LSB is meaningful)
PULX
;
LDAA DUM2 ; read the LSB of the result
RTS

36

Interrupts and Resets


An interrupt is a hardware (sometimes software) initiated subroutine call or jump that interrupts the
currently executing program. Depending on the type of the interrupt and the logic state of the I bit in
the condition code register, the CPU may suspend its normal operation and service the interrupt.
The software used in response to the interrupt signal is called an interrupt service subroutine. After
the interrupt service subroutine is executed, the CPU returns to the original program segment and
resumes execution as if no interrupt has occurred. This requires the CPUs registers to be saved when
CPU services an interrupt and to be returned unaltered when the service subroutine is finished. An
interrupt service subroutine ends with an RTI instruction (not an RTS) that automatically restores the
CPU registers.

Interrupt vectors
All resets and interrupts use vectors indicating the start address of reset or interrupt subroutines.

68HC11 uses a vector table and for each interrupt, the corresponding interrupt vector contains

an address in the memory. The vector addresses are fixed and they are at a permanent part of
the chip - usually at the ROM area. Hence, one has to tell the factory what to put in those
areas before the mass production of the chip.

37

In order to be able to change the starting address of any interrupt subroutine, something called a
pseudovector is used in the development boards. For example in Motorola EVBU Development
Boards, some part of the RAM area is reserved for pseudovector table. Three-byte memory areas are
used as pseudovectors for existing interrupts. The actual interrupt vector contains the address of the
three-byte pseudo-vector. The user then places the actual service subroutine anywhere in the memory
map and writes a three byte jump instruction in the corresponding pseudovector, which effectively
means that the associated subroutine will be executed in the case of corresponding interrupt.
For example, the IRQ vector (locations $FFF2 and $FFF3) of the chip on the EVBU development
board contains $00EE. If the three byte RAM locations starting at $00EE is made to contain a JMP
Address instruction (machine code $7E AdressH AddressL) then in the event of an IRQ interrupt, the
program executes the code starting at location Address as illustrated below.

When the signal at pin IRQ goes low, the CPU responds by putting the vector contents (i.e., $00EE)
to the PC, CPU then executes the instruction at $00EE, in this case JMP $C15A. Therefore, the actual
service subroutine starts at $C15A. This service subroutine ends with RTI instruction which causes
the PC and all registers to retain their values before the interrupt. Then, the main program can
continue its execution from where it was interrupted.

38

Interrupt masks and enables


Programmer can control an interrupt signal to be or not to be recognized by mostly setting the
interrupt mask bit (I bit) in the CPUs CCR. If I = 1, CPU does not recognize interrupt signals =>
Interrupts are masked. I bit can be set by using the SEI instruction and cleared by using the CLI
instruction.

Stacking the registers


When an interrupt request occurs CPU pushes all CPU register values to stack in the order: PC, IY,
IX, ACCA, ACCBA, CCR (pushing low byte first for 16-bit registers). When RTI is executed the data
is pulled from the stack and the registers are restored.
For RESET: No stacking of the registers.
All interrupt service subroutines should end with an RTI instruction.

Hardware interrupts and resets


RESET: Executed whenever the chip is powered up and whenever the external RESET pin is
activated. It has the highest priority.
Other processor resets: Computer Operating Properly (COP) failure reset, COP clock monitor fail
reset.
Nonmaskable interrupt (XIRQ): is used to handle the highest priority interrupts. When you power
up or RESET 68HC11, XIRQ is masked, i.e. X bit in CCR is set. To clear X, TAP (Transfer from
ACCA to CCR) instruction should be used.
Interrupt Request (IRQ): is maskable by setting bit I in the CCR.

IRQ

68HC11

XIRQ

IRQ versus XIRQ:


1. CPU can ignore the IRQ input if the I flag is 1; it can ignore XIRQ if the X flag is 1.
However I flag can be set and cleared any time by software. X flag can be cleared only once
and then it remains at 0 until the next reset or power up.
2. IRQ can be programmed as a level-sensitive or edge-sensitive input via the IRQE bit in the
OPTION (at $1039) register. XIRQ is always level sensitive.
3. XIRQ input has higher priority over IRQ input. When they are activated simultaneously
(while X=I=0), CPU will respond to XIRQ first.
The following figure illustrates the operation of XIRQ. One of the external pins of 68HC11 is for the
XIRQ input. For example, a printer control line is connected to it. The sequence of operation is as
follows (pseudovector is not considered for this example): While the controller is executing the
instruction LDAA #$1C, the signal at pin XIRQ goes low.

39

First it completes executing the

instruction. Then, because the X bit is zero, the microcontroller stacks the registers and sets the X and
I bits in the CCR. This prevents other interrupts from interfering with the rest of this operation. The
controller fetches the contents of vector address $FFF4 and $FFF5 and loads it into the PC. This is
$E71F for this example. It then executes the routine starting at address $E71F. If the XIRQ service
routine does not reset the I bit, other interrupts can interfere with its operation. When the service
routine executes RTI, it pulls the stored register values from the stack. This includes the return value
of $E125, the value of $1C in ACCA, and the original CCR contents (in which X=0 and I=0).

Example of XIRQ interrupt

Software and CPU control interrupts


Software interrupt (SWI): SWI instruction forces the CPU to respond the same way as it does to an
externally generated interrupt. It is useful in debugging the programs. It is not maskable by I or X bits
in CCR.
Wait for Interrupt (WAI): When the WAI instruction is executed, 68HC11 reduces its power while
waiting to be woken up. All registers are stacked and only an unmasked interrupt wakes up the
controller.
STOP: When the STOP instruction is executed, if S bit in CCR is set, STOP performs like a NOP. If
S bit is reset, all internal clocks halt, thus halting the execution. To wake up the controller, RESET,
XIRQ or IRQ (when I=0) must be used.

40

Steps that 68HC11 follows to service the IRQ.

41

Chapter 5
Clocked Operation, Bus Concepts, Address Decoding
Clock Circuitry
The clock is a periodic sequence of pulses. MC68HC11 contains an internal clock generator.
Connecting a crystal to the crystal pins (XTAL, EXTAL) with a clock frequency of 8 MHz (max.)
creates an internal clock frequency of 2 MHz (the crystal is internally divided by a factor of 4). This
clock is referred to as the system clock or the E clock.

Crystal connection

Cycle time

Clock rise time

Clock fall time

Peripheral data setup time

Peripheral data hold time

Clock details and port read timing


During each clock cycle, E goes low first, then high. When E clock output is low, an internal process
is taking place. When it is high, the MCU is writing or reading data. Port C is an I/O port when the
MCU operates in single-chip mode. An instruction to read data from an input data takes several cycles
depending on the type of instruction and its addressing mode. The figure given above shows the last

42

cycle during which MCU latches in the data at the port pins. The MCU latches in the data when the
clock falls. Note that the timing parameters are important in circuit design. The peripheral device must
provide stable data within the time limits shown relative to the clock. Data should be retained for a
short period after E goes low again.
Timing diagrams: Show how signals change over time. They can show either one or multiple signals
(for example bus signals) on the same diagram. In microcontroller systems bus transitions occur in
relation to a clock signal.
logic 1

falling
edge

rising
edge

logic 0
Single bit (line) timing diagram
Invalid data

Long period of time


Valid data

High impedance state


Bus timing diagram

Bus Operations
Bus:

Typically a series of etched copper lines on a printed circuit board connecting plug-in sockets
for other PCBs.
A set of signal lines.

P signals can be divided into three separate busses that transfer data, address and control
information.

Bus structure

43

Address bus
Data bus
Control bus

: 16 bit -> capable of addressing 64 Kbytes


: 8 bit, bi-directional, three-state
: R/W, E, etc.

General bus operations:


1. Processor places the desired peripherals address to the address bus.
2. Processor [peripheral] places desired data to the data bus for write [read]
3. Operation is directed by various control lines that are included in the control bus
Bus is not a static connection mechanism. Only one device can drive the bus at a time. For an MCU to
use only one device at a time, it enables the device, meaning that it gives permission to the device to
use the bus. The MCU disables other devices, meaning that it refuses permission. To disable other
devices, the MCU must effectively disconnect them from the bus. To do this, it puts them in a state
called high impedance. This is like opening a switch. An open switch has infinite resistance, so it is
high impedance. Instead of such mechanical switches, Tristate devices are commonly used for this
purpose. Other than being high or low, if an output can also be at high impedance (a third state), then
the device is a tristate device.

Tristate logic

Modes of Operation
Many microcontrollers, such as the 68HC11 can be operated in different modes. The I/O and memory
requirements of an application, or test requirements, determine in which mode to operate the MCU.
The 68HC11 has four modes. The mode selection is determined by how pins MODA and MODB are
connected at the time of reset. Usually, the mode is fixed for any application. Two of the modes are
operational: single-chip and expanded multiplexed.
Single-chip operating mode:
Only one chip is required. There is no need for extra memory or I/O chips. Hence, an external bus is
not required. The pins on ports B and C are used for I/O. I/O subsystems can control these ports to
perform specialized I/O tasks.
Expanded-multiplexed operating mode:
Larger microcontroller applications use circuits with peripheral chips connected to the microcontroller
chip. This means that the microcontroller must use some pins for external bus (address, data and
control). The 68HC11 can operate in an expanded mode and it uses ports B and C as an address and

44

data bus. The mode is also multiplexed because port C has a dual function. It caries address signals
and data signals at alternating intervals. The MCU chip does not use the I/O capability of these ports.
Applications must use expanded multiplexed mode if they require more memory or I/O subsystems
than are provided in the chip.
Port B carries only the upper address byte of a 16-bit address. Pins PB0 to PB7 are also address pins
A8 to A15. Port C pins, PC0 to PC7, are also pins A0 to A7. In expanded multiplexed mode, port C is
a bus that carries both the low byte of the address and the (single) data byte. The address and data
signals cannot appear on the bus at the same time. They must be multiplexed. Multiplexed signals
share a common communication channel which is preferred by the manufacturers to keep the pin
count down.

Address/Data Multiplexing in Expanded Mode Operation


Many controllers use multiplexed address and data bus, i.e. the data bus and (part of) the address bus
use the same physical lines. When using a multiplexed bus, it is necessary to connect the bus to
hardware to demultiplex it. Extra logic is required for demultiplexing. Demultiplexing is the process
of separating all the signals in a common channel into the separate signals.
In the figure given below, typical connection diagram for expanded mode operation is given. The
74HC373 latch demultiplexes port C.
Port B

LE

Port C

Address/Data multiplexing in expanded mode of operation


At the beginning of a clock cycle, the MCU puts the address high byte on port B, the address low byte
on port C, and pulses AS high for address strobe. This forces latch enable (LE) high, which causes the
address low byte to be latched. The output of the 74HC373 is now the current low address byte. The
address pins of the external device (memory or I/O device) will see both the high and low address
bytes for the entire clock cycle. When the clock goes high the MCU reads or writes data (See the
figure given below). In read case, the read/write signal remains high and the external device puts data
on the port C lines only when E is high. The MCU latches in the data at port C when the clock goes
low again (i.e. at the end of the cycle). In write case, the MCU sends data on port C. Also, it forces
read/write low. The external device must latch in the data before E goes low again.

45

Read/Write timing in expanded mode of operation


Address Decoding
MCU enables a memory chip only when it wants to address it. To do this, MCU uses an address
decoding circuit. The signals on the address pins determine which memory location is selected or
addressed. Address decoding methods are:
1. Full (exhaustive) decoding: Each peripheral is assigned to a unique address. All address bits
are used to define the referenced location.
2. Partial decoding: Not all address bits are used in the decoding process. Peripherals may
respond to more than one address. Reduced complexity in the decoder.
Basic address decoder uses a NAND gate:
Example: You have a 4Kx8 bit memory chip and 16 address lines coming out of the MCU. Then 12
address lines should be used for internal decoding and 4 address lines should be used for chip select.
Assume that you want to decode the addresses between $D000 and $DFFF.
12
A0-A11
Used for internal decoding
A12
A13
A14
A15

A15
1
1

A14
1
1

A13
0
0

used for chip selection

A12
1
1

4K memory
8

A11
0
1

A10
0
1

data

CS or CE

..

A1
0
1

used for internal memory addressing

46

A0
0
1

:$D000
:$DFFF

Example: For a particular application it is required to use a 2716 (2Kx8bit) EPROM for memory
locations $A000 thru $A7FF. Design a decoder circuit using NAND gates.
A15
1
1

A14
0
0

A13
1
1

A12
0
0

A11
0
0

used for chip selection

..

A1
0
1

A0
0
1

:$A000
:$A7FF

used for internal EPROM addressing

A0-A10 of
address bus
A11
A12
A13
A14
A15

A10
0
1

A0-A10
D0-D7

CS

8 input NAND
gate

Integrated decoder circuits for address decoding:


In most applications, more than one memory device is usually required for system operation. For
many applications 74HC138 (3-to-8 line decoder) is used.

74HC138 (3-to-8 line decoder)

47

Example: For a particular processor, design the decoding circuitry to connect eight 2716 (2K)
EPROMs at memory addresses $0000 thru $3FFF.
This can be achieved using eight 8-input NAND gates and a number of inverters or a single 74HC138
decoder.
A15
0
0
.
.
.
0

A14
0
0

A13
0
0

A12
0
0

A11
0
1

A10
x
x

A9
x
x

..

A1
x
x

A0
x EPROM1
x EPROM2

x EPROM8

Bit 15,14: Used for the selection of this eight-chip portion in the whole 64K address space.
Bit 13,12,11: Used for 1 out of 8 decoder (EPROM chip) selection
Bit 10,..,0: Used for internal decoding of the selected EPROM chip

74HC138

0000 to 07FF

0800 to 0FFF

3800 to 3FFF

3000 to 37FF

1000 to 17FF

1800 to 1FFF

A11

.
.

A12
A13

7
2800 to 2FFF

2000 to 27FF

5v A15 A14
Decoding circuit
Example: Show the full connection diagram for interfacing a 6164 RAM chip to 68HC11 in expanded
multiplexed mode between memory addresses $C000 thru $DFFF.
A15
1
1

A14
1
1

A13
0
0

use for chip selection

A12
0
1

A11
0
1

A10
0
1

A9
0
1

..

use for internal RAM addressing

48

A1
0
1

A0
0
1

:$C000
:$DFFF

Full connection diagram for a 68HC11 and a 6164 RAM interface circuit

49

Static memory systems


A memory map illustrates which segments are to be used for RAM, ROM, and in some cases where
the I/O resides.
Example: The following memory map is given and it is required to be implemented using three 4K
ROM and two 1K RAM chips available.

$0000
ROM
$2FFF

$6000
RAM
$67FF

4K ROM1
4K ROM2
4K ROM3

$0000 - $0FFF

1K RAM1
1K RAM2

$6000 - $63FF

$1000 - $1FFF
$2000 - $2FFF

$6400 - $67FF

$FFFF
For RAM internal addressing we need 10 bits (A0-A9). A10-A15 are left for RAM selection.
For ROM internal addressing we need 12 bits (A0-A11). A12-A15 are left for ROM selection.

A15
0
0
0
0
0

A14
0
0
0
1
1

A13
0
0
1
1
1

A12
0
1
0
0
0

A11
x
x
x
0
0

A10
x
x
x
0
1

A9
x
x
x
x
x

..

A1
x
x
x
x
x

A0
x
x
x
x
x

1 of 3 ROM selection
Internal decoding for RAMs
1 of 2 RAM selection

RAM/ROM selection

Internal decoding for ROMs

May be used for low active enable input if a decoder is used.

50

ROM1
ROM2
ROM3
RAM1
RAM2

Using 74HC138 decoders


12
ROM1

A0-A11

ROM2

ROM3

74HC138
A12
A13
A14

A0
A1
A2

0
1
2
3

74HC138

4
5
E1
E2
E3

A15
VCC

A10
A11

A0
A1
A2

0
1
2
3

RAM2

4
5
E1
E2
E3

RAM1
10

A0-A9

6
7

Memory Overlaying
Example: Design a decoder circuit for the following memory map.
$0000
4K ROM1

Overlaying:
$0FFF
Each 4 Kbyte ROM may overlay 8 Kbytes of memory
$2000

Each 1 Kbyte RAM may overlay 8 Kbytes of memory

4K ROM2
$2FFF

$4000
4K ROM3
$4FFF

$8000
1K RAM1
$83FF

$A000
1K RAM2
$A3FF
$FFFF

51

A12 is always 0 and not used in the following


decoding circuit
A15
0
0
0
1

A14
0
0
1
0

A13
0
1
0
0

A12
0
0
0
0

A11
x
x
x
0

A10
x
x
x
0

A9
x
x
x
x

A1
x
x
x
x

A0
x
x
x
x

ROM1 (4K)
ROM2 (4K)
ROM3 (4K)
RAM1 (1K)

RAM2 (1K)

Can be used for chip selection with overlays


12
ROM1

A0-A11

ROM2

ROM3

74HC138
A13
A14
A15

A0
A1
A2

0
1
2
3
4
5

E1
E2
E3

GND
5v

RAM2

RAM1
10

A0-A9

The above circuit implements the following logical memory (40K) with 14 K physical
memory:
A15
0
0
0
1
1

A14
0
0
1
0
0

A13
0
1
0
0
1

A12
x
x
x
x
x

A11
x
x
x
x
x

A10
x
x
x
x
x

A9
x
x
x
x
x

52

A1
x
x
x
x
x

A0
x
x
x
x
x

ROM1 (8K)
ROM2 (8K)
ROM3 (8K)
RAM1 (8K)
RAM2 (8K)

Chapter 6
Interfacing Concepts
Interfacing is the process of connecting devices together so that they can exchange information. A
special interface must translate between the signal that the computer uses and those that the peripheral
uses. An interface includes the physical connection, the hardware and a set of rules or procedures, i.e.,
the software. The interface must provide the proper timing and control. Formally, an interface is a
device and/or set of rules to match the output of one device to the input of another device for sending
information from one to the other. For example, the connection between a microprocessor and
external memory is an interface. There are physical connections for addressing, data flow and control
signals. The software consists of instructions that read from and/or write to an addressed location.
The major problems with interfacing are:
wide variety of peripheral devices
enormous range of peripheral speeds
variety in signal types and signal levels in peripheral devices
complexity of the signaling structure (strobes, handshaking, etc.)

Basic Input/Output Interfacing


The process of getting signals in and sending signals out is called input/output (I/O). The subsystems
responsible for this task are known as I/O subsystems, which are sometimes called an interface. Input
and output are similar to memory accesses. The processor can transfer data to and from the
peripherals in the same way that it transfers data to and from memory. In fact, memory is simply
another peripheral. I/O direction is relative to the MCU. Input is data read by the MCU. Output is data
sent out by the MCU.
A simple I/O section in a microcomputer system may include a temperature sensor that provides data
every 5 minutes, a modem device that transfers 56K bits every second and a floppy disk that transfers
bits in the order of megabits per second.
Simple Input Interface
An input operation is similar to a memory read cycle.
1. P generates address and control signals to select the input device.
2. Input device generates data and loads data lines.
3. P reads data from the data bus and places it in a register.
Most Ps accept data from an input device through the data bus connections and therefore require
some form of switch to connect this data to the bus at the appropriate time. One effective digital
switch available is the three-state buffer.
Example: Eight On/Off switches can be connected to the CPU by the use of a three-state buffer as
follows:
74LS244
+5v
R
+5v
R

from P
address
bus

Device
Decoder

INSTROBE

53

to P data bus

INSTROBE is the timing control signal. Device decoder generates the INSTROBE signal for the
required input device.
Simple Output Interface
An output operation is similar to a memory write cycle.
1. P generates address and control signals to select the output device.
2. P places data on the data bus.
3. P waits for the transfer to be successfully completed.
Whenever data is sent out from the P to an external output device, it appears on the data bus for only
a brief period of time. In almost all instances, the external output device uses some form of latch to
grab onto and hold the data bus information.
Example: Eight LEDs can be connected to the CPU by the use of latch as follows:
D Q
R
from P
data bus

.
.
D Q
R

from P
address
bus

Device
Decoder

OUTSTROBE

Other examples of output devices are 7-segment displays, liquid crystal displays (LCD), relays,
solenoids, etc.
Input/Output Mapping
Most I/O sections consist of more than one device. Such I/O sections require bus structures that must
be combined with those required by the memory section. Almost all microprocessors use the same bus
for both memory and I/O transfers.
There are two basic input/output schemes:
1. Memory-mapped I/O; in which I/O devices (parallel I/O lines) are treated exactly the same as
memory locations
2. Isolated I/O; in which memory and I/O addresses are decoded separately.
Example: (Memory-mapped I/O) (used by most Motorola processor)
Suppose that it is required to use eight I/O devices and the locations $CF00 through $CFFF are to be
used for this purpose.

54

Memory Map
$0000

Device 0: $CF00-$CF1F
Device 1: $CF20-$CF3F
Device 2: $CF40-$CF5F
Device 3: $CF60-$CF7F
Device 4: $CF80-$CF9F
Device 5: $CFA0-$CFBF
Device 6: $CFC0-$CFDF
Device 7: $CFE0-$CFFF

$CF00
I/O area
$CFFF

In fact there are


256 locations and
eight different
devices use this
space with
overlays

$FFFF

CFxx selects the I/O space (page selection)


For each device only the higher order 3-bits of the remaining 8 address bits are used.

A5
A6
A7
A15
A14
A13
A12
A11
A10
A9
A8

A0
A1
A2

CFxx
E1
PAGE CF
0

E2

E3

Device 0

Device 1

Device 2

Device 3

Device 4

Device 5

Device 6

Device 7

INCF00

INCF20

INCF40

INCF60

INCF80

INCFA0

INCFC0

INCFE0

Decoder Circuit

A5
A6
A7

A0
A1
A2

MEMR
E1

R/W

E2

PAGE CF
1

E3

Input Strobe Generator Circuit

55

To access the input device 0, one can use LDAA $CF00 and to access the input device 7, one can use
LDAA $CFE0. Input and output devices should use R/ W signal for proper activation.
Advantages of memory-mapped I/O are:

Any instruction that operates on data in memory can operate on data at input and output
devices.
No separate decoding or control system other than memory decoding or control is necessary
for input and output.

Drawbacks of memory-mapped I/O are:

I/O transfers may be difficult to distinguish from other operations in software.


I/O devices occupy some of the address space.
The decoding system may become complex because I/O devices occupy much less than
memory chips. In order to avoid complexity the memory space has to be wasted.

Example: (Isolated I/O) (used by most Intel and Zilog processors)


In this type of I/O, there are separate memory and I/O instructions and separate memory and I/O
maps. Suppose that it is required to use eight I/O devices and the locations between $80 through $9F
in the I/O map are to be used for this purpose.
Memory Map
$0000

I/O Map
Device 0: $80-$83
Device 1: $84-$87
Device 2: $88-$8B
Device 3: $8C-$8F
Device 4: $90-$93
Device 5: $94-$97
Device 6: $98-$9B
Device 7: $9C-$9F

$00

$80
$9F

$FFFF

I/O area

In fact there are 32


locations and eight
different devices
use this space with
overlays

$FF

A10
A11
A12

A
B
C

A13

E1

A14

E2

A15

E3

Device 0

Device 1

Device 2

Device 3

Device 4

Device 5

Device 6

Device 7

For example in Intel 8085,


address lines A7-A0 and A15-A8
have the same information when
I/O map is used, i.e., address of
one of 256 ports is issued in both
low and high order address bytes.

Decoder Circuit

56

Example: Draw the strobe generation circuit for four input and four output ports between addresses
$00-$3F in the isolated I/O mode
A12
A13
IOR

A
B
C

A14

E1

A15

E2

IOR
IOW

E3

IN00

IN10

IN20

IN30

OUT00

OUT10

OUT20

OUT30

Overlayed usage

Strobe generator circuit


In Intel chips, for example, there are special IN and OUT instructions in addition to memory access
instructions. Also on the chip there exists an IO/M signal in addition to R/W signal. The above IOR
and IOW signals can be constructed using these signals.
Advantages of isolated I/O are:

I/O device addresses can be short.


Programs are clearer because I/O transfers are distinguished from other operations.
Memory and I/O design can be separated

Drawback of isolated I/O is the requirement for extra decoding and extra instructions.
General Input/Output Interfacing and I/O Registers
I/O systems do not control only simple switches and leds. I/O systems usually transfer data to and
from more complex peripheral devices. Data is usually required to be input whenever it is ready at the
device side. Similarly data is usually required to be output whenever the peripheral device is ready to
accept it. Microcontrollers generally have built-in I/O subsystems because they are designed to handle
the different types of interface requirements commonly found in industry. Some applications require
more I/O than can be handled by the MCUs built in I/O subsystems. In this case the MCU board
could include programmable I/O peripheral chips.
Both microcontrollers and programmable I/O chips handle I/O processing using registers. Generally,
an I/O section has some associated registers like the control, status and data registers.
The control register is programmed (suitable data is written) to define the operation characteristics of
the I/O section. An I/O section can therefore be programmed as follows:
- the signal lines can be defined as input or output
- availability of the external data or the readiness of the external device can be detected by a
transition in an associated signal line
- the transition type can be defined to be level (high or low) or edge (rising or falling edge)
sensitive
- whenever a transition occurs, an interrupt signal may or may not be generated.
The status register is read to check the status of the I/O. By reading it, one can understand,

57

whether the external data is available (external device made its data ready) or whether the
external device is ready to input its data
whether there is an error in the transfer or not.

The data register holds the input data that has been received or the output data that was most recently
sent out.
The above I/O functionality can be done on a separate chip which then can be connected to the P
appropriately or the I/O functionality can be implemented on the microcontroller itself. The MC6821
Peripheral Interface Adapter (PIA) chip is a programmable I/O interface chip.
The Peripheral Interface Adapter (PIA)
A set of ports (parallel I/O signal lines), sometimes on chip memory, registers, programmable counter
and a timer may constitute the peripheral interface adapter (PIA). In general, PIA is a programmable
LSI device with the following features.
- buffers and latches for input and output data
- status and control signals for handshaking
- other control and timing signals for peripherals
- direct interface with the processor address, data and control buses
PIA usage:

Device

P buses

PIA

For simple parallel input/output:


1.
2.
3.
4.

address the PIA control register


transfer control information into PIA
address the PIA data register
transfer data (in or out) through PIA

A typical simplified port pin connection of a PIA is as follows:


D

Port Pin
OUT
IN and OUT are generated by
software, WR Port and RD Port
signals are generated by the
decoding circuitry.

WR port
Data bus
IN
RD port

58

The MC6821 Peripheral Interface Adapter (PIA)

Data Registers (DR), when addressed, store the data present on the MPU data bus during an MPU
write operation.
During an MPU read operation, the data present on peripheral lines programmed as inputs is
transferred directly to the system data bus.
The Data Direction Registers (DDR) are used to establish each individual peripheral bus line as
either an input or an output. This is accomplished by having the MPU write "ones" or "zeros"
into the eight bit positions of the DDR. Zeros or ones cause the corresponding peripheral data
lines to function as inputs or outputs, respectively.
Selection of 6821 and Internal Registers:
There are three chip select inputs and one enable input.
Since all data transfers take place during the high portion of the clock cycle, the Enable (E) input is
normally connected to E clock of the 6811.
The PIA occupies four memory locations through two RS pins. Since there are six registers, but four
addresses, DDR and DR share the same address from the point of MPU address bus. These
two are selected via bit-2 of CR. If it is zero DDR is selected, if one DR is selected.
Internal addressing (register selection) of the PIA is as follows:
RS1
0
0
0
1
1
1

RSO
0
0
1
0
0
1

CRA-2
0
1
X
X
X
X

CRB-2
X
X
X
0
1
X

Selected Register
DDRA
DRA (Peripheral Register)
CRA
DDRB
DRB (Peripheral Register)
CRB

Before the selection of DDR and DR, bit-2 of the corresponding CR has to be set to the proper level.

59

The control registers (CR) allow the MPU to establish and control the operating modes of the
peripheral control lines, CA1, CA2, CB1, CB2.
Organization of the PIA control registers is as follows:

Bit-7 (IRQA1 Interrupt Flag): Goes high on active transition of CA.); automatically cleared by MPU
read of DRA, may also be cleared by hardware reset. It is read only (CRB-7).
Bit-6 (IRQA2 Interrupt Flag):
If CA2 is input: Goes high on active transition of CA2, cleared in the same way as bit-7.
If CA2 is output: It is equal to zero, not affected by CA2 transitions. (CRB-6)
Bit-0 (Interrupt Request Enable/Disable): If it is equal to zero, disables IRQA interrupt which will
be caused by CA1 active transition. If it is one, enable CA1 interrupt. (CRB-0)
Bit-1 (Active transition determination): if 0, high-to-low transition of CA1 sets IRQA1;
if 1, low-to-high transition sets IRQA1. (CRB-1)
Bit-2 (DDRA access): If 0, DDRA is selected; if 1, DRA selected. (CRB-2)
Bit-5 (CA2 input-output control):

RESET: The RESET input clears all the PIA registers. All the data and control lines are initially
inputs, all interrupts are disabled and DDR is selected.

60

Examples on I/O applications


If PIA is used, the device has to be initialized by programming. General initialization procedure is as
follows:
- clear bit-2 of CRA (CRB) to select DDRA (DDRB)
- load DDR in order to program the ports as input or output lines in the required manner
- set bit-2 of CRA (CRB) to select DRA (DRB)
- write (to output port) and read (from input port)
Example: Transfer the contents of location $0040 via port A of the PIA. Assume the following PIA
register address:
DDRA, DRA: $8008
CRA:
$8009
mnemonic
CLR $8009
LDAB #$FF
STAB $8008
LDAB #$04
STAB $8009
LDAA $40
STAA $8008
.
.
.

comment
CRA-2 is cleared. $8008 is the address of DDRA
DDRA is loaded with all 1s. Port A is programmed as output
CRA-2 is set. $8008 is the address of DRA
Load the contents of location $40 to Acc.A
Transfer the contents of Acc.A to Port A

Example: It is required to control a 4-bit LED display with a 4-bit DIP switch via a 6811+6821
system. You are allowed to use only Port A of the PIA and assume the following PIA register address:
DDRA, DRA: $8008
CRA:
$8009

PIA

label

LOOP

PA0
PA1
PA2
PA3
PA4
PA5
PA6
PA7

mnemonic
CLR $8009
LDAB #$F0
STAB $8008
LDAB #$04
STAB $8009
LDAA $8008
ASLA
ASLA
ASLA
ASLA
STAA $8008
BRA LOOP

DIP
SWITCH
LED
DISPLAY

comment
CRA-2 is cleared. $8008 is the address of DDRA
DDRA is loaded with four 1s and four 0s. Port A is
programmed as half output and half input
CRA-2 is set. $8008 is the address of DRA
Read the position of the DIP switch

Transfer LSN to MSN


Transfer the info to display

61

Example: Consider the following connection of 6821 to 6811 and determine the address of the PIA
registers.
1
A14
A15
R/W
E
A0
A1

CS0
CS1
CS2
R/W
E
RS0
RS1

A15 A14 A13


0
1 x
0
1 x
0
1 x
0
1 x

PIA

With overlays:
$4000-$7FFF
$4000
$4001
$4002
$4003

. . . A2
... x
... x
... x
... x

A1
0
0
1
1

A0
0 : DDRA/DRA
1 : CRA
0 : DDRB/DRB
1 : CRB

: 16K locations are used for the PIA


: DDRA/DRA
($7FFC)
: CRA
($7FFD)
: DDRB/DRB
($7FFE)
: CRB
($7FFF)

Example: Write a program segment that determines the contact position of the following eightposition switch. If there is no contact with any terminal of the switch then wait for the switch to make
a contact.
+5v
PIA
A13
A14
A15
R/W
E
A0
A1

CS0
CS1
CS2
R/W
E
RS0
RS1

R
PA0
PA1
PA2
PA3
PA4
PA5
PA6
PA7

PIA base address: $6000


label

WAIT

SRCHPOS

FOUND

mnemonic
LDX #$6000
CLR $01,X
CLR $00,X
LDAA #$04
STAA $01,X
LDAA #$FF
CMPA $00,X
BEQ WAIT
CLRB
LDAA $00,X
RORA
BCC FOUND
INCB
BRA SRCHPOS
WAI

comment
get the base address of PIA
access DDRA
make all lines input
$6000 is the address of DRA
if the switch is not at any contact position, i.e.
if the input byte is $FF then wait for
a position to be contacted
the switch is in contact position, begin testing
the zero position
get switch data
check if the corresponding bit is grounded or not
if so, contact position is found
if not, increment ACCB and go on
with checking if the position is the next one

62

Interfacing using polling or interrupts


There are two methods for controlling the flow of data in and out of the computer:
1. Program controlled I/O (polling):
P repeatedly executes a program code and checks periodically whether a peripheral requests
servicing. When it finds that a peripheral has requested service, the P performs the data
transfer operation, either a read or write.
An external peripheral may request service by sending a pulse on an I/O request line. The I/O
request may be for a read or a write operation. Either a low-to-high transition or a high-to-low
transition on the I/O request line causes a bit in the associated status register to set (or reset).
To determine whether or not to serve a peripheral, the MCU reads (polls) a status register
periodically to check the corresponding status bit (request flag). If an I/O request is detected,
then it proceeds to handle the request as required, i.e. the MCU executes an I/O service
routine. For a read operation, it may be something like read the data register and pass the
value to the main program in an accumulator. For a write operation, it may be an output
routine that passes an accumulator value to the data register.
Advantage: Simple program.
Disadvantage: Inefficient use of P time. P may miss data if the input data changes more
rapidly than P loop time.
2. Interrupt controlled I/O:
An I/O device sends an interrupt signal to P to notify the computer that either the peripheral
has data for the P or it expects the computer to output data for the peripheral. The P then
suspends its current task to service the interrupt. P goes to the interrupt service subroutine
which then services the interrupt by reading from or writing to I/O ports. After the service, P
returns back to its original execution.
Like polling, an active transition on the request line may set the request flag. In this case it
also asserts an interrupt.
The P stacks the P registers and sets I bit in the condition code register.
P then executes the service routine addressed by the interrupt vector. If more than one
device could cause the same interrupt, the P checks other status bits to determine which
service has caused the interrupt. The P clears the request flag and then completes the I/O
depending on the requirements. After completion of the interrupt service, return from
interrupt (RTI) instruction is eceuted by the MPU, which returns the control to the interrupted
program.
Adv: More efficient
Disadvantage: Complex program.
Which of the two methods are to be used is programmed through the control register of the PIA chip
(CRA-1 for 6821).

63

How interrupt is sent to P?


PIA (6821)

IRQA

CA1

IRQB

CA2

IRQ

If bit0 (interrupt enable bit for CA1) of CRA is set, then PIAs IRQA line will go low whenever CA1
is triggered. This sets status bit 7 (CRA-7) and passes an interrupt request to P. P services the
interrupt by reading the DRA. After the execution, PIA automatically clears the status bit 7, which
clears the interrupt signal on IRQA.
Example: (Rotary switch example) If the task of monitoring switches is placed under interrupt control,
the P is freed from the tasks of monitoring the switches and can perform other tasks.
+5v
R
A13
CS0
PA0
A14
CS1
PA1
A15
CS2
PA2
R/W
R/W
PA3
E
E
PA4
A0
RS0
PA5
A1
RS1
PA6
PA7
CA1

PIA base address: $6000


label

mnemonic
LDX #$6000
CLR $01,X
CLR $00,X
LDAA #$05
STAA $01,X
CLI

ISR

SRCHPOS

FOUND

LDAA #$FF
CLRB
LDAA $00,X
RORA
BCC FOUND
INCB
BRA SRCHPOS
RTI

comment
get the base address of PIA
access DDRA
make all lines input
control word %00000101 (active CA1 transition is
high -to-low and IRQA is enabled)
$6000 is the address of DRA

if the switch is not at any position, i.e.


the switch is at a position, begin with zero pos.
get switch data
check is the next bit is grounded
if so, position is found
if not, increment ACCB and go on
with checking if the position is the next one

64

I/O Systems and registers for 68HC11

MC68HC11 block diagram

65

MC68HC11 E series registers

66

67

Port functions
The 68HC11 has five 8-bit ports. Any of these can be used as parallel I/O ports, depending on how
their respective control registers are configured. Of these, ports B and C can only be used for parallel
I/O. Port D is for serial I/O, port A is for programmable timer and port E is for analog/digital
converter.
Any of the port C and D lines can be used as input or output, depending on how their respective data
direction bits are configured. Pin 7 of port A (PA7) is also bidirectional. When port A is used for
parallel I/O, lines 0,1 and 2 are input only and lines 3,4,5 and 6 are output only. Port B is used for
output only. Port E is an input port when used for parallel I/O.
Parallel I/O

Each line carries 1 bit of data word.


All 5 ports on the 68HC11 can be used for parallel I/O.
Mostly used parallel ports are Port B and Port C.
Port B is an output port.
Port C can be configured to be either input or output.
Ports B and C can be used for strobed I/O or full handshake I/O.
Uses: LED, keyboard, printer interface, switches.

Serial I/O

Uses a single line to transmit bits one after the other. This reduces the number of lines but
slows down the rate of data transfer.
May be synchronous or asynchronous.
Port D used for serial I/O
Often used for: Computer connection, modem, mouse, network
One of the most common standards is asynchronous serial which is called the RS-232
interface.

Programmable timer

Port A is used for timer functions such as timed outputs or measuring input times.
Uses: Generate time delays, measure frequency of input signals, measure pulse widths

Analog/digital converter

Converts an analog voltage into a binary number


Port E is used for A/D conversion
Uses: Many physical quantities are represented by anolog values such as temperature,
voltage, pressure, light intensity,...

Summary of port functions

PORT A: Timer operations or parallel I/O


o PA0-PA2 input only
o PA4-PA6 output only
o PA3 and PA7 output or input
PORT B: Upper 8 bits of address bus (expanded multiplexed mode) or parallel I/O
o PB0-PB7 output only
PORT C: Multiplexed address/data bus (expanded multiplexed mode) or parallel I/O

68

o PC0-PC7 input or output


PORT D: Asynchronous serial I/O (PD0-PD1), synchronous serial I/O (PD2-PD5) or parallel
I/O
o PD0-PD5 input or output
PORT E: A/D converter or parallel I/O
o PE0-PE7 input only

69

Chapter 7
Parallel Input/Output
This chapter presents the following I/O techniques:

Simple, blind data transfers


Strobed data transfers
Data transfers with handshaking

Simple, blind data transfers


Example: (Switch-LED connection to PORTC)

The circuit shows light emitting diode (LED) outputs and switch inputs connected to the port C pins.
Each bit in the data direction register (DDRC) specifies the direction of the corresponding pin in port
C. Each associated bit in the port C register will indicate the corresponding switch status or drive the
corresponding LED. Driving an LED high will turn it off and driving it low will turn on the LED.
When the switch is open, voltage at a port C input is 5 V. When a switch is closed, the corresponding
port C input is pulled low to ground.

70

Example: Seven-Segment display

a
f

g
e

c
d

ldp

rdp

Each segment of a seven-segment display is an LED. A character can be displayed by illuminating


some of the segments in the group of seven. Most displays include extra segments to be used as
decimal points. There are two types of seven-segment LEDs:
1. Common anode connection
( current is sinking when bit is low)

2. Common cathode connection


( current is sinking when bit is high)

5v

b0

I
R

R
a
b0
x

0 0 1 1 0 0 1
g f e d c b a
0: segment illuminated

g f
e d c
1: segment illuminated

71

In general instead of isolated current limiting resistors, drivers such as MC14495-1 Hexadecimal-toseven Segment Latch/decoder ROM/driver are used. The MC14495-1 accepts a binary number,
decodes it, and drives the appropriate segments to display the number.
B0
B1
B2
B3

MC 14495-1

B4

LE

7 segment
display

Example: Write a software to display the digit 5 when port C is connected to a noninverting buffer.
The buffer drives a common anode seven-segment display. Assume no decimal point is connected
(dp) g f e d c b a
1 0 0 1 0 0 1 0 = $92

DISP5
REGBAS
PORTC
DDRC

EQU
EQU
EQU
EQU

$92
$1000
$03
$07

; binary number for coding 5


; register block pointer
; Port C register address offset
; Port C data direction register address offset

LDX
BSET
LDAA
STAA

#REGBAS
DDRC,X $FF
#DISP5
PORTC,X

; point to registers block


; define portc as output
; load the number
; send data to portc

BEGIN

Example: If you do not use a hexadecimal-to-seven segment decoder, you have to do the conversion
using a look-up table.

LDY
LDX

#REGBAS
#TABLE

LDAB DATA
ABX
LDAA $00,X
STAA PORTC,Y

; TABLE can be an EEPROM location to mark the


; beginning of 16-byte block
; get single digit hex representation of data

72

KEYBOARD INTERFACING

12-key keypad circuit


Each key has a momentary contact switch that is connected to an intersection of row and column
wires. When a key is released, an open circuit exists between all wires/terminals. When a key is
pressed the contact closure connects the row and column wire. Thus, a short circuit exists between
row and column wires when a key is pressed. To determine which key is pressed, a microcontroller
must scan the rows and columns to identify the row and column intersection of the short circuit. A
keyboard decoder can drive a signal to a column and sense the row lines to determine which key is
pressed, if any. Port C is a convenient port to use (see the following figure) because its lines can be
configured as input or output. To identify the key code, the microprocessor scans each contact in
sequence.

73

Simple keyboard interface


Debouncing
Bouncing is the tendency of any two metal contacts in an electronic device to generate multiple
signals as the contacts close or open. When you press a key on your computer keyboard, you expect a
single contact to be recorded by your computer. In fact, after the initial contact, a bounce or lightening
up of the contact and then contact again occurs for a number of times. A similar effect takes place
when a switch made up of a metal contact is opened. The usual solution is a de-bouncing device or
software which ensures only one of contact events is registered within a given time period (usually
milliseconds).
Example: Keyboard decoding
ORG
MAIN LDS
LDX
JSR
MAIN1
JSR
JSR
BRA

$100
#$00FF
#REGBAS
INITKYBD

; initialize stack
; point to registers
; initialize keyboard interface

GETKEY
BREAKKEY
MAIN1

; wait for key to be pressed


; then wait for it to be released
; and repeat loop

* Subroutine INITKYBD
* Initializes the keyboard interface
* Calling Register
*
IX = register block address
* Return Registers
*
CCR affected
INITKYBD
PSHA
; preserve registers
LDAA #%00001111
STAA DDRC,X
; PC0-3 output, PC4-7 input
PULA
; restore registers
RTS
; return

74

* Subroutine GETKEY
* Waits for key to be pressed and returns its key code
* Calling Registers
*
IX = register block address
* Return Registers
*
ACCA = key code
*
CCR affected
GETKEY
PSHB
; preserve registers
GETKEY1
JSR
IDKEY
; return key code in ACCA
CMPA #0
; if key == 0 then repeat scan
BEQ GETKEY1
JSR
DEBOUNCE ; debounce delay
PSHA
; save key found prior to debounce
JSR
IDKEY
; return new key code in ACCA
PULB
; if key != key-1 then repeat scan
CBA
BNE GETKEY1
; else return
PULB
; restore registers
RTS
* ---------------------------------------------------------* Subroutine BREAKKEY
* Waits for key to be released (break condition)
* Calling Registers
*
IX = register block address
* No return registers except that CCR affected
BREAKKEY
PSHA
BREAK1
JSR
CMPA
BNE
JSR
JSR
CMPA
BNE
PULA
RTS

IDKEY
#0
BREAK1
DEBOUNCE
IDKEY
#0
BREAK1

; key code of zero


; means break occurred
; if break detected then debounce
; and check for break again
; if no break then repeat
; else return

* Subroutine IDKEY
* Returns key code from keyboard. A key code of zero
* means that no key was pressed.
* Calling Registers
*
IX = register block address
* Return Registers
*
ACCA = key code
IDKEY
PSHY
PSHB

; preserve registers

75

LDY #KYTAB
CLRA
IDKEY1
INCA
INY
LDAB 0,Y
STAB PORTC,X
ANDB #$F0
PSHA
LDAA PORTC,X
ANDA #$F0
CBA
PULA
BEQ IDKEY2
CMPA #12
BLO IDKEY1
CLRA
IDKEY2
PULB
PULY
RTS

; point to table, init keypt


; key = 0
; key++
; keypt++
; drive port C outputs
; mask off LS nibble
; preserve key
; mask off LS nibble
; if portc == *keypt then return
; note CCR is not unaffected, so next decision is about CBA result
; if key < lastkey (12)
; then repeat idkey1
; else key = 0 if no key pressed
; restore registers
; return(key)

* Subroutine DEBOUNCE
* Delay 10 ms at E = 2 MHz
* No calling or return registers
DEBOUNCE
PSHX
LDX #$0D06
* this is the delay loop
DEBOUNCE1
DEX
BNE DEBOUNCE1
PULX
RTS

; preserve register
; init loop counter

; restore register
; return

* Look-up table to map port C data to each key code


* Note that interface has PC7 connected to logic high
KYTAB
FCB
FCB
FCB
FCB
FCB

$FF
$EE, $DE, $BE
$ED, $DD, $BD
$EB, $DB, $BB
$E7, $D7, $B7

; key code of zero, don't care

76

Strobed I/O
An I/O port may have to read a sequence of bytes or transmit a sequence. Parallel communication
interfaces used in printers, floppy disks and parallel buses for peripheral communication use control
signals to coordinate the transfer of data. The simplest controlled data transfer technique is strobed
I/O. This method of performing I/O operations uses a control line, the strobe, to notify the receiving
unit of the availability of data. When a microprocessor sends data to a peripheral, it tells the peripheral
that data is available by sending a strobe signal. Similarly, if the microprocessor is reading data from a
peripheral, it has to know when the next data is sent. The peripheral can send a strobe signal to notify
the microprocessor that new data is available.
Basic strobed I/O operation:
Device performing the write places data onto data bus (its output port)
Strobe signal is asserted (for 2 cycles in 68HC11)
Strobe signal causes data to be latched into input port of the receiving device
Strobe signal causes an I/O interrupt to occur or a flag to be set -- in either case the receiving
device is signaled to indicate that new data has arrived
It is up to the receiving device to read the new data at its input port in a "timely" fashion
Two control pins for strobed I/O: Strobe A (STRA) and strobe B (STRB).
68HC11 register support for strobed I/ O
DDRC
PORTCL
PORTC
PORTB
PIOC

-- data direction register for port C (at $1007)


-- port C input latch -- data is latched on STRA edge (at $1005) used for strobed
and handshake I/O
-- input pins for port C -- not latched (at $1003)
-- latched output data port B outputs data using STRB (at $1004)
-- parallel I/ O control register (at $1002) determines how the microcontroller will
behave for parallel operations.

PIOC register explanation:


STAF (Strobe A Flag)
0 = Inactive
1 = Set at the active edge of STRA pin.
The Strobe A Flag bit can be read by the program. It is set by the STRA active edge which is defined
by the state of the EGA bit. The programmer can use the STAF to find out if data has been latched
into PORTCL. A two-step process clears the STAF bit. First, the PIOC register is read. If the STAF
bit is set, reading the data in PORTCL clears the STAF bit.

77

STAI (Strobe A Interrupt Enable)


0 = No hardware interrupt generated (default).
1 = Interrupt requested when STAF = 1.
The STAI bit enables or disables the interrupt request from being generated when STRA is asserted.
CWOM (Port C Wire-OR Mode)
0 = Port C outputs normal (default)
1 = Port C outputs Open-drain
The CWOM bit in the PIOC allows the outputs to be configured as open-drain, wire-OR bits to be
connected directly to a bus that has pull-up transistors.
HNDS (Handshake simple strobe mode select)
0 = Simple strobe mode (default)
1 = Full handshake mode.
OIN (Output/Input handshake select) (Only in handshake mode)
0 = Input (default)
1 = Output
PLS (Pulse mode select for STRB Output) (Only in handshake mode)
0 = STRB level active
1 = STRB pulses
EGA (Active edge select for STRA)
0 = High to low (falling)
1 = Low to high (rising, default)
INVB (Invert STRB out) (Only in handshake mode)
0 = STRB active low.
1 = STRB active high (default)

Strobed input operations using PORTC

Data is placed at the input pins of PORTC


STRA is asserted by peripheral device, causing
o Data to be latched into PORTCL
o STAF flag to be asserted
o Interrupt initiated, if interrupts are enabled
Data is read into the processor from PORTCL
To clear STAF, read PIOC first and then PORTCL

Example: (transfer 10 bytes from port C into a memory array)


ORG $100
LDX
CLR
LDAA
STAA
LDY
LDAB
CIN

#REGBAS
DDRC,X
#$02
PIOC,X
#PTR
#$0A

BRCLR PIOC,X $80 CIN

; configure port C as input


; configure PIOC register
; active STRA is rising edge
; initialize storage pointer
; initialize byte counter (10 bytes are going to be read)
; poll STAF bit to detect the rising edge in STRA signal
; same as LDAA PIOC,X, ANDA #$80, BEQ CIN

78

LDAA PORTCL,X
STAA 0,Y
INY
DECB
BNE CIN
STOP

; read port CL to get the input when STRA was detected


; and store it
; repeat 10 times

; then stop

Strobed Output
Peripheral device is connected to PORT B
When the MCU writes to PORT B,
o Data is placed on PORT B pins,
o STRB is automatically asserted low for 2 clock cycles.
Peripheral device should use STRB to latch the data
STRB can be configured as active-high or active-low
Example: (transfer 10 bytes from a memory array to the port)
ORG $100
LDY #PTR
; initialize data pointer
REPEAT
LDAA 0,Y
; send out data when it occurs
STAA PORTB,X
; note, MCU also pulses STRB low for two E cycles
INY
; repeat for next data transfer
CPY #PTR+10
BEQ EXIT
BRA REPEAT
EXIT
...
Example: You are given the following components:
0

BCD
input

a
b
c
d

Display

A simple unencoded keypad organized as a 2x5 matrix,


in which the bouncing is eliminated by the switch
hardware. A switch at a cross point connects the rows
and columns when pressed and there is no need for
software debounce handling.

An output device, which displays the BCD number at its


input terminals. The inputs are latched and displayed
each time LE signal is activated.

LE

You are required to design an M68HC11 based system such that the system displays the number code
of the pressed key. Each time a new key is pressed, the display will be updated accordingly. In your
system, use interrupt driven strobed I/O technique. Logic one and zero are available but no other
components, apart from resistors and logic gates are available.
a) Give the connection diagram of your system that connects the given components to M68HC11 to
perform the required task assuming that processor operates in the single-chip micro-controller
mode.

79

b) Using your connection diagram, write a complete M68HC11 program to do the required task. The
display should show zero initially. Write your program in assembly language using labels. For
clarity, give as much comments as possible and use a reasonable number of instructions.
Solution:
to 5 pull-up resistors

PC7

PC6
PC0
PC1
PC2
PC3
PC4

M68HC11
STRA
PB0
PB1
PB2
PB3
STRB

a
b
c
d

Display

LE

REGBASE EQU $1000


PIOC EQU $02
PORTC EQU $03
PORTB EQU $04
PORTCL EQU $05
DDRC EQU $07
PORTDIR EQU %11000000
PIOCDATA EQU %01000000

ORG $IRQ_PSEUDO_VECTOR
JMP STAF_ISR
ORG $5000
LDS #STACKBASE
LDX #REGBASE
LDAA #PORTDIR
STAA DDRC,X
LDAA #PIOCDATA
STAA PIOC,X
BCLR PORTC,X $CO
CLI

; PC7-6: output, PC5-4: input


; STAI enabled, simple strobe mode selected
; STRA falling edge, SRTB automatically active
low.
; address of the interrupt pseudo vector
; jump to the address of the interrupt subroutine
; main program
; initialize stack address
; initialize register base address
; initialize port C directions
; initialize port C control register
; clear Port C 7-6
; enable interrupt

CONT
WAI
BRA CONT

80

STAF_ISR
JSR INKEY
STAA PORTB,X
EXIT RTI

; interrupt subroutine
; if an interrupt occurs go to INKEY sunroutine
; store ACCA to Port B

INKEY
BCLR PORTC,X $80
BSET PORTC,X $40
LDAB PORTC,X
CLRA
CLR OFFSET

; Prot C 7 is cleared
; Port C 6 is set
; read Port C
; ACCA stores the pressed keys column number
; for first row/ second row separation

SHIFT
LSRB
BCC FOUND
INCA
CMPA #$05
BNE SHIFT
LDAB #$05
STAB OFFSET
CLRA
BSET PORTC,X $80
BCLR PORTC,X $40
LDAB PORTC,X
BRA SHIFT
FOUND
ADDA OFFSET
LDAB PIOC,X
LDAB PORTCL,X
BCLR PORTC,X $C0
RTS

; if the checked bit is clear then it is the pressed key


; otherwise increment ACCA
; if the pressed key is in first row
; continue to check
; otherwise continue checking with the second row

; obtain the pressed keys number from the column


number and offset
; clear STAF
; clear Port C 7-6
; return to the interrupt subroutine

81

Handshaking I/O
Strobed input includes a signal from the peripheral telling the MCU that data is available. But
there is no signal from the MCU to the peripheral telling it that the MCU is ready to receive
data. Similarly, strobed output includes a signal for the MCU to tell the peripheral that data is
available. But there is no signal from the peripheral to the MCU to tell the MCU that the
peripheral is ready to receive data.
When there is a transfer of data, there may be a set of rules, which defines when and how to
transfer each byte. This set of rules is known as a data exchange protocol. A protocol is a set
of standard procedures used in data communications that coordinates the transmitting and
receiving of information.
The handshake protocol is an agreement whereby the receiver acknowledges each unit of data
it receives. The transmitter waits for this acknowledgement before it sends the next unit. A
parallel I/O subsystem handshake protocol in general, transfers each byte as a unit.
The 68HC11 supports automatic handshaking for parallel I/O for port C. This is determined
by configuring the control register PIOC. An automatic handshake means that the hardware
responds to certain signals automatically without using any program instructions.
It is possible to use PORTCL, STRA and STRB to set up a full handshaking I/O transfer
protocol. In this case STRA is always used as a pathway for peripheral communication to the
MCU and STRB is always used for communication from the MCU to the peripheral.
To use automatic handshaking, the HNDS bit of PIOC should be set to 1, and the OIN should
be set to 0 for input handshake and 1 for output handshake.
Input Handshake

82

There are two options for the signal going from the MCU to the peripheral on STRB. If
PLS=0 then STRB will be level active, if PLS=1 then STRB will be pulsed. These two modes
are also known as interlocked and pulsed handshaking, respectively.
Pulsed input operation with handshake:
The peripheral will generate a pulse on strobe A to indicate that it has sent data. The 68HC11
responds to the pulse. It should have a program that responds by reading the data in. When
68HC11 reads the data, it automatically acknowledges the peripheral device by pulsing
SRTB for two clock cycles. This is known as pulsed handshake operation.
The figure below shows the timing diagram for the case when 68HC11 is configured for
STRA active falling and STRB active low. To cause the output acknowledge pulse in input
handshake mode, the PORTCL register must be read by 68HC11 software after reading
PIOC.

Summary:
Peripheral pulses STRA to indicate that data is present
When 68HC11 reads the data (from PORTCL), it automatically generates an
acknowledgment strobe on STRB for 2 cycles
This mode is selected by initializing the PLS bit (bit 2 of the PIOC) to 1

Interlocked input operation with handshake:


In this case STRB acts like a ready signal. It is active only when the MCU is ready to read
data. This is its normal condition. When it is busy with the process of reading in data, the
ready line is deasserted. It asserts again after the MCU has read the data.
Figure below shows interlocked operation when strobe B, the ready line, is active low. When
the peripheral sees the ready line deasserted, it should follow the rules by not sending new
data at that time. When the 68HC11 reads the contents of data latch register PORTCL, strobe
B asserts automatically to indicate that the MCU is ready for new data. The peripheral should
not send new data until it sees the strobe B line low.

83

Summary:
Here, STRB acts as a READY signal
Asserted = 68HC11 ready to receive data
Negated = 68HC11 is not ready -- do not send data now
This mode is selected by initializing the PLS bit (bit 2 of the PIOC) to 0

Example: Simple input handshake subroutine.


*Program simply reads in data as it comes.
*Subsystem configuration is interlocked

DIR
CONF

ORG $100
EQU $00
EQU $01

DEMOIN

LDX #REGBAS
CLR DIR
LDAA #$10
STAA CONF
JSR INITHNDS

;point to registers
;configure for input handshake
;HNDS=1 OIN,PLS,EGA,INVB=0

REPEATIN

JSR INHNDA
NOP
BRA REPEATIN

;read input data continuously

*Subroutine INITHNDS
*Initializes port c for handshake mode
INITHNDS

PSHA
BCLR PIOC,X $10
LDAA PIOC,X
LDAA PORTCL,X

;preserve registers
;put in strobe mode first
;then clear STAF if set

84

LDAA DIR
STAA DDRC,X
LDAA CONF
STAA PIOC,X
PULA
RTS

;set up port C direction

;restore registers

*Subroutine INHNDS
*Uses input handshake to read port C
INHNDS

BRCLR PIOC,X $80 INHNDS


LDAA PORTCL,X
RTS

;poll for STRA transition


;input strobed data and clear STAF

Output Handshake

Strobe A is an input ready or busy line and strobe B is an output strobe line. To configure
port C for output handshake, set bit OIN to 1.
Port C is used for output handshake operations, along with STRB and STRA
STRB is the output "data available" strobe
STRA is the acknowledgment / input ready strobe line
PIOC bit 3, OIN, set to 1 for output operations

Pulsed operation:
The 68HC11 writes data to port C (PORTCL) and automatically sends a strobe signal by
pulsing strobe B for two clock cycles. This tells the peripheral that data is available for it to

85

read. The peripheral reads the data and responds by asserting a ready signal. This tells the
MCU that the peripheral has read the data and is ready for new data. The 68HC11 sees the
ready signal as a transition on pin STRA. It sees it because the active edge of STRA causes
flag bit STAF to set. The MCU can now write the next byte to register PORTCL.
Figure below shows the timing diagram when strobes A (edge) and B (pulse) are configured
to be active low for polled I/O operation. The flag-clearing sequence of bit STAF is to read
control register PIOC first and then write to data latch register PORTCL.

Summary:
68HC11 writes data to PORTCL and automatically asserts STRB for 2 cycles
Peripheral device reads data upon receipt of the STRB strobe
Peripheral asserts its READY line (68HC11's input STRA line) to signal receipt
of data
PIOC bit 2, PLS set to 1 for pulsed mode
Interlocked operation:
Writing to PORTCL asserts strobe B. When the 68HC11 receives the acknowledgement (or
ready), it deasserts strobe B. Writing new data to PORTCL will assert strobe B again. For
interlocked output handshake the configuration routine must reset bit PLS and set bit OIN in
control register PIOC.

86

Summary:
Upon writing data to PORTCL, STRB is asserted
STRB negated only upon ACK

Example: Simple program code for output handshake.


*Program simply outputs same data when requested by peripheral.
*Subsystem is interlocked.

DIR
CONF
OUTDATA
DEMOOUT

REPEATOUT

ORG $100
EQU $00
EQU $01
EQU $02
LDX #REGBAS
LDAA #$FF
STAA DIR
LDAA #$18
STAA CONF
JSR INITHNDS
LDAA OUTDATA
JSR OUTHNDS
BRA REPEATOUT

;point to registers
;configure for output direction
;and output handshake, interlocked

*Subroutine uses output handshake to send data to port C and


*waits for peripheral ready before returning
OUTHNDS
OUTHNDS1

STAA PORTCL,X
;output data clears STAF also
BRCLR PIOC,X $80 OUTHNDS1 ;polling for STRA transition
RTS

87

Parallel subsystem summary

Ports B and C are available for I/O only in the single chip mode -- can be replaced by the
PRU (port replacement unit) when in expanded mode

Port A
3 input, 3 output, 2 bi-directional pins
Bits DDRA7 and DDRA3 in PACTL set direction for A7 and A3

Port B
Parallel output only (single chip mode)

Port C
Data register is PORTC
Latched register is PORTCL
Each bit is bi-directional
Direction set using the register DDRC

Port D
6 bi-directional pins, directions set by DDRD
Pin 6 = STRA, Pin 7 = STRB
(These pins become AS and R/W* in expanded multiplexed mode)

Port E
8-bit input only

Conditions on reset
All data direction bits are set to 0 (input)
Output port bits are set to 0
Input port bits are high impedance

Strobed I/O
Strobed output via Port B, strobed input via Port C
Detected edge on STRA causes input data to be latched in PORTCL and STAF flag in PIOC
register to be set (and interrupt, if enabled)
Writing data to Port B also pulses STRB

Handshake I/O
Port C used for either input or output operation
Input: read data from PORTCL
Output: write data to PORTCL

Some Parallel Interface Standards


The Centronics Parallel Interface is commonly used for printers. It defines how to connect a printer to
a computer and the form of the data sent to it. Microcontrollers often use this standard because many
printers use a microcontroller. Also, some other microcontroller systems send output to a printer. A
handshake protocol is defined by this standard.
IEEE-488 General-Purpose Instrumentation Bus (GPIB) standard is used for communication between
a computer and instruments. For example, a computer tells a digital storage csope to sample data and
send the data to the computer for analysis. IEEE-488 specifies the physical characteristics and the
protocol for transferring bytes of data. It also uses handshaking.

88

The small computer systems interface (SCSI) is designed for communications between personal
computers and intelligent I/O devices such as disk drives, tape dries and remote printers.

89

Chapter 8
Serial Input/Output
Asynchronous Serial Communications
Serial systems use a single line to transfer data bits one after the other. This reduces the number of
lines but slows down the rate of data transfer. The term asynchronous refers to the fact that each
device uses its own clock and the clocks do not need to be synchronized.
The asynchronous I/O subsystem for the 68HC11 is called the serial communications interface (SCI).
The SCI subsystem is used primarily for serial data communications. In asynchronous serial
communications, the communicating devices are remote (with a distance greater than a few meters),
for example they may communicate over a telephone line.
An asynchronous communication system (or network) must have at least one transmitter and one or
more receivers. A transmitter sends data to be read by the receivers.
Start and Stop Framing
In asynchronous serial communications, the basic unit (group of bits) of communication is the
character or data frame (normally a byte). The transmitter can send frames at any rate and whenever
it feels like. Hence there is a need for the receiver to know when a frame starts and ends. So each
character is framed by start and stop bits. In the figure given below a constant high signal is
considered to be idle with no data being transmitted; a start bit is always zero (0) and a stop bit is
always a one (1); data bits are transmitted with the LSB first; and voltage does not return to zero
between adjacent 1 bits.

90

Parity
It is used to detect single bit errors in communication. It refers to the quantity of 1 bits in a binary
number. The transmitter generates the parity and the receiver checks it. Parity bit is either a 0 or 1
depending on:
1. the type of parity selected, even or odd
2. the number of 1 bits in the data byte to be transferred
Example: (even parity convention) Assume that the transmitter wants to send the seven bit ASCII
code 0111000 with even parity. Then the transmitted bits (shown in order of transmission from left to
right) are as follows:
0
Start
Bit

0001110
Data
bits

1
1
Parity Stop
bit
bit

The number of one bits in the above frame excluding the start and stop bits but including the parity is
even.

Some possible framing configurations


Data Speed and Baud Rate
Serial data speed is the number of bits transmitted per second (bps). Baud is the rate at which the
signal changes. If each signal element represents one bit, then the data speed and baud rate are the
same. In some cases communication requires extra signal bits that are not data. In other cases, a signal
element may encode several bits. If each signal element represents more than one bit, then the data
speed and the baud rate are not equal to each other. In 6811 SCI, each signal element encodes 1 bit.

91

Baud rate includes the start, parity and stop bits. In asynchronous serial communications terminology,
for example, 9600 baud means that serial data (including the start and stop bits) is transmitted and
received at the rate of 9600 bits per second. Since there are overheads in the frame
number of data bits
Actual data transfer speed (bps) = -------------------------------- x baud rate
number of frame bits

RS-232 Interface Standard


Most equipments communicating in asynchronous serial mode use the RS-232 standard. This standard
defines the signal levels, connectors and pin assignments, among other things. A serial port is the
serial interface connector plus all the electronics required to make the interface fully functional.
The standard defines 25 different signals, although in practice few of these are used. Most RS-232
interfaces use a mechanical connector with 25 pins known as DB-25. Since few of the 25 signals are
ever used, many serial ports also use a DB-9 connector. It only uses 9 plug pins. These are shown in
the figure below. Only 3 signals are required for a connection: transmit data, receive data and signal
ground.

The RS-232 standard also uses the categorization of the standard organizations such as ISO and
CCITT for equipments of data communications into two types: data terminal equipment (DTE) and
data communications equipment (DCE). Normally, a DTE interfaces with a DCE in order to
communicate with another DTE that is also interfaced to a DCE. A DTE is the initial source of data or
the final recipient. Examples are terminals and computers. The DCE provides the functions to
establish, to maintain and terminate a connection. It also codes and decodes signals as required.
Examples are line drivers and modems for telephone communications. According to the standard, a
DTE uses a plug and a DCE uses a socket. One can make a direct connection between a DCE and a
DTE without crossing wires. But if a DCE is connected to a DCE or a DTE is connected to a DTE
then wires 2 and 3 have to be crossed. Because the two types use their transmit (TxD) and receive
(RxD) lines differently:
DTE: TxD transmits, RxD receives
DCE: TxD receives, RxD transmits
The logic levels used for RS-232 signals differ from the usual digital circuit logic. The nominal RS232 data signals are +12 V for logic 0 and 12 V for logic 1. These allow signals to be transmitted
over relatively long distances. Since the RS-232 signal levels differ from normal HCMOS or TTL
levels, it is necessary to use special driver chips for signal conversion. There exists driver chips for

92

interfacing TTL levels to RS-232 levels and one such interfacing example is as follows. In this
example the use of such a chip to build a RS-232 port for a 68HC11 is shown.

DCE

DTE

93

Protocols and Flow Control


A protocol is a set of rules for making connections and transferring messages. Flow control refers to
methods of stopping data transfers ad restarting them. When data is to be transferred, there have to be
agreed upon rules by both the transmitter and receiver. Some protocols used in the communications
industry are as follows:
Acknowledge/Not Acknowledge (ACK/NAK) Flow Control: The transmitter waits for the receiver to
acknowledge each block of data before the next block can be sent. Upon reception of a block of data,
the receiver checks it and send an ACK signal (or message) otherwise NAK is sent.
Cyclic Redundancy Check (CRC): Not a single parity but a longer check field is used for error
detection and correction. CRC uses a feedback mechanism to make a code word depend on the
previous history of the message. The transmitter calculates the code for the message block it sent and
adds it to the end of the block. The receiver also calculates the code based on the data it receives.
XON/XOFF Flow Control: A receiver might initiate or stop a transmitter by sending XON and XOFF
signals (messages).
BREAK Signal: used to abort a transfer in midstream or wake up a sleeping receiver. The break signal
drives the line low for longer than a frame time. Recall that each transmitted character has at least one
bit high, the stop bit. Also, an idle line is always high.
Communication Channel Types
There are three ways to transmit data along a communication channel:
1. simplex (unidirectional)
2. half-duplex (bidirectional but only one direction is active at a given time)
3. full-duplex (bidirectional and both directions are active at a given time)

94

Asynchronous Serial Communications Interface in M68HC11 SCI


The SCI is full duplex asynchronous, serial interface used by the 68HC11 microcontroller. With
additional conversion circuits the SCI can be used to communicate with remote devices using industry
standard cables, telephone lines, or radio transmitters. The SCI subsystem uses port D pin PD1 as a
transmit line and port D pin PD0 as a receive line. These lines can be enabled or disabled by one of
the SCI control registers (SCCR2). When disabled port D lines can be used as general parallel I/O
lines.
Transmitting a byte is a simple matter of writing bytes to a data register (SCDR). The SCI subsystem
handles the data framing requirements. It does not perform parity generation or checking
automatically. The microcontroller reads serial input by reading the data register to get each character
received. The SCI receiver automatically converts each framed serial character into a parallel byte.
The SCI system uses an internal clock tapped off the main microprocessor clock for serial transfer or
sampling of data. By configuring another control register (BAUD), a program can set the baud rate to
available integral fractions of the system frequency (E).
The receiver and transmitter are double buffered and although they operate independently, they use
the same baud rate and data format. The SCI subsystem uses one data register address ($102F) and
name (SCDR) for both registers. An instruction to write data to SCDR causes data to be sent to the
transmit data register (TDR). An instruction to read SCDR causes data to be read physically from the
receive data register (RDR). The system can send and receive 8-bit or 9-bit data; it has a variety of
interrupts and it is fully programmable.

Transmit Operation: The system writes a byte to TDR, which in turn is transferred to the output shift
register. If enabled, the ninth bit as determined by transmit bit 8 (bit T8 in SCCR1) is also transferred
to the shift register. Start and stop bits are generated automatically. The setting of the baud register
determines the shift rate. This can occur while the previous data byte is being shifted out. The term
double buffering is used to refer to the fact that while the shift register is shifting out a byte, the data
buffer is storing the next byte to be transmitted. When the shift register has completed shifting out the

95

byte, the SCI system automatically transfers the contents of the TDR buffer to the shift register. It
starts to shift it out immediately. Every time the SCI transfers data from the TDR to the output shift
register, it sets the TDRE (transmit data register empty) flag. Writing to TDR buffer clears TDRE flag
if SCSR is read first which arms the clearing mechanism.
Receive Operation: If the receiver is awake and a data frame is received, then the data is transferred
from the receive shift register to receive data register (RDR). If configured for 9-bits, the ninth bit (bit
R8 in SCCR1) is also transferred. The setting of register BAUD determines the rate of sampling and
shifting in. A receiver driver routine may read the RDR buffer any time while the next data is being
shifted in. This is also double buffering. In this case the buffer stores the most recent received byte. It
stores the currently received byte while the next byte is shifting in. The software should read the
buffer before the next byte has shifted in completely. Otherwise, it will miss reading the next data
byte. Each time a transfer occurs from the receive shift register to RDR, then RDRF (receive data
ready flag) is set. Reading the RDR buffer resets RDRF, if SCSR is read first which arms the clearing
mechanism.

SCI Related Registers and Their Programming

96

Receive Errors
Overrun Error Flag (OR) : Overrun occurs when a newly received character has been shifted
completely into the receiver before the microprocessor software has read the receive data register. An
occurrence of this error sets OR flag and any data currently in the shift register will be lost.

Noise Error Flag (NF): The receiver uses a sampling clock that has a frequency of 16 times the baud
frequency. Once the receiver has established the bit boundaries, it samples the bits during the eighth,
ninth and tenth cycles of the sampling clock. The system sets flag NF if these samples are not
identical.

97

SCI Software
Using and programming the SCI can be broken into three parts:
1. Configuration procedure,
2. Transmit procedure for each byte,
3. Receive procedure for each byte.
1. Configuration procedure:
Select the baud rate. Write to the BAUD register (SCP0-1, SCR0-2),
Select the word length and wake up. Write to the SCCR1 register (M, WAKE),
Enable interrupts, transmit, receive and wake up as required. Write to the SCCR2 register
(TIE,TCIE,RIE,ILIE,TE,RE,RWU)
2. Transmit procedure for each byte:
Poll the SCSR register or respond to the interrupt (read SCSR),
If applicable (M=1), write to T8 in the SCCR1 register,
If TDRE==1, write to the SCDR register.
3. Receive procedure for each byte:
Poll the SCSR register or respond to the interrupt (read SCSR),
If RDRF==1, then read SCDR register,
Option: If there is an error (OR|NF|FE==1), handle the error,
If applicable (M=1), read R8 in the SCCR1 register.

98

Example: 68HC11 needs to communicate over a serial line at 9600 bits per second, using 1 start bit, 1
stop bit, and even parity. Eight-bit characters will be transmitted, including the parity bit. Assume that
the system needs to transmit character string of arbitrary length. To transmit one string, the main
program places the characters into an array and then places $00 immediately after the last character
($00 should not be transmitted). The main program then initiates transmission by writing the first
character to the SCDR and placing the address of the second character in memory location
MEM_PTR. Write an ISR that will cause the remaining characters to be transmitted (It can access
and/or modify MEM_PTR). Use interrupt driven I/O only.
Solution:
Initially SCCR2 should contain 10001000.
XMT_ISR LDX #REGBASE
LDY MEM_PTR
LDAA SCSR,X
LDAA 0,Y
BEQ DONE
STAA SCDR,X
INY
STY MEM_PTR
DONE
RTI

; arm the clearing mechanism for TDRE flag


; get char from array
; if char==$00, exit
; else transmit that character which also clears TDRE

99

Chapter 9
Analog to Digital Conversion
Analog-to-Digital and Digital-to-Analog I/O
Analog refers to physical quantities that vary continuously instead of discretely. Physical phenomena
typically involve analog signals. Examples include temperature, speed, position, pressure, voltage,
altitude, etc. Microprocessors work with digital quantities (values taken from the discrete domain).
For a digital system to interact with analog systems, conversion between analog and digital values is
needed. Building blocks to perform the conversions are: (1) Digital to analog converters (DACs), (2)
Analog to digital converters (ADCs). A digital to analog converter has a digital input that specifies an
output whose value changes in steps. These step changes are in volts or amperes. The analog to digital
converter has an input that can vary from a minimum to a maximum value of volts or amperes. The
output is a digital number that represents the input value.

Transducers
A device that converts a process variable (ex. Car speed) into an electrical signal or vice versa.
Sensors (Input transducers): Potentiometer (position); strain gauge, piezoelectric device (force);
thermistor, thermocouple (temperature); photoconductive cell, phototransistor (light); current
transformer, SENSEFET (current); microphone (sound), etc.
Actuators (Output transducers): solenoids, relays, speakers; darlington transistors, triacs, etc.
Some common sensors

100

Signal Conditioning
Signal conditioning is sometimes necessary because raw sensor outputs are not always suitable for
analog-to-digital conversion.

Amplification : Op amps are preferred because of their performance characteristics


Open Loop gain: several hundred thousand, input current ~0, output
impedance ~0.
Filtering: LPF

Concepts and terminology


Definitions

Offset: minimum value


Span: maximum value minimum value
o Some common spans:
range of 0 V to 5 V: span = 5 V
range of 12 V to 12 V: span = 24 V
range of 4 mA to 20 mA: span = 16 mA
Weight: The analog change corresponding to a change in a bit in the digital number.
Step size: span / 2n (Typically, the digital representation is an unsigned n- bit integer) (n is
the number of bits in the corresponding digital code. e.g. n=0 for a 1-bit number)
Resolution: Same as step size. Weight of the LSB.

Example: Analog signal in range +5 to -5 volts, 8- bit ADC:


Offset = 5 V
Span = 10 V
Step size = 10 / 256 = 39.1 mV
Notice that the MSB has a weight of 5 V (= span/ 2), and the LSB has a weight of .0391 V
Equations
Analog number = (bn-1 21 + bn-2 22 + +b0 2n ) x stepsize + offset
= (digital number x step size) + offset
Digital number = (analog number offset)/ (step size)
These equations hold true as long as the numbers are within the range. If the input of an A/D is below
the minimum or above the maximum of the range, the corresponding digital value will be minimum or
maximum, respectively. In practice, extreme input swing beyond the specified range may damage the
device.
Example: 6-bit D/A converter, analog output range :-2.5 to 5 volts. Calculate the analog output when
the input is %010101 (decimal 21)
Offset : -2.5 V
Span: 7.5 V
Step size: 0.1172 V
Analog number = 21 x 0.1171 2.5 = -0.039 V

101

Example: As an example the following table lists some values for -5 V to +5 V analog range to 8-bit
digital conversion:
Analog (V)
Digital (hex)
-5
00
-3.75
20
-2.5
40
-1.25
60
0
80
1.25
A0
2.5
C0
3.75
E0
5-0.0391=4.961
FF
Digital-to-Analog Converters
A DAC takes an n- bit digital input and outputs a corresponding analog voltage. DAC systems
normally consist of three components: (a) A reference voltage, (b) The DAC itself, (c) An op amp for
output buffering.

102

Many digital-to-analog converters use R-2R ladder network. Inverted ladder type of network is shown
in the figure below. The switches are analog switches controlled by digital signals. The output voltage
(Vo) is proportional to the binary input. Each branch of the ladder network contributes current whose
value is proportional to the bit weight of that branch. The amplifier circuit sums the current
components to produce a voltage proportional to the binary input.

Interfacing DAC to microprocessor system


DAC integrated circuits are available with different bit resolutions. In principle, any DAC can be
interfaced to any microprocessor system. In practice, some combinations of DACs and
microprocessors are easier than others and require much simpler hardware and software in the
interface. Here, interfacing a 12-bit DAC to an 8-bit microprocessor will be considered. This will
serve to show how to mate different bit resolutions with different size data buses. Also, the
importance of double buffering will be illustrated.

103

The figure given above shows an interface for a microprocessor operating in expanded multiplexed
mode. The latches are used to convert a sequence of 2 bytes into one 12-bit word. To output a 12-bit
word, the microprocessor writes the data in two steps. First, it puts the upper 4 bits on the lower
nibble of the data bus. Then it selects the latch address. The address decoder decodes the address and
drives the latch chip select input low. Also, the microprocessor drives the address line A0 low so that
only the 4-bit latch accepts data from the data bus. Then the microprocessor repeats the sequence for
the lower 8 bits except that it drives A0 high. The other purpose of the latches is to provide the double
buffering. The updated latch data is not transferred to the DAC until the microprocessor drives the
control line to latch in data to the buffer in the DAC. DAC does not change its output until L is
driven low. Note that this is important when there is a change in the upper nibble.
Analog-to-Digital Converters
The function of ADCs is to quantize the analog voltage and then output the corresponding digital code
value. As with the DAC conversion, a full- scale analog voltage will be divided into 2n quantization
levels or steps for an n- bit digital coding scheme. Several techniques are used to do the conversion.
Among them successive approximation which has a medium conversion speed (nominally 20 ms) is
common in computer systems.

The ADC has a built in DAC. A sample and hold circuit stores an analog input. The ADC logic steps
through a sequence of trial-and-error guessing to find the digital equivalent of the input. It begins the
sequence by sending a digital signal that is at midrange to the DAC. The analog output V out from the
DAC is compared to the analog input Vin from the sample-and-hold circuit. Thus, the ADC
determines whether the analog input is above, at or below half scale. It continues determining to
which half of the next range selection the analog input belongs.
Successive Approximation example

104

68HC11 A/D Converter


105

The 68HC11 has a built-in A/D subsystem, but it does not have a D/A, although it can easily be
interfaced to one. External D/A converter such as DAC0808 ( 8-bit D/A) can be used. 68HC11 uses
an A/D which in turn uses a D/A to generate internal signals as part of the process to convert analog
to digital. This is common to many types of A/Ds.

68HC11 supports 8 input ADC channels


Channels are located on port E (Channel 0 on PE0, Channel 1 on PE1, etc.)
In performing A/D conversions, 4 conversions are performed as a "block," each taking 32
cycles -- 128 cycles total
Control registers:
o OPTION ($ 1039): ADPU and CSEL bits
o ADCTL ($ 1030): Control and status information
o ADR1 - ADR4 ($ 1031 - $1034): Result registers

106

More detailed description for conversion

DAC is replaced by a series of capacitors that are charged to the voltages that correspond to
the weights of each bit
During the sample mode, the capacitors are charged. This total charge is proportional to the
input analog signal. For the duration of the conversion process, this total charge remains
conserved. The A/D switches to the hold mode and then to the approximation mode. The
approximation mode is a sequence of successive approximation steps that switches different
capacitors to modify the input voltage to the comparator. The result of each step sets or resets
a corresponding bit in a successive approximation register (SAR).
VRH is normally set to the signal maximum (analog value for digital data $FF) and VRL is set
to minimum (analog value of $00). However, VRH should not be higher than 6 V and VRL
should not be lower than ground, and VRH - VRL should be greater than 2.5 V.
8-bit outputs from four successive conversions are placed into analog data registers ADR1ADR4.

68HC11 A/D related Registers


The MCU on the EVB has an 8-bit register at location $1030 that is the A/Ds control and status
register (ADCTL). Bits 0-5 are the control bits and may be read from or written to. Bit 6 is not used
and is always read as logic 0. Bit 7 is a status bit and can only be read. Data written to this bit is
ignored.

Conversion Complete Flag (CCF) Bit 7: Bit 7 is a read-only status flag. It is set automatically by
the MCU after the A/D completes the fourth conversion and the results are stored in the result
registers. This bit is cleared each time the ADCTL register is written to. Also, any time the ADCTL
register is written to, a new conversion sequence begins immediately. Note that a conversion
operation begins immediately after writing to the ADCTL register. Also, by writing to the ADCTL

107

register, the programmer stops any conversion in progress and begins a new one. If the MCU is
programmed for the continuous scan mode (bit 5 = logic 1), then the CCF bit may remain set and the
result registers are updated automatically.
Scan Control (SCAN) Bit 5: This bit is also known as continuous scan control. It allows the
programmer to choose between a single conversion sequence and a continuous sequence. When the
SCAN bit is 0, the A/D is in the single conversion mode, thereby performing four conversions and
filling the four result registers. No more conversions are performed at this time. When this bit is 1, the
A/D is in its continuous conversion mode. Conversions are performed in a round-robin fashion and
the result registers are continuously updated.
Multiple/Single Channel Control (MULT) Bit 4: Bit 4 of the ADCTL register is used to select
between a single-channel conversion or a four-channel conversion. When this bit is 0, single-channel
conversion is selected. The A/D selects a single channel (according to the binary pattern in the CDCC-CB-CA bits) and performs four consecutive conversions placing the digital data into the result
registers. The first conversion goes to ADR1, the second into ADR2, and so forth. When bit 4 is set,
the A/D performs a single conversion on each channel in the group selected by the CD and CC bits
(CB and CA are ignored). Tables given below show which group is selected and which register stores
the data for each channel. Binary patterns in the CD-CA bits for 8 to 11 are reserved and 12 to 15 are
for factory testing and are not shown in this table.
Channel Select Bits (CD, CC, CB, CA) Bits 3-0: These four bits select the channel or channels to
be used for the A/D conversion.
Channel selection when MULT (Bit 4) = 0
CC
CB
CA
Port E
0
0
0
PE 0
0
0
1
PE 1
0
1
0
PE 2
0
1
1
PE 3
1
0
0
PE 4
1
0
1
PE 5
1
1
0
PE 6
1
1
1
PE 7

CD
0
0
0
0
0
0
0
0

CD
0
0

CC
0
1

CB
x
x

Channel selection when MULT (Bit 4) = 1


CA
ADR1
ADR2
ADR3
x
PE0
PE1
PE2
x
PE4
PE5
PE6

108

ADR4
PE3
PE7

Timing Diagram for 4 conversions

Initialization
The software initialization procedure for the A/D includes enabling the charge pump and defining the
conversion clock source.A charge pump is a system of switching capacitors to redistribute a stored
charge. The A/D power-up (ADPU) bit in the system configuration option register (OPTION) is set to
charge pump (ADPU = 1 means A/D charge pump is powered up). Then, the MCU should wait at
least 100sec. It is only necessary to enable it once after a power-on reset.
The successive approximation circuit can use the system clock E, if it is greater than 750 kHz. This
low-frequency limit is necessary to minimize charge leakage. The software selects E as the clock
source by clearing the clock select bit (CSEL) in OPTION register residing at $1039. To select an
internal RC oscillator (around 2 MHz), the software should set the CSEL bit.
7
ADPU

6
CSEL

5
IRQE

4
3
2
DLY
CME
0
Option Register, $1039

1
CR1

0
CR0

Example: Initialization subroutine for A/D


* Subroutine STARTAD
* Powers up A/D. Must be run before using it after reset or a power-down sequence.
* In this case, uses E clock as source. No calling or return registers except CCR affected
STARTAD
PSHX
LDX #REGBAS
BSET OPTION,X $80
BCLR OPTION,X $40
JSR DLY100
PULX
RTS

; preserve IX
; point to registers
; ADPU = 1 to power up
; CSEL = 0 to select E clock
; wait 100 us
; restore IX
; return

109

Example: Subroutine for single channel operation


* Subroutine INAD
* I/O handler routine for analog input using continuous scan. Calling program must execute
* this subroutine after subroutine STARTAD and before reading the result.
* Calling registers
*
IX = register block address
*
ACCA = channel number from 0 to 7
* Return registers
*
ACCA = analog result
INAD
ANDA #$07
*
ORAA #$20
STAA ADCTL,X
*
* wait for first conversion done
INAD1
BRCLR ADCTL,X $80 INAD1
*
LDAA ADR4,X
RTS

; ensure that bits 3 to 7 clear


; note that others select channel
; SCAN=1, MULT=0
; start conversion
; also clears CCF

; CCF set at this point


; read any result register ;in this case, the most recent
; return

Example: You are required to design a M68HC11 based system, which continously monitors eight
analog voltages v0 to v7 (all within 0-5V range) and displays the index of the channel with the smallest
analog voltage at a single digit commonanode seven-segment display.
a) Give a simple connection diagram of the system assuming that the display is connected to port B
of the M68HC11, which operates in the single-chip micro-controller mode.
b) Write a complete program using M68HC11 assembly language with labels to perform the
required task. Write explanotary comments and use a reasonable number of instructions.
Solution:
PE7
PE6
PE5
PE4
PE3
PE2
PE1
PE0

V7
.
.
.

V0

M68HC11
+5v
PB0
PB1
PB2
PB3
PB4
PB5
PB6
PB7

a
b
c
d
e
f
g

110

Anode

REGBASE EQU $1000


PORTB EQU $04
ADCTL EQU $30
ADR1 EQU $31
ADR2 EQU $32
ADR3 EQU $33
ADR4 EQU $34
OPTION EQU $39
ORG $5000
LDS #STACKBASE
LDX #REGBASE
BSET OPTION,X $80
BCLR OPTION,X $40
JSR DLY100

; ADPU = 1 to power up
; CSEL = 0 to select E clock
; wait 100 us assuming that the subroutine exists

START
LDAB #$FF
CLR MININDEX
CLRA
CONVERT
STAA ADCTL,X
WAIT
BRCLR ADCTL,X $80 WAIT
CMPB ADR4,X
BCS SKIP
LDAB ADR4,X
STAA MININDEX
SKIP
INCA
CMPA #$08
BNE CONVERT
LDAA MININDEX
JSR GET_7-SEG_CODE
STAA PORTB,X
BRA START

; holds channel index


; single scan, single channel, channel no in AccA
; also clears CCF and starts conversion
; wait until CCF is set

; use the subroutine to convert the index to 7-segment code

111

Chapter 10
Programmable Timer Subsystem
The timer section in the M68HC11 is based ona 16-bit counter operating from the system Eclock. It provides basic real time functions with the following features:

Timer overflow to extend the 16-bit capability of the timer section counter.
Output compare function that can generate a variety of waveforms by comparing the 16bit timer counter with the contents of a programmable register.
Input capture function that can latch the value of the 16-bit timer counter on selected
edges of external control signals.
Programmable and periodic interrupt generator, called the real time interrupt.
Pulse accumulator to count external events or act as a gated timer counting internal clock
pulses.
Computer operating properly (COP) watchdog timer.

The timer subsystem is the most complex subsystem in the M68HC11 and it involves many
control registers and control bits. All timer functions have interrupt controls and separate
interrupt vectors. Figure 10.1 illustrates the timer subsystem block diagram.
Timer subsystem registers:
Data registers
TCNT
TIC1-TIC3
TIC1-TIC5
PACNT

Timer count register


Timer input capture registers 1 to 3
Timer output compare registers 1 to 5
Pulse accumulator count register

Control registers
TCTL1
Timer control register 1 (output compare specifications)
TCTL2
Timer control register 2 (input capture edge specifications)
TMSK1
Main timer interrupt mask register 1 (output compare and input capture
interrupt enable bits)
TMSK2
Miscellaneous timer interrupt mask register 2 (other interrupt enable bits)
PACTL
Pulse accumulator control register
OC1M
Action mask register
OC1D
Action data register
Status registers
TFLG1
Main timer interrupt flag register 1 (output compare and input capture flags)
TFLG2
Miscellaneous timer flag register 2 (other system flags)
For the names and positions of various control and status bits see also Fig 11.1 in your
reference book (Spasov).

112

Fig. 10.1 Main timer system block diagram


Port A Pins
If the timer function is not enabled Port A pins can be used as general input/output pins.
Otherwise port A pins have certain other functionality related to the specified timer subsection
operation.
Basic Timer
The key to the operation of the M68HC11 is the 16-bit, free running counter called the TCNT.
It is input is the system E-clock, which may be prescaled (divided) by 1, 4, 8 or 16. Starting
from $0000 at system reset, the counter counts forever and the programmer can read its
113

contents at any time. When it reaches $FFFF, it is reset to $0000 and the timer overflow flag
(TOF in TFLG2) is set. This state can be detected either by polling or by an interrupt if timer
overflow interrupt enable (TOI in TMSK2) bit is set.
Clearing Timer Flag
The flag bits in both of the status registers TFLG1 and TFLG2 are cleared by writing a 1 to
the bit to be cleared. For example to clear TOF, you may use the following instructions:
LDAA #$80
STAA TFLG2, X
(assuming IX=$1000 and TFLG2 is the offset relative to
the base register address)
Example:

REPEAT
SPIN1

LDS #STACK
LDAA #%10000000
STAA TFLG2
LDAA #NTIMES
STAA COUNTER
TST TFLG2
BPL SPIN1
LDAA #%10000000
STAA TFLG2
DEC COUNTER
BNE SPIN1
JSR RING_A_BELL
BRA REPEAT

; clear the TOF bit


; init the counter variable
; wait until TOF (bit-7 in TFLG2) is set
; reset TOF
; decrement the counter
; ring a bell if the counter reaches to 0
; continue by re-initializing the counter

The above program rings a bell every NTIMES*65536 E-clock cycles assuming a prescaling
factor of 1 (NTIMES*32.768 ms with a 2 Mhz E-clock).
The same example with interrupt driven approach:
Timer overflow interrupt vector: $FFDE:$FFDF
Buffalo monitor vector jump table (pseudovector) for timer overflow interrupt: $D0:$ D2)
ORG $00D0
JMP ISR

START
ISR

ORG PROG
LDS #STACK
CLR DATA
LDAA #%10000000
STAA TFLG2
STAA TMSK2
CLI
BRA START
INC DATA
LDAA DATA

; set the timer overflow interrupt pseudo vectors

; reset TOF flag


; enable the timer interrupts (set TOI bit)
; enable processor interrupts

; increment DATA

114

CMPA #NTIMES
BNE ENDIF
JSR RING_A_BELL

ENDIF

CLRA
STAA DATA
LDAA #%10000000
STAA TFLG2
RTI

; check if it is equal to NTIMES


ring a bell if DATA is equal to NTIMES

; reinitialize DATA
; reset TOF

Output Compare
The output compare allows more accurate timing delays than the timer overflow flag. The
following figures describe the output compare operation

10.2

10.3
115

A 16-bit timer output compare register, TOCn, may be written by the program with a doublebyte store instruction, e.g., STD TOC5. The other 16-bit compare register is the free-running
TCNT counter. A comparison is made at every bus clock cycle (E-clock cycle) and when the
TOCn is identical to TCNT, the output compare flag, OCnF, is set. OCnF is also ANDed with
an output compare interrupt eneable bit to generate an interrupt. The output compare
functions are controlled by several registers as follows:

116

Example: Generate a 10 msec (which is less than the minimum timer overlow duration) pulse
assuming a 2 Mhz E-clock.
* Drive one-shot high pulse for 10 ms
* with E = 2 MHz and prescale = 1
ORG $100
PWIDTH

EQU 20000

LDD TCNT,X
STD TOC2,X
PULSE
BSET PORTA,X $40
LDAA #$80
STAA TCTL1,X
LDAA #$40
STAA TFLG1,X
LDD TCNT,X
ADDD #PWIDTH-17
STD TOC2,X
PULSE1
BRCLR TFLG1,X $40 PULSE1

;prevent premature
;OC2 compare
;drive PA6/OC2 high
;configure OC2 to clear
;and disconnect other OCx's
;clear OC2F if set
;arm TOC2 for 10-ms trigger

BCLR PORTA,X $40


LDAA #$40
STAA TFLG1,X
BCLR TCTL1,X $80

;wait for trigger by polling for OC2F high


;now OC2 becomes low automatically
;clear internal latch bit for PA6 and
;
; then clear OC2F
;disconnect OC2

BRA *

;end for now

117

One Output Compare Controlling Up to Five Outputs


The Output Compare 1 channel has special features that are controlled by the OC1M and
OC1I registers. Output Compare 1 can simultaneously switch up to five outputs.

OC1M and OC1D work together to define the action taken on port A, bits 7-3. OC1M is a
mask register and a 1 in a bit position in the mask means that the corresponding data bit in the
data register, OC1D, is transferred to the output bit in port A. The transfer from OC1D to port
A occurs when a successful output comparison is made. Thus up to five bits can be
simultaneously changed by one output comparison.
Note that Output Compare 1 can be used with another output compare channel to produce
very short duration pulses (as short as one E-clock) (see the example program below).
Forced Output Compares
CFORC register bit is ORed with the output compare flag. Therefore, writing a one to this
register forces a comparison action to occur at the output pins. This forced comparison does
not set the output compare flag and therefore no interrupt will be generated.

,
The above figure illustrates some of the capabilities of the timer subsection. Using the output
compare function, it is possible to generate a one shot or a fixed or variable duty cycle
continuous waveforms.

118

Example: A 2 s (very short duration) pulse generation at every 32.768 ms on port A bit-6.
TCNT EQU $0E
TFLG1 EQU $23
TCTL1 EQU $20
TOC1 EQU $16
TOC2 EQU $18
OC1M EQU $0C
OC1D EQU $0D
PROG EQU $C000
DATA EQU $D000
STACK EQU $DFFF
REGS EQU $1000
ORG PROG
LDS #STACK
LDX #REGS
LDD TCNT, X
STD TOC1, X

; grab the value of the TCNT register

ADDD #4
STD TOC2, X

; set TOC2 to compare 4 cycles later

LDAA #%11000000
STAA TFLG1, X

; reset output compare flags

LDAA #%01000000
STAA OC1D, X
STAA OC1M, X

; init the data and mask registers

LDAA #%10000000
STAA TCTL1, X

; setup OC2 to reset the bit

BRCLR TFLG1, X %01000000 SPIN


LDAA #%11000000
STAA TFLG1, X
BRA SPIN

; wait until OC2F is set


; reset OC1F, OC2F

SPIN

; continue

119

Input Capture

The input capture hardware is shown above. Three 16-bit Timer Input Capture registers,
TIC1-TIC3, latch the value of the free-running counter in response to a program-selected,
external signal. For example the length of a positive pulse can be measured by capturing the
time at the rising edge and then again at the falling edge.

The above figure illustrates again some of the capabilities of the timer subsection. Using the
input capture function, it is possible to make pulse width measurements, period measurements
or count pulses.

120

121

Example: Write a subroutine, which determines the period of a square wave in units of clock
cycles (assume that the period is <65536 cycles).
REGS EQU $1000
TCTL2 EQU $21
TFLG1 EQU $23
TIC1 EQU $10
FIRST RMB 2
GET_PERIOD
PSHX
LDX #REGS
LDAA #%00010000
STAA TCTL2, X

; init IC1 for rising edge

LDAA #%00000100
STAA TFLG1, X

; reset IC1 flag

SPIN1
BRCLR TFLG1, X %00000100 SPIN1 ; wait for the next rising edge by waiting IC1F
LDD TIC1, X
STD FIRST

; get the count that was latched


; store it

LDAA #%00000100
STAA TFLG1, X

; reset IC1 flag

SPIN2
BRCLR TFLG1, X %00000100 SPIN2 ; wait for the next rising edge
LDD TIC1, X
SUBD FIRST

; get the count that was latched


; store it

BPL EXIT
ADD #$FFFF

; correct if the result is negative

EXIT PULX
RTS

Stepper Motor Control Using Output Compare


Stepper motors are electric motors that rotate from one position to the next in dicsrete
intervals (steps). A step refers to a fraction of a full 360 degrees of the motor shaft (or rotor)
rotation. The primary stepper motor application is position control.
A common stepper motor type is the four-phase stepper motor.

122

In four-phase stepper motors, the direction (polarity) of the current through the windings
determines which position the motor steps to next. A high level of current called the rush
current is required to cause shaft rotation. Each change of polarity at the terminal of a winding
is called a step of phase shift. A sequence of logic pulses steps the motor from one position to
the next.

This causes the shaft (rotor) to rotate in precise angular increments per step. The phase
sequence may begin anywhere but it must continue in the specified order. For example, the
following waveform rotates the motor for 10 steps clockwise.

During the period when no rotation occurs, the motor windings must be supplied with a lower
level of current called the hold current. Since high currents are required to drive the stepper
motor, a MOSFET latch with open drain outputs may be used to supply pulses to the
windings. TPIC2406 Intelligent Power Quad MOSFET Latch by Texas Instruments is one
such example.

123

Stepper Motor Control Utility Subroutines


* Subroutine INITOC4
* Initializes OC4 to drive four-phase stepper motor
* Calling Register
* IX = register block address
* No return registers except that CCR affected
ORG $180
INITOC4
PSHA
PSHB
BCLR TCTL1,X $0C
LDD TCNT,X
STD TOC4,X
LDAA #$10
STAA TFLG1,X
STAA TMSK1,X
CLI
PULB
PULA
RTS

;preserve registers
;OM4:OL4=0:0
;avoid premature compare
;clear OC4F is set
;OC4I=1 to enable interrupt
;restore registers
;return
124

* Listing 11.5
* Service routine RTOC4
* Drives stepper motor to next step.
* It uses a look-up table to find the output pattern of the current step.
* Then it drives the outputs and moves the pointer to the next step.
* It also increments a step counter (STEPCNT) for use by an application program to keep
* track of number of steps driven.
* Driver Outputs:
* MT1 <--- PB0
* MT2 <--- INV PB0
* MT3 <--- PB1
* MT4 <--- INV PB1
* RUSH <-- PB2
* Global variables
* STEPLEN = time duration of step
* STEPPTR = pointer to step in sequence
* STEPCNT = step counter
STEPLEN
STEPPTR
STEPCNT

EQU $0A
EQU $0C
EQU $0D

RTOC4
LDX #REGBAS
;point to registers
LDD STEPLEN
;schedule next step
ADDD TOC4,X
STD TOC4,X
BCLR TFLG1,X $EF
;clears flag OC4F
LDY #STEPTAB
;point to sequence for this step
LDAB STEPPTR
ABY
LDAA PORTB,X
;get previous drive outputs and
ANDA #$FC
;modify by clearing last two bits
ORAA 0,Y
;then change them as per table
STAA PORTB,X
;and update drive outputs
INC STEPPTR
;stepptr ++
LDAB STEPPTR
;if stepptr == 4
CMPB #4
;(note stepper mtr has four phases)
BNE SKIP
CLR STEPPTR
;then stepptr = 0
SKIP
INC STEPCNT
;update stepper mtr count
RTI
;return
* Stepper motor sequence look-up table
* PB2 is high to supply rush current
STEPTAB
STEP1 FCB %101
STEP2 FCB %111
STEP3 FCB %110
STEP4 FCB %100
125

* Listing 11.6
* Demonstration of utility routines to drive
* stepper motor for 16 steps using EVB board.
* REMINDER, see template listing in Appendix E for
* necessary overhead, such as segment definition,
* stack setup, and interrupt vectors
* ---------------------------------------------------------ORG $0A
STEPLEN
FCB $01, 00
;period of time for each step
STEPPTR
RMB 1
;points to step sequence in STEPTAB
STEPCNT
RMB 1
;for use by application program to
*
;keep track of number of steps
* Remove above definitions from Listing 11.5
* ---------------------------------------------------------ORG $100
* Stepper motor control part
LDD
CLR
LDX
BSET
JSR
CLR

STEPLEN
STEPPTR
#REGBAS
PORTB,X $04
INITOC4
STEPCNT

* OC4 interrupt drives program here


LOOP
LDAA STEPCNT
CMPA #16
BNE LOOP
BCLR TMSK1,X $10
BCLR PORTB,X $04
BRA *

;init stepper motor step time


;define first step
;point to registers
;supply rush current
;initialize OC4 for stepper motor control
;init step counter

;for 16 steps

;then disable OC4 interrupt


;and supply hold current
;end of demo for now

126

Bibliography
1. M68HC11E Series Programming Reference Guide, Rev.1, Motorola, 2002.
2. Barry B. Brey, Microprocessors/Hardware Interfacing and Applications, Merrill, 1984
(ISBN 0-675-20158-6).
3. Barry B. Brey, Intel Microprocessors 8086/8088, 80186/80188, 80286, 80386, 80486
Pentium, Pentium Pro Processor, Pentium II, Pentium III, and Pentium IV: Architecture,
Programming, and Interfacing, 6/e, Prentice Hall, 2003 (ISBN 0-13-060714-2).
4. Fredrick M. Cady, Microcontrollers and Microcomputers: Principles of Software and
Hardware Engineering, Oxford University Press, 1997 (ISBN 0-19-511008-0).
5. Fredrick M. Cady, Software and Hardware Engineering: Motorola M68HC11, Oxford
University Press, 1997 (ISBN 0-19-511046-3).
6. Fredrick M. Cady and James M. Sibigtroth, Software and Hardware Engineering:
Motorola M68HC12, Oxford University Press, 2000 (ISBN 0-19-512469-3).
7. Robert John Dirkman, John Leonard, Laboratory Manual for Microcontroller
Technology, 1/e, Prentice Hall, 1996 (ISBN 0-13-207523-7).
8. Frederick F. Driscoll, Robert F. Coughlin, Robert S. Villanucci, Data Acquisition and
Process Control with the M68HC11 Microcontroller, 2/e, Prentice Hall, 2000 (ISBN 013-779976-4).
9. Dale Grover, John Deller, Digital Signal Processing and the Microcontroller, 1/e,
Prentice Hall, 1999 (ISBN 0-13-081348-6).
10. Richard E. Haskell, Design of Embedded Systems Using 68HC12/11 Microcontrollers,
1/e, Prentice Hall, 2000 (ISBN 0-13-083208-1).
11. Michael R. Kheir, M68HC11 Microcontroller: Applications in Control, Instrumentation
and Communication, 1/e, 1997 (ISBN 0-13-205550-3).
12. Todd D. Morton, Embedded Microcontrollers, 1/e, Prentice Hall, 2001 (ISBN 0-13907577-1).
13. Daniel J. Pack, Steven F. Barrett, 68HC12 Microcontroller, The: Theory and
Applications, 1/e, Prentice Hall, 2002 (ISBN 0-13-033776-5).
14. John C. Skroder, Using the M68HC11 Microcontroller: A Guide to Interfacing and
Programming, 1/e, Prentice Hall, 1997 (ISBN 0-13-120676-1).
15. Peter Spasov, Microcontroller Technology: The 68HC11, 4/e, Prentice Hall, 2002 (ISBN
0-13-019579-0).
16. Peter Spasov, Microcontroller Technology: The 68HC11 and 68HC12, 5/e, Prentice Hall,
2004 (ISBN 0-13-124791-3).
17. Ronald J. Tocci, Frank J. Ambrosio, Microprocessors and Microcomputers: Hardware
and Software, 6/e, Prentice Hall, 2003 (ISBN 0-13-060904-8).

127

18. William C. Wray, Joseph D. Greenfield, Ross Bannatyne, Using Microprocessors and
Microcomputers: The Motorola Family, 4/e, Prentice Hall, 1999 (ISBN 0-13-840406-2).

128

You might also like