Vous êtes sur la page 1sur 64

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

SYLLABUS
Module 0: (Review) Computing Systems (6)
From Bits and Gates to C and Beyond

Module 1: Architecture of Microprocessors (6)


General definitions of mini computers, microprocessors, micro controllers and digital signal processors.
Overview of 8085 microprocessor. Overview of 8086 microprocessor. Signals and pins of 8086 microprocessor

Module 2: Assembly language of 8086 (6)


Description of Instructions. Assembly directives. Assembly software programs with algorithms

MICROPROCESSOR & Module 3: Interfacing with 8086 (8)


Interfacing with RAMs, ROMs along with the explanation of timing diagrams. Interfacing with peripheral ICs
like 8255, 8254, 8279, 8259, 8259 etc. Interfacing with key boards, LEDs, LCDs, ADCs, and DACs etc.
MICROCONTROLLER Module 4: Coprocessor 8087 (4)
Architecture of 8087, interfacing with 8086. Data types, instructions and programming

Module 5: Architecture of Micro controllers (4)


Overview of the architecture of 8051 microcontroller. Overview of the architecture of 8096 16 bit
microcontroller

Module 6: Assembly language of 8051 (4)


Description of Instructions. Assembly directives. Assembly software programs with algorithms

Module 7: Interfacing with 8051 (5)


Interfacing with keyboards, LEDs, 7 segment LEDs, LCDs, Interfacing with ADCs. Interfacing with DACs, etc.

Module 8: High end processors (2)


Introduction to 80386 and 80486

Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 2

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Module 0: Computing Systems


From Bits and Gates to C and Beyond Chapter 1
Welcome Aboard

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 3 Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course

1
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Big Idea #1: Universal Computing Device Turing Machine


Mathematical model of a device that can perform
All computers, given enough time and memory, any computation – Alan Turing (1937)
are capable of computing exactly the same things. • ability to read/write symbols on an infinite “tape”
• state transitions, based on current state and symbol

Every computation can be performed by some


Turing machine. (Turing’s thesis)

= = a,b Tadd a+b a,b Tmul ab

PDA
Workstation Turing machine that adds Turing machine that multiplies
Supercomputer
For more info about Turing machines, see For more about Alan Turing, see
http://www.wikipedia.org/wiki/Turing_machine/ http://www.turing.org.uk/turing/

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 5 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 6

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Universal Turing Machine From Theory to Practice


A machine that can implement all Turing machines In theory, computer can compute anything
-- this is also a Turing machine! that’s possible to compute
• inputs: data, plus a description of computation (other TMs)
• given enough memory and time

Tadd, Tmul
In practice, solving problems involves
U computing under constraints.
a,b,c c(a+b)
• time
Universal Turing Machine  weather forecast, next frame of animation, ...
• cost
 cell phone, automotive engine controller, ...
U is programmable – so is a computer! • power
• instructions are part of the input data  cell phone, handheld video game, ...
• a computer can emulate a Universal Turing Machine

A computer is a universal computing device.


Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 7 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 8

2
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Big Idea #2: Transformations Between Layers How do we solve a problem using a computer?
A systematic sequence of transformations between
Problems layers of abstraction.

Problem
Algorithms
Software Design:
choose algorithms and data structures
Language
Algorithm
Instruction Set Architecture Programming:
use language to express design
Microarchitecture
Program

Circuits Compiling/Interpreting:
convert language to
Instr Set machine instructions
Devices Architecture
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 9 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 10

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Deeper and Deeper… Descriptions of Each Level


Problem Statement
Instr Set • stated using "natural language"
Architecture • may be ambiguous, imprecise
Processor Design: Algorithm
choose structures to implement ISA
• step-by-step procedure, guaranteed to finish
Microarch • definiteness, effective computability, finiteness
Logic/Circuit Design: Program
gates and low-level circuits to • express the algorithm using a computer language
implement components • high-level language, low-level language
Circuits
Instruction Set Architecture (ISA)
Process Engineering & Fabrication: • specifies the set of instructions the computer can perform
develop and manufacture • data types, addressing mode
lowest-level components
Devices

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 11 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 12

3
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Descriptions of Each Level (cont.) Course Outline


Bits and Bytes
Microarchitecture • How do we represent information using electrical signals?
• detailed organization of a processor implementation Digital Logic
• different implementations of a single ISA • How do we build circuits to process information?
Logic Circuits Processor and Instruction Set
• combine basic operations to realize microarchitecture • How do we build a processor out of logic elements?
• What operations (instructions) will we implement?
• many different ways to implement a single function
(e.g., addition) Assembly Language Programming
• How do we use processor instructions to implement algorithms?
Devices
• How do we write modular, reusable code? (subroutines)
• properties of materials, manufacturability
I/O, Traps, and Interrupts
• How does processor communicate with outside world?
C Programming
• How do we write programs in C?
• How do we implement high-level programming constructs?

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 13 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 14

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

How do we represent data in a computer?


At the lowest level, a computer is an electronic machine.
• works by controlling the flow of electrons

Easy to recognize two conditions:


Chapter 2 1. presence of a voltage – we’ll call this state “1”
2. absence of a voltage – we’ll call this state “0”
Bits, Data Types,
and Operations Could base state on value of voltage,
but control and detection circuits more complex.
• compare turning on a light switch to
measuring or regulating voltage

Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 16

4
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Computer is a binary digital system. What kinds of data do we need to represent?


Digital system: Binary (base two) system:
• finite number of symbols • has two states: 0 and 1 • Numbers – signed, unsigned, integers, floating point,
complex, rational, irrational, …
• Text – characters, strings, …
• Images – pixels, colors, shapes, …
• Sound
• Logical – true, false
• Instructions
Basic unit of information is the binary digit, or bit.
• …
Values with more than two states require multiple bits.
• A collection of two bits has four possible states:
Data type:
00, 01, 10, 11
• representation and operations within the computer
• A collection of three bits has eight possible states:
We’ll start with numbers…
000, 001, 010, 011, 100, 101, 110, 111
• A collection of n bits has 2n possible states.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 17 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 18

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Unsigned Integers Unsigned Integers (cont.)


Non-positional notation An n-bit unsigned integer represents 2n values:
• could represent a number (“5”) with a string of ones (“11111”) from 0 to 2n-1.
• problems?
22 21 20
0 0 0 0
Weighted positional notation 0 0 1 1
• like decimal numbers: “329”
0 1 0 2
• “3” is worth 300, because of its position, while “9” is only worth 9
0 1 1 3
most least 1 0 0 4
329 significant
101 significant
1 0 1 5
102 101 100 22 21 20 1 1 0 6
1 1 1 7
3x100 + 2x10 + 9x1 = 329 1x4 + 0x2 + 1x1 = 5

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 19 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 20

5
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Unsigned Binary Arithmetic Signed Integers


Base-2 addition – just like base-10! With n bits, we have 2n distinct values.
• add from right to left, propagating carry • assign about half to positive integers (1 through 2 n-1)
and about half to negative (- 2n-1 through -1)
carry • that leaves two values: one for 0, and one extra
Positive integers
10010 10010 1111 • just like unsigned – zero in most significant (MS) bit
+ 1001 + 1011 + 1 00101 = 5
11011 11101 10000 Negative integers
• sign-magnitude – set MS bit to show negative,
other bits are the same as unsigned
10111 10101 = -5
• one’s complement – flip every bit to represent negative
+ 111 11010 = -5
• in either case, MS bit indicates sign: 0=positive, 1=negative
Subtraction, multiplication, division,…

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 21 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 22

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Two’s Complement Two’s Complement Representation


Problems with sign-magnitude and 1’s complement If number is positive or zero,
• two representations of zero (+0 and –0) • normal binary representation, zeroes in upper bit(s)
• arithmetic circuits are complex
If number is negative,
 How to add two sign-magnitude numbers?
• start with positive number
– e.g., try 2 + (-3)
 How to add to one’s complement numbers? • flip every bit (i.e., take the one’s complement)
– e.g., try 4 + (-3) • then add one
Two’s complement representation developed to make
circuits easy for arithmetic.
• for each positive number (X), assign value to its negative (-X), 00101 (5) 01001 (9)
such that X + (-X) = 0 with “normal” addition, ignoring carry out 11010 (1’s comp) (1’s comp)
+ 1 + 1
00101 (5) 01001 (9)
11011 (-5) (-9)
+ 11011 (-5) + (-9)
00000 (0) 00000 (0)
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 23 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 24

6
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Two’s Complement Shortcut Two’s Complement Signed Integers


To take the two’s complement of a number: MS bit is sign bit – it has weight –2n-1.
• copy bits from right to left until (and including) the first “1” Range of an n-bit number: -2n-1 through 2n-1 – 1.
• flip remaining bits to the left • The most negative number (-2n-1) has no positive counterpart.

-23 22 21 20 -23 22 21 20
011010000 011010000 0 0 0 0 0 1 0 0 0 -8
100101111 (1’s comp) (flip) (copy) 0 0 0 1 1 1 0 0 1 -7
+ 1 0 0 1 0 2 1 0 1 0 -6
100110000 100110000 0 0 1 1 3 1 0 1 1 -5
0 1 0 0 4 1 1 0 0 -4
0 1 0 1 5 1 1 0 1 -3
0 1 1 0 6 1 1 1 0 -2
0 1 1 1 7 1 1 1 1 -1

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 25 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 26

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Converting Binary (2’s C) to Decimal More Examples


1. If leading bit is one, take two’s complement to get a
positive number. X = 00100111two
2. Add powers of 2 that have “1” in the n 2n = 25+22+21+20 = 32+4+2+1 n 2n
corresponding bit positions. 0 1 0 1
3. If original number was negative,
= 39ten
1 2 1 2
add a minus sign. 2 4 2 4
3 8 3 8
X = 11100110two
4 16 4 16
X = 01101000two 5 32 -X = 00011010 5 32
= 26+25+23 = 64+32+8 6 64 = 24+23+21 = 16+8+2 6 64
7 128 7 128
= 104ten 8 256 = 26ten 8 256
9 512 9 512
X= -26ten
10 1024 10 1024
Assuming 8-bit 2’s complement numbers.
Assuming 8-bit 2’s complement numbers.
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 27 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 28

7
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Converting Decimal to Binary (2’s C) Converting Decimal to Binary (2’s C) n 2n


First Method: Division Second Method: Subtract Powers of Two 0 1
1. Find magnitude of decimal number. (Always positive.) 1. Find magnitude of decimal number. 1 2
2. Divide by two – remainder is least significant bit. 2 4
2. Subtract largest power of two
3. Keep dividing by two until answer is zero, 3 8
less than or equal to number.
writing remainders from right to left. 4 16
3. Put a one in the corresponding bit position. 5 32
4. Append a zero as the MS bit;
if original number was negative, take two’s complement. 4. Keep subtracting until result is zero. 6 64
5. Append a zero as MS bit; 7 128
if original was negative, take two’s complement. 8 256
X = 104ten 104/2 = 52 r0 bit 0
9 512
52/2 = 26 r0 bit 1 10 1024
26/2 = 13 r0 bit 2 X = 104ten 104 - 64 = 40 bit 6
13/2 = 6 r1 bit 3 40 - 32 = 8 bit 5
6/2 = 3 r0 bit 4 8-8 = 0 bit 3
3/2 = 1 r1 bit 5
X = 01101000two
X = 01101000two 1/2 = 0 r1 bit 6

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 29 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 30

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Operations: Arithmetic and Logical Addition


Recall: As we’ve discussed, 2’s comp. addition is just
a data type includes representation and operations.
binary addition.
We now have a good representation for signed integers,
• assume all integers have the same number of bits
so let’s look at some arithmetic operations:
• ignore carry out
• Addition
• Subtraction • for now, assume that sum fits in n-bit 2’s comp. representation
• Sign Extension
We’ll also look at overflow conditions for addition.
Multiplication, division, etc., can be built from these 01101000 (104) 11110110 (-10)
basic operations. + 11110000 (-16) + (-9)
Logical operations are also useful:
• AND 01011000 (98) (-19)
• OR
• NOT
Assuming 8-bit 2’s complement numbers.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 31 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 32

8
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Subtraction Sign Extension


Negate subtrahend (2nd no.) and add. To add two numbers, we must represent them
• assume all integers have the same number of bits with the same number of bits.
• ignore carry out If we just pad with zeroes on the left:
• for now, assume that difference fits in n-bit 2’s comp. representation
4-bit 8-bit
0100 (4) 00000100 (still 4)
01101000 (104) 11110110 (-10) 1100 (-4) 00001100 (12, not -4)

- 00010000 (16) - (-9)


Instead, replicate the MS bit -- the sign bit:
01101000 (104) 11110110 (-10)
+ 11110000 (-16) + (9) 4-bit 8-bit
0100 (4) 00000100 (still 4)
01011000 (88) (-1)
1100 (-4) 11111100 (still -4)

Assuming 8-bit 2’s complement numbers.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 33 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 34

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Overflow Logical Operations


If operands are too big, then sum cannot be represented as an n-bit Operations on logical TRUE or FALSE
2’s comp number. • two states -- takes one bit to represent: TRUE=1, FALSE=0
01000 (8) 11000 (-8)
+ 01001 (9) + 10111 (-9) A B A AND B A B A OR B A NOT A
10001 (-15) 01111 (+15) 0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
We have overflow if:
1 0 0 1 0 1
• signs of both operands are the same, and
1 1 1 1 1 1
• sign of sum is different.
Another test -- easy for hardware:
• carry into MS bit does not equal carry out
View n-bit number as a collection of n logical values
• operation applied to each bit independently

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 35 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 36

9
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Examples of Logical Operations Hexadecimal Notation


AND 11000101 It is often convenient to write binary (base-2) numbers
• useful for clearing bits
AND with zero = 0
AND 00001111 as hexadecimal (base-16) numbers instead.
• fewer digits -- four bits per hex digit
AND with one = no change 00000101 • less error prone -- easy to corrupt long string of 1’s and 0’s

OR Binary Hex Decimal Binary Hex Decimal


• useful for setting bits
11000101 0000 0 0 1000 8 8
OR with zero = no change OR 00001111 0001 1 1 1001 9 9

OR with one = 1 11001111 0010


0011
2
3
2
3
1010
1011
A
B
10
11
0100 4 4 1100 C 12
NOT 0101 5 5 1101 D 13
• unary operation -- one argument
NOT 11000101 0110 6 6 1110 E 14
• flips every bit 00111010 0111 7 7 1111 F 15

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 37 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 38

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Converting from Binary to Hexadecimal Fractions: Fixed-Point


How can we represent fractions?
Every four bits is a hex digit.
• Use a “binary point” to separate positive
• start grouping from right-hand side from negative powers of two -- just like “decimal point.”
• 2’s comp addition and subtraction still work.
011101010001111010011010111  if binary points are aligned

2-1 = 0.5
3 A 8 F 4 D 7 2-2 = 0.25
2-3 = 0.125
00101000.101 (40.625)
+ 11111110.110 (-1.25)
This is not a new machine representation,
00100111.011 (39.375)
just a convenient way to write the number.
No new operations -- same as integer arithmetic.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 39 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 40

10
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Very Large and Very Small: Floating-Point Floating Point Example


Large values: 6.023 x 1023
-- requires 79 bits Single-precision IEEE floating point number:
Small values: 6.626 x 10-34 -- requires >110 bits 10111111010000000000000000000000
Use equivalent of “scientific notation”: F x 2E sign exponent fraction
Need to represent F (fraction), E (exponent), and sign.
IEEE 754 Floating-Point Standard (32-bits): • Sign is 1 – number is negative.
• Exponent field is 01111110 = 126 (decimal).
1b 8b 23b • Fraction is 0.100000000000… = 0.5 (decimal).
S Exponent Fraction
Value = -1.5 x 2(126-127) = -1.5 x 2-1 = -0.75.
N  ( 1)S  1.fraction  2exponent 127 , 1  exponent  254
N  ( 1)S  0.fraction  2126 , exponent  0

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 41 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 42

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Floating-Point Operations Text: ASCII Characters


ASCII: Maps 128 characters to 7-bit code.
Will regular 2’s complement arithmetic work for
• both printable and non-printable (ESC, DEL, …) characters
Floating Point numbers?
(Hint: In decimal, how do we compute 3.07 x 10 12 + 9.11 x 108?)
00 nul 10 dle 20 sp 30 0 40 @ 50 P 60 ` 70 p
01 soh 11 dc1 21 ! 31 1 41 A 51 Q 61 a 71 q
02 stx 12 dc2 22 " 32 2 42 B 52 R 62 b 72 r
03 etx 13 dc3 23 # 33 3 43 C 53 S 63 c 73 s
04 eot 14 dc4 24 $ 34 4 44 D 54 T 64 d 74 t
05 enq 15 nak 25 % 35 5 45 E 55 U 65 e 75 u
06 ack 16 syn 26 & 36 6 46 F 56 V 66 f 76 v
07 bel 17 etb 27 ' 37 7 47 G 57 W 67 g 77 w
08 bs 18 can 28 ( 38 8 48 H 58 X 68 h 78 x
09 ht 19 em 29 ) 39 9 49 I 59 Y 69 i 79 y
0a nl 1a sub 2a * 3a : 4a J 5a Z 6a j 7a z
0b vt 1b esc 2b + 3b ; 4b K 5b [ 6b k 7b {
0c np 1c fs 2c , 3c < 4c L 5c \ 6c l 7c |
0d cr 1d gs 2d - 3d = 4d M 5d ] 6d m 7d }
0e so 1e rs 2e . 3e > 4e N 5e ^ 6e n 7e ~
0f si 1f us 2f / 3f ? 4f O 5f _ 6f o 7f del

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 43 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 44

11
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Transistor: Building Block of Computers


Microprocessors contain millions of transistors
• Intel Pentium 4 (2000): 48 million
• IBM PowerPC 750FX (2002): 38 million
• IBM/Apple PowerPC G5 (2003): 58 million
Chapter 3
Logically, each transistor acts as a switch
Digital Logic Combined to implement logic functions
• AND, OR, NOT
Structures Combined to build higher-level structures
• Adder, multiplexer, decoder, register, …
Combined to build processor
• 8086, 80586 …

Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 46

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

n-type MOS Transistor p-type MOS Transistor


MOS = Metal Oxide Semiconductor p-type is complementary to n-type
• two types: n-type and p-type • when Gate has positive voltage,
n-type open circuit between #1 and #2
(switch open)
• when Gate has positive voltage,
short circuit between #1 and #2 • when Gate has zero voltage,
(switch closed) short circuit between #1 and #2
(switch closed)
• when Gate has zero voltage,
open circuit between #1 and #2
(switch open)
Gate = 1 Gate = 1

Gate = 0 Gate = 0
Terminal #2 must be Terminal #1 must be
connected to GND (0V). connected to +2.9V.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 47 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 48

12
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Logic Gates CMOS Circuit


Use switch behavior of MOS transistors Complementary MOS
to implement logical functions: AND, OR, NOT. Uses both n-type and p-type MOS transistors
• p-type
Digital symbols:  Attached to + voltage
• recall that we assign a range of analog voltages to each
digital (logic) symbol  Pulls output voltage UP when input is zero
• n-type
 Attached to GND
 Pulls output voltage DOWN when input is one

For all inputs, make sure that output is either connected to GND or to +,
• assignment of voltage ranges depends on but not both!
electrical properties of transistors being used
 typical values for "1": +5V, +3.3V, +2.9V
 from now on we'll use +2.9V

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 49 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 50

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Inverter (NOT Gate) NOR Gate

Truth table
A B C
0 0 1
In Out In Out
0 1 0
0 V 2.9 V 0 1
1 0 0
2.9 V 0V 1 0
Note: Serial structure on top, parallel on bottom. 1 1 0
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 51 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 52

13
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

OR Gate NAND Gate (AND-NOT)


A B C
0 0 0
0 1 1
1 0 1
1 1 1

A B C
0 0 1
Add inverter to NOR. 0 1 1
1 0 1
1 1 0
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 53 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 54

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

AND Gate Basic Logic Gates


A B C
0 0 0
0 1 0
1 0 0
1 1 1

Add inverter to NAND

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 55 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 56

14
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

DeMorgan's Law More than 2 Inputs?


Converting AND to OR (with some help from NOT) AND/OR can take any number of inputs.
Consider the following gate: • AND = 1 if all inputs are 1.
• OR = 1 if any input is 1.
• Similar for NAND/NOR.

To convert AND to OR Can implement with multiple two-input gates,


A B A B A B A B (or vice versa), or with single CMOS circuit.
0 0 1 1 1 0 invert inputs and output.
0 1 1 0 0 1
1 0 0 1 0 1
1 1 0 0 0 1

Same as A+B!
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 57 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 58

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Summary Building Functions from Logic Gates


MOS transistors are used as switches to implement Combinational Logic Circuit
logic functions. • output depends only on the current inputs
• n-type: connect to GND, turn on (with 1) to pull down to 0 • stateless
• p-type: connect to +2.9V, turn on (with 0) to pull up to 1
Sequential Logic Circuit
• output depends on the sequence of inputs (past and present)
Basic gates: NOT, NOR, NAND • stores information (state) from past inputs
• Logic functions are usually expressed with AND, OR, and NOT

We'll first look at some useful combinational circuits,


DeMorgan's Law then show how to use sequential circuits to store information.
• Convert AND to OR (and vice versa)
by inverting inputs and output

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 59 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 60

15
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Decoder Multiplexer (MUX)


n inputs, 2n outputs n-bit selector and 2n inputs, one output
• exactly one output is 1 for each possible input pattern • output equals one of the inputs, depending on selector

2-bit
decoder
4-to-1 MUX

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 61 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 62

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Full Adder Four-bit Adder


Add two bits and carry-in,
produce one-bit sum and carry-out.

A B Cin S Cout
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 63 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 64

16
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Logical Completeness Combinational vs. Sequential


Can implement ANY truth table with AND, OR, NOT. Combinational Circuit
• always gives the same output for a given set of inputs
A B C D
 ex: adder always generates sum and carry,
0 0 0 0 regardless of previous inputs
0 0 1 0 1. AND combinations Sequential Circuit
that yield a "1" in the • stores information
0 1 0 1 truth table.
• output depends on stored information (state) plus input
0 1 1 0  so a given input might produce different outputs,
1 0 0 0 depending on the stored information
• example: ticket counter
1 0 1 1 2. OR the results  advances when you push the button
of the AND gates.  output depends on previous state
1 1 0 0
• useful for building “memory” elements and “state machines”
1 1 1 0

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 65 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 66

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

R-S Latch: Simple Storage Element Clearing the R-S latch


R is used to “reset” or “clear” the element – set it to zero. Suppose we start with output = 1, then change R to zero.
S is used to “set” the element – set it to one.
1
0 1
1 1 1
0 1 1 0
1
1 0
0
Output changes to zero.
0 1 1
1 0 0
1
1 1
1 0
If both R and S are one, out could be either zero or one. 1
• “quiescent” state -- holds its previous value
• note: if a is 1, b is 0, and vice versa 1
0 0
0
Then set R=1 to “store” value in quiescent state.
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 67 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 68

17
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Setting the R-S Latch R-S Latch Summary


Suppose we start with output = 0, then change S to zero. R=S=1
• hold current value in latch
1
S = 0, R=1
1 0 • set value to 1
R = 0, S = 1
• set value to 0
0 1
Output changes to one.
1
R=S=0
0
• both outputs equal one
0 1 • final state determined by electrical properties of gates
• Don’t do it!

1 0
1
Then set S=1 to “store” value in quiescent state.
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 69 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 70

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Gated D-Latch Register


Two inputs: D (data) and WE (write enable) A register stores a multi-bit value.
• when WE = 1, latch is set to value of D • We use a collection of D-latches, all controlled by a common WE.
 S = NOT(D), R = D • When WE=1, n-bit value D is written to register.
• when WE = 0, latch holds previous value
S = R = 1

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 71 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 72

18
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Representing Multi-bit Values Memory


Number bits from right (0) to left (n-1) Now that we know how to store bits,
• just a convention -- could be left to right, but must be consistent we can build a memory – a logical k × m array of
Use brackets to denote range: stored bits.
D[l:r] denotes bit l to bit r, from left to right
15 0

A = 0101001101010101
Address Space:
number of locations k = 2n
(usually a power of 2) locations •

A[14:9] = 101001 A[2:0] = 101 •

May also see A<14:9>,


especially in hardware block diagrams. Addressability:
number of bits per location
(e.g., byte-addressable) m bits

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 73 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 74

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

22 x 3 Memory
word select word WE
input bits
More Memory Details
address
This is a not the way actual memory is implemented.
write • fewer transistors, much more dense,
enable relies on electrical properties
But the logical structure is very similar.
• address decoder
• word select line
• word write enable
Two basic kinds of RAM (Random Access Memory)
Static RAM (SRAM)
• fast, maintains data as long as power applied
Dynamic RAM (DRAM)
• slower but denser, bit storage decays – must be periodically refreshed

address
Also, non-volatile memories: ROM, PROM, flash, …
decoder
output bits
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 75 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 76

19
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

State Machine Combinational vs. Sequential


Another type of sequential circuit Two types of “combination” locks
• Combines combinational logic with storage
• “Remembers” state, and changes output (and state)
based on inputs and current state
30
25 5
State Machine 4 1 8 4 20 10
15
Inputs Combinational Outputs
Logic Circuit Combinational Sequential
Success depends only on Success depends on
the values, not the order in the sequence of values
Storage
which they are set. (e.g, R-13, L-22, R-3).
Elements

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 77 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 78

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

State State of Sequential Lock


The state of a system is a snapshot of
all the relevant elements of the system Our lock example has four different states, labelled A-D:
at the moment the snapshot is taken. A: The lock is not open,
and no relevant operations have been performed.
Examples: B: The lock is not open,
• The state of a basketball game can be represented by and the user has completed the R-13 operation.
the scoreboard.
C: The lock is not open,
 Number of points, time remaining, possession, etc. and the user has completed R-13, followed by L-22.
• The state of a tic-tac-toe game can be represented by D: The lock is open.
the placement of X’s and O’s on the board.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 79 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 80

20
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

State Diagram Finite State Machine


Shows states and A description of a system with the following components:
actions that cause a transition between states.
1. A finite number of states
2. A finite number of external inputs
3. A finite number of external outputs
4. An explicit specification of all state transitions
5. An explicit specification of what determines each
external output value

Often described by a state diagram.


• Inputs trigger state transitions.
• Outputs are associated with each state (or with each transition).

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 81 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 82

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

The Clock Implementing a Finite State Machine


Frequently, a clock circuit triggers transition from Combinational logic
one state to the next. • Determine outputs and next state.
“1” Storage elements
• Maintain state representation.
“0”
One time
Cycle State Machine

At the beginning of each clock cycle, Inputs Combinational Outputs


state machine makes a transition, Logic Circuit
based on the current state and the external inputs.
• Not always required. In lock example, the input itself triggers a transition. Storage
Clock Elements

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 83 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 84

21
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Storage: Master-Slave Flipflop Storage


A pair of gated D-latches, Each master-slave flipflop stores one state bit.
to isolate next state from current state.
The number of storage elements (flipflops) needed
is determined by the number of states
(and the representation of each state).

Examples:
• Sequential lock
 Four states – two bits
• Basketball scoreboard
 7 bits for each score, 5 bits for minutes, 6 bits for seconds,
During 1st phase (clock=1), During 2nd phase (clock=0), 1 bit for possession arrow, 1 bit for half, …
previously-computed state next state, computed by
becomes current state and is logic circuit, is stored in
sent to the logic circuit. Latch A.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 85 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 86

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Complete Example Traffic Sign State Diagram


A blinking traffic sign
• No lights on
• 1 & 2 on
• 1, 2, 3, & 4 on 3
4
• 1, 2, 3, 4, & 5 on 1
5
• (repeat as long as switch
2
Switch on
is turned on)
Switch off

DANGER
MOVE
RIGHT State bit S1
State bit S0
Outputs

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 87 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 88

22
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Traffic Sign Truth Tables Traffic Sign Logic


Outputs Next State: S1’S0’
(depend only on state: S1S0) (depend on state and input)
Lights 1 and 2 Switch

Lights 3 and 4 In S1 S0 S1’ S0’


Light 5
0 X X 0 0
S1 S0 Z Y X 1 0 0 0 1
0 0 0 0 0 1 0 1 1 0
0 1 1 0 0 1 1 0 1 1
1 0 1 1 0 1 1 1 0 0 Master-slave
flipflop
1 1 1 1 1
Whenever In=0, next state is 00.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 89 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 90

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

From Logic to Data Path

The data path of a computer is all the logic used to


process information.

Combinational Logic
• Decoders -- convert instructions into control signals
Chapter 4
• Multiplexers -- select inputs and outputs
• ALU (Arithmetic and Logic Unit) -- operations on data
The Von Neumann
Model
Sequential Logic
• State machine -- coordinate control signals and data movement
• Registers and latches -- storage elements

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 91 Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course

23
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

The Stored Program Computer Von Neumann Model


1943: ENIAC
• Presper Eckert and John Mauchly -- first general electronic computer.
MEMORY
(or was it John V. Atanasoff in 1939?)
MAR MDR
• Hard-wired program -- settings of dials and switches.
1944: Beginnings of EDVAC
INPUT OUTPUT
• among other improvements, includes program stored in memory
Keyboard Monitor
1945: John von Neumann Mouse PROCESSING UNIT Printer
• wrote a report on the stored program concept, Scanner LED
known as the First Draft of a Report on EDVAC Disk ALU TEMP Disk
The basic structure proposed in the draft became known
as the “von Neumann machine” (or model).
• a memory, containing instructions and data
• a processing unit, for performing arithmetic and logical operations
• a control unit, for interpreting instructions
CONTROL UNIT
PC IR
For more history, see http://www.maxmon.com/history.htm

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 93 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 94

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Memory Interface to Memory


2k x m array of stored bits How does processing unit get data to/from memory?
Address MAR: Memory Address Register
0000
• unique (k-bit) identifier of location 0001 MDR: Memory Data Register MEMORY
Contents 0010
0011 00101101
• m-bit value stored in location 0100 To LOAD a location (A): MAR MDR
0101
0110 1. Write the address (A) into the MAR.
Basic Operations: • 2. Send a “read” signal to the memory.


LOAD 3. Read the data from MDR.
1101 10100010
• read a value from a memory location 1110 To STORE a value (X) to a location (A):
1111
STORE 1. Write the data (X) to the MDR.
• write a value to a memory location 2. Write the address (A) into the MAR.
3. Send a “write” signal to the memory.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 95 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 96

24
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Processing Unit Input and Output


Devices for getting data into and out of computer memory
Functional Units
• ALU = Arithmetic and Logic Unit PROCESSING UNIT Each device has its own interface,
• could have many functional units. usually a set of registers like the
some of them special-purpose
ALU TEMP memory’s MAR and MDR
(multiply, square root, …)
• keyboard: data register (KBDR) and status register (KBSR)
Registers • monitor: data register (DDR) and status register (DSR)
• Small, temporary storage
• Operands and results of functional units Some devices provide both input and output
Word Size • disk, network INPUT OUTPUT
• number of bits normally processed by ALU in one instruction Program that controls access to a device is Keyboard Monitor
Mouse Printer
• also width of registers usually called a driver. Scanner LED
Disk Disk

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 97 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 98

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Control Unit Instruction Processing


Orchestrates execution of the program

Fetch instruction from memory


CONTROL UNIT
PC IR
Decode instruction

Instruction Register (IR) contains the current instruction. Evaluate address


Program Counter (PC) contains the address
of the next instruction to be executed.
Control unit:
Fetch operands from memory
• reads an instruction from memory
 the instruction’s address is in the PC Execute operation
• interprets the instruction, generating signals
that tell the other components what to do
 an instruction may take many machine cycles to complete Store result

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 99 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 100

25
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Instruction Instruction Processing: FETCH


The instruction is the fundamental unit of work. Load next instruction (at address stored in PC)
Specifies two things: from memory F
• opcode: operation to be performed into Instruction Register (IR).
• operands: data/locations to be used for operation • Copy contents of PC into MAR.
• Send “read” signal to memory. D
An instruction is encoded as a sequence of bits. • Copy contents of MDR into IR.
(Just like data!)
EA
• Often, but not always, instructions have a fixed length, Then increment PC, so that it points to
such as 16 or 32 bits.
the next instruction in sequence.
• Control unit interprets instruction:
• PC becomes PC+1. OP
generates sequence of control signals to carry out operation.
• Operation is either executed completely, or not at all.
EX
A computer’s instructions and their formats is known as its
Instruction Set Architecture (ISA).
S

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 101 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 102

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Instruction Processing: DECODE Instruction Processing: EVALUATE ADDRESS


First identify the opcode. For instructions that require memory access,
• In LC-3, this is always the first four bits of instruction. F compute address used for access. F
• A 4-to-16 decoder asserts a control line corresponding
to the desired opcode. Examples:
D D
• add offset to base register (as in LDR)
Depending on opcode, identify other operands • add offset to PC
from the remaining bits. EA • add offset to zero EA
• Example:
 for LDR, last six bits is offset
 for ADD, last three bits is source operand #2 OP OP

EX EX

S S

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 103 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 104

26
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Instruction Processing: FETCH OPERANDS Instruction Processing: EXECUTE


Obtain source operands needed to Perform the operation,
perform operation. F using the source operands. F

Examples: Examples:
D D
• load data from memory (LDR) • send operands to ALU and assert ADD signal
• read data from register file (ADD) • do nothing (e.g., for loads and stores)
EA EA

OP OP

EX EX

S S

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 105 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 106

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Instruction Processing: STORE RESULT Changing the Sequence of Instructions


Write results to destination. In the FETCH phase,
(register or memory) F we increment the Program Counter by 1.

Examples: What if we don’t want to always execute the instruction


D that follows this one?
• result of ADD is placed in destination register
• examples: loop, if-then, function call
• result of memory load is placed in destination register
• for store instruction, data is stored to memory EA
 write address to MAR, data to MDR
Need special instructions that change the contents
of the PC.
 assert WRITE signal to memory
OP These are called control instructions.
• jumps are unconditional -- they always change the PC
• branches are conditional -- they change the PC only if
EX some condition is true (e.g., the result of an ADD is zero)

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 107 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 108

27
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Instruction Processing Summary Control Unit State Diagram


Instructions look just like data -- it’s all interpretation. The control unit is a state machine. Here is part of a
simplified state diagram:

Three basic kinds of instructions:


• computational instructions (ADD, AND, …)
• data movement instructions (LD, ST, …)
• control instructions (JMP, BRnz, …)

Six basic phases of instruction processing:


F  D  EA  OP  EX  S
• not all phases are needed by every instruction
• phases may take variable number of machine cycles

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 109 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 110

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Stopping the Clock


Control unit will repeat instruction processing sequence
as long as clock is running.
• If not processing instructions from your application,
then it is processing instructions from the Operating System (OS).
• The OS is a special program that manages processor
and other resources.
To stop the computer: Chapter 5
• AND the clock generator signal with ZERO
• When control unit stops seeing the CLOCK signal, it stops processing.
Programming

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 111 Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course

28
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Solving Problems using a Computer Stepwise Refinement


Methodologies for creating computer programs Also known as systematic decomposition.
that perform a desired function.
Start with problem statement:
Problem Solving “We wish to count the number of occurrences of a character
• How do we figure out what to tell the computer to do? in a file. The character in question is to be input from
• Convert problem statement into algorithm, the keyboard; the result is to be displayed on the monitor.”
using stepwise refinement.
Debugging Decompose task into a few simpler subtasks.
• How do we figure out why it didn’t work?
• Examining registers and memory, setting breakpoints, etc. Decompose each subtask into smaller subtasks,
and these into even smaller subtasks, etc....
until you get to the machine instruction level.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 113 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 114

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Problem Statement Three Basic Constructs


Because problem statements are written in English, There are three basic ways to decompose a task:
they are sometimes ambiguous and/or incomplete.
• Where is “file” located? How big is it, or how do I know
when I’ve reached the end? Task
• How should final count be printed? A decimal number?
• If the character is a letter, should I count both
upper-case and lower-case occurrences?

How do you resolve these issues?


True Test False
• Ask the person who wants the problem solved, or condition Test False
Subtask 1 condition
• Make a decision and document it.
True
Subtask 1 Subtask 2
Subtask 2 Subtask

Sequential Conditional Iterative


Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 115 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 116

29
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Sequential Conditional
Do Subtask 1 to completion, If condition is true, do Subtask 1;
then do Subtask 2 to completion, etc. else, do Subtask 2.

Get character
input from
keyboard True file char False
= input?

Count and print the Examine file and Test character.


occurrences of a count the number If match, increment Count = Count + 1
character in a file of characters that counter.
match

Print number
to the screen

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 117 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 118

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Iterative Problem Solving Skills


Do Subtask over and over, Learn to convert problem statement
as long as the test condition is true. into step-by-step description of subtasks.

• Like a puzzle, or a “word problem” from grammar school math.


 What is the starting state of the system?
False  What is the desired ending state?
more chars
to check?  How do we move from one state to another?
Check each element of
the file and count the
True • Recognize English words that correlate to three basic constructs:
characters that match.
 “do A then do B”  sequential
Check next char and  “if G, then do H”  conditional
count if matches.  “for each X, do Y”  iterative
 “do Z until W”  iterative

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 119 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 120

30
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Code for Conditional Code for Iteration


PC offset to
Exact bits depend address C
on condition PC offset to
Instruction Exact bits depend
being tested address C
A on condition Instruction
Generate
Condition being tested A
True Test False Generate
Test False
Condition B 0000 ? C Condition
Condition
0000 ? C
Subtask 1 True B
Subtask 1 Subtask 2
Subtask
0000 111 D
Subtask
C 0000 111 A
Subtask 2 C
Next
Unconditional branch
Next Subtask
to Next Subtask D Next
Subtask Next PC offset to Unconditional branch
Subtask address D Subtask to retest condition
PC offset to
address A

Assuming all addresses are close enough that PC-relative branch can be used. Assuming all addresses are on the same page.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 121 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 122

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example: Counting Characters Refining B


START

A Initialize: Put initial values


into all locations that w ill be
needed to carry out this B
START task.

- Input a character.
- Set up a pointer to the first
Yes
Done?
Input a character. Then location of the file that will
scan a file, counting be scanned. B
occurrences of that - Get the first character from Scan the file, location by No
location, incrementing the B1
character. Finally, display the file.
- Zero the register that holds counter if the character
on the monitor the number Test character. If a match,
the count. matches.
of occurrences of the increment counter. Get next
character (up to 9). character.
B
Scan the file, location by
location, incrementing the
counter if the character
STOP m atches.

C Display the count on the


Initial refinement: Big task into m onitor. Refining B into iterative construct.
three sequential subtasks.
STOP

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 123 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 124

31
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Refining B1 Refining B2 and B3


Yes
Done?

No
B2

B Yes
Done?
Yes R1 = R0?
Done? Yes No
Yes No
Done?
B1 No
B1
R2 = R2 + 1
No B2 Test character. If matches,
B1
increment counter. B2 Test character. If matches,
Test character. If a match,
increment counter.
increment counter. Get next
character. B3 Get next character. B3
B3 Get next character.
R3 = R3 + 1

R1 = M[R3]

Conditional (B2) and sequential (B3).


Refining B1 into sequential subtasks. Use of LC-2 registers and instructions.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 125 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 126

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Debugging Debugging Operations


You’ve written your program and it doesn’t work. Any debugging environment should provide means to:
Now what? 1. Display values in memory and registers.
2. Deposit values in memory and registers.
What do you do when you’re lost in a city? 3. Execute instruction sequence in a program.
Drive around randomly and hope you find it? 4. Stop execution when desired.
Return to a known point and look at a map? Different programming levels offer different tools.
• High-level languages (C, Java, ...)
usually have source-code debugging tools.
In debugging, the equivalent to looking at a map
• For debugging at the machine instruction level:
is tracing your program.
 simulators
• Examine the sequence of instructions being executed.
 operating system “monitor” tools
• Keep track of results being produced.
 in-circuit emulators (ICE)
• Compare result from each instruction to the expected result.
– plug-in hardware replacements that give
instruction-level control

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 127 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 128

32
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Types of Errors Tracing the Program


Syntax Errors
Execute the program one piece at a time,
• You made a typing error that resulted in an illegal operation. examining register and memory to see results at each step.
• Not usually an issue with machine language, Single-Stepping
because almost any bit pattern corresponds to • Execute one instruction at a time.
some legal instruction. • Tedious, but useful to help you verify each step of your program.
• In high-level languages, these are often caught during the Breakpoints
translation from language to machine code.
• Tell the simulator to stop executing when it reaches
Logic Errors a specific instruction.
• Your program is legal, but wrong, so • Check overall results at specific points in the program.
the results don’t match the problem statement.  Lets you quickly execute sequences to get a
high-level overview of the execution behavior.
• Trace the program to see what’s really happening and
determine how to get the proper behavior.  Quickly execute sequences that your believe are correct.
Watchpoints
Data Errors
• Tell the simulator to stop when a register or memory location changes
• Input data is different than what you expected. or when it equals a specific value.
• Test the program with a wide variety of inputs. • Useful when you don’t know where or when a value is changed.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 129 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 130

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example 1: Multiply Debugging the Multiply Program


This program is supposed to multiply the two unsigned Single-stepping
integers in R4 and R5. PC R2 R4 R5
Breakpoint at branch (x3203)
x3200 -- 10 3
PC and registers
at the beginning x3201 0 10 3
clear R2 of each instruction x3202 10 10 3 PC R2 R4 R5
x3200 0101010010100000
x3203 10 10 2 x3203 10 10 2
x3201 0001010010000100
x3201 10 10 2 x3203 20 10 1
add R4 to R2 x3202 0001101101111111
x3202 20 10 2 x3203 30 10 0
x3203 0000011111111101
x3203 20 10 1 x3203 40 10 -1
decrement R5 x3204 1111000000100101
x3201 20 10 1 40 10 -1
x3202 30 10 1
x3203 30 10 0 Should stop looping here!
No
R5 = 0? x3201 30 10 0
Set R4 = 10, R5 =3. x3202 40 10 0
Yes Run program. Executing loop one time too many.
x3203 40 10 -1
Result: R2 = 40, not 30. Branch at x3203 should be based
x3204 40 10 -1
HALT on Z bit only, not Z and P.
40 10 -1
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 131 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 132

33
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example 2: Summing an Array of Numbers Debugging the Summing Program


This program is supposed to sum the numbers stored in 10 locations beginning with Running the the data below yields R1 = x0024,
x3100, leaving the result in R1. but the sum should be x8135. What happened?

R1 = 0 Address Contents
x3000 0101001001100000
R4 = 10
x3001 0101100100100000 x3100 x3107 Start single-stepping program...
R2 = x3100
x3002 0001100100101010 x3101 x2819 PC R1 R2 R4
R1 = R1 + M[R2] x3003 0010010011111100 x3102 x0110 x3000 -- -- --
R2 = R2 + 1 x3004 0110011010000000 x3001 0 -- --
x3103 x0310
x3005 0001010010100001 x3002 0 -- 0
R4 = R4 - 1 x3006 0001001001000011 x3104 x0110
x3003 0 -- 10
x3007 0001100100111111 x3105 x1110 x3004 0 x3107 10
x3008 0000001111111011 x3106 x11B1
No x3009 1111000000100101
R4 = 0? x3107 x0019 Should be x3100!
x3108 x0007 Loading contents of M[x3100], not address.
Yes
x3109 x0004 Change opcode of x3003
from 0010 (LD) to 1110 (LEA).
HALT
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 133 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 134

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example 3: Looking for a 5 Debugging the Fives Program


This program is supposed to set x3000 0101000000100000 Running the program with a 5 in location x3108
R0=1 if there’s a 5 in one ten x3001 0001000000100001 results in R0 = 0, not R0 = 1. What happened?
memory locations, starting at x3100. x3002 0101001001100000
Else, it should set R0 to 0. x3003 0001001001111011 Address Contents Perhaps we didn’t look at all the data?
x3004 0101011011100000 x3100 9 Put a breakpoint at x300D to see
x3005 0001011011101010 how many times we branch back .
R0 = 1, R1 = -5, R3 = 10
x3006 0010100000001001 x3101 7
R4 = x3100, R2 = M[R4]
x3007 0110010100000000 x3102 32 PC R0 R2 R3 R4
x3008 0001010010000001 x300D 1 7 9 x3101
x3009 0000010000000101 x3103 0
Yes x300D 1 32 8 x3102
R2 = 5? x300A 0001100100100001 x3104 -8
x300D 1 0 7 x3103
x300B 0001011011111111
No
x3105 19 0 0 7 x3103 Didn’t branch
x300C 0110010100000000
back, even
R4 = R4 + 1 x300D 0000001111111010 x3106 6
though R3 > 0?
No
R3 = 0? R3 = R3-1 x300E 0101000000100000 x3107 13 Branch uses condition code set by
R2 = M[R4] x300F 1111000000100101
x3108 5 loading R2 with M[R4], not by decrementing R3.
Yes x3010 0011000100000000
Swap x300B and x300C, or remove x300C and
x3109 61 branch back to x3007.
R0 = 0 HALT
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 135 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 136

34
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example 4: Finding First 1 in a Word Debugging the First-One Program


This program is supposed to return (in R1) the bit position of the first 1 in Program works most of the time, but if data is zero,
a word. The address of the word is in location x3009 (just past the end of it never seems to HALT.
the program). If there are no ones, R1 should be set to –1.
R1 = 15
Breakpoint at backwards branch (x3007)
R2 = data x3000 0101001001100000
PC R1 PC R1
x3001 0001001001101111
x3007 14 x3007 4
Yes x3002 1010010000000110
R2[15] = 1? x3007 13 x3007 3 If no ones, then branch to HALT
x3003 0000100000000100 x3007 12 x3007 2 never occurs!
No
x3004 0001001001111111 x3007 11 x3007 1 This is called an “infinite loop.”
decrement R1
x3005 0001010010000010 x3007 10 x3007 0 Must change algorithm to either
shift R2 left one bit
x3006 0000100000000001 x3007 9 x3007 -1 (a) check for special case (R2=0), or
(b) exit loop if R1 < 0.
x3007 0000111111111100 x3007 8 x3007 -2
R2[15] = 1?
No x3007 7 x3007 -3
x3008 1111000000100101
x3007 6 x3007 -4
Yes x3009 0011000100000000
x3007 5 x3007 -5
HALT
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 137 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 138

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Debugging: Lessons Learned


Trace program to see what’s going on.
• Breakpoints, single-stepping

When tracing, make sure to notice what’s


really happening, not what you think should happen.
• In summing program, it would be easy to not notice
that address x3107 was loaded instead of x3100.
Chapter 6
Assembly Language
Test your program using a variety of input data.
• In Examples 3 and 4, the program works for many data sets.
• Be sure to test extreme cases (all ones, no ones, ...).

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 139 Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course

35
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Human-Readable Machine Language An Assembly Language Program


Computers like ones and zeros… ;
; Program to multiply a number by the constant 6
0001110010000110 ;
.ORIG x3050
Humans like symbols… LD R1, SIX
LD R2, NUMBER
ADD R6,R2,R6 ; increment index reg. AND R3, R3, #0 ; Clear R3. It will
; contain the product.
; The inner loop
Assembler is a program that turns symbols into ;
machine instructions. AGAIN ADD R3, R3, R2
ADD R1, R1, #-1 ; R1 keeps track of
• ISA-specific: BRp AGAIN ; the iteration.
close correspondence between symbols and instruction set ;
 mnemonics for opcodes HALT
;
 labels for memory locations NUMBER .BLKW 1
• additional operations for allocating storage and initializing data SIX .FILL x0006
;
.END

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 141 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 142

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Opcodes and Operands Labels and Comments


Opcodes Label
• reserved symbols that correspond to LC-3 instructions • placed at the beginning of the line
• listed in Appendix A • assigns a symbolic name to the address corresponding to line
 ex: ADD, AND, LD, LDR, …  ex:
Operands LOOP ADD R1,R1,#-1
• registers -- specified by Rn, where n is the register number BRp LOOP
• numbers -- indicated by # (decimal) or x (hex) Comment
• label -- symbolic name of memory location • anything after a semicolon is a comment
• separated by comma • ignored by assembler
• number, order, and type correspond to instruction format
• used by humans to document/understand programs
 ex:
ADD R1,R1,R3 • tips for useful comments:
ADD R1,R1,#3  avoid restating the obvious, as “decrement R1”
LD R6,NUMBER  provide additional insight, as in “accumulate product in R6”
BRz LOOP
 use comments to separate pieces of program

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 143 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 144

36
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Assembler Directives Trap Codes


Pseudo-operations Assembler provides “pseudo-instructions” for
• do not refer to operations executed by program each trap code, so you don’t have to remember them.
• used by assembler
• look like instruction, but “opcode” starts with dot Code Equivalent Description
HALT TRAP x25 Halt execution and print message to console.
Opcode Operand Meaning IN TRAP x23 Print prompt on console,
.ORIG address starting address of program read (and echo) one character from keybd.
Character stored in R0[7:0].
.END end of program
OUT TRAP x21 Write one character (in R0[7:0]) to console.
.BLKW n allocate n words of storage
GETC TRAP x20 Read one character from keyboard.
.FILL n allocate one word, initialize with value n Character stored in R0[7:0].
.STRINGZ n-character allocate n+1 locations, PUTS TRAP x22 Write null-terminated string to console.
string initialize w/characters and null terminator Address of string is in R0.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 145 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 146

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Style Guidelines Sample Program


Use the following style guidelines to improve Count the occurrences of a character in a file.
the readability and understandability of your programs: Remember this?
1. Provide a program header, with author’s name, date, etc.,
and purpose of program. Count = 0
Convert count to
(R2 = 0) Done? YES
2. Start labels, opcode, operands, and comments in same column (R1 ?= EOT)
ASCII character
(R0 = x30, R0 = R2 + R0)
for each line. (Unless entire line is a comment.)
Ptr = 1st file character NO
3. Use comments to explain what each register does. (R3 = M[x3012])
Print count
4. Give explanatory comment for most instructions. YES Match? NO (TRAP x21)
(R1 ?= R0)
5. Use meaningful symbolic names. Input char
from keybd
• Mixed upper and lower case for readability. (TRAP x23)

HALT
• ASCIItoBinary, InputRoutine, SaveR1 (TRAP x25)
Incr Count
6. Provide comments between program sections. Load char from file (R2 = R2 + 1)
(R1 = M[R3])
7. Each line must fit on the page -- no wraparound or truncations.
• Long statements split in aesthetically pleasing manner. Load next char from file
(R3 = R3 + 1, R1 = M[R3])

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 147 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 148

37
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Char Count in Assembly Language (1 of 3) Char Count in Assembly Language (2 of 3)


; ;
; Program to count occurrences of a character in a file. ; Test character for match. If a match, increment count.
; Character to be input from the keyboard. ;
; Result to be displayed on the monitor. NOT R1, R1
; Program only works if no more than 9 occurrences are found. ADD R1, R1, R0 ; If match, R1 = xFFFF
; NOT R1, R1 ; If match, R1 = x0000
; BRnp GETCHAR ; If no match, do not increment
; Initialization ADD R2, R2, #1
; ;
.ORIG x3000 ; Get next character from file.
AND R2, R2, #0 ; R2 is counter, initially 0 ;
LD R3, PTR ; R3 is pointer to characters GETCHAR ADD R3, R3, #1 ; Point to next character.
GETC ; R0 gets character input LDR R1, R3, #0 ; R1 gets next char to test
LDR R1, R3, #0 ; R1 gets first character BRnzp TEST
; ;
; Test character for end of file ; Output the count.
; ;
TEST ADD R4, R1, #-4 ; Test for EOT (ASCII x04) OUTPUT LD R0, ASCII ; Load the ASCII template
BRz OUTPUT ; If done, prepare the output ADD R0, R0, R2 ; Covert binary count to ASCII
OUT ; ASCII code in R0 is displayed.
HALT ; Halt machine

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 149 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 150

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Char Count in Assembly Language (3 of 3) Assembly Process


; Convert assembly language file (.asm)
; Storage for pointer and ASCII template
; into an executable file (.obj) for the LC-3 simulator.
ASCII .FILL x0030
PTR .FILL x4000
.END

First Pass:
• scan program file
• find all labels and calculate the corresponding addresses;
this is called the symbol table
Second Pass:
• convert instructions to machine language,
using information from symbol table

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 151 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 152

38
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

First Pass: Constructing the Symbol Table Second Pass: Generating Machine Language
1. Find the .ORIG statement, For each executable assembly language statement,
which tells us the address of the first instruction. generate the corresponding machine language instruction.
• Initialize location counter (LC), which keeps track of the • If operand is a label,
look up the address from the symbol table.
current instruction.

2. For each non-empty line in the program: Potential problems:


a) If line contains a label, add label and LC to symbol table. • Improper number or type of arguments
b) Increment LC.  ex: NOT R1,#7
ADD R1,R2
– NOTE: If statement is .BLKW or .STRINGZ,
ADD R3,R3,NUMBER
increment LC by the number of words allocated.
• Immediate argument too large
3. Stop when .END statement is reached.  ex: ADD R1,R2,#1023
• Address (associated with label) more than 256 from instruction
 can’t use PC-relative addressing mode
NOTE: A line that contains only a comment is considered an empty line.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 153 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 154

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Multiple Object Files Linking and Loading


An object file is not necessarily a complete program. Loading is the process of copying an executable image
• system-provided library routines into memory.
• code blocks written by multiple developers • more sophisticated loaders are able to relocate images
to fit into available memory
• must readjust branch targets, load/store addresses
For LC-3 simulator,
can load multiple object files into memory,
then start executing at a desired address. Linking is the process of resolving symbols between
• system routines, such as keyboard input, are loaded automatically independent object files.
 loaded into “system memory,” below x3000 • suppose we define a symbol in one module,
 user code should be loaded between x3000 and xFDFF and want to use it in another
• some notation, such as .EXTERNAL, is used to tell assembler that a
• each object file includes a starting address
symbol is defined in another module
• be careful not to load overlapping object files
• linker will search symbol tables of other modules to resolve symbols
and complete code generation before loading

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 155 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 156

39
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

I/O: Connecting to Outside World


So far, we’ve learned how to:
• compute with values in registers
• load data from memory to registers
• store data from registers to memory

Chapter 7 But where does data in memory come from?

I/O And how does data get out of the system so that
humans can use it?

Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 158

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

I/O: Connecting to the Outside World I/O Controller


Types of I/O devices characterized by: Control/Status Registers
• behavior: input, output, storage • CPU tells device what to do -- write to control register
 input: keyboard, motion detector, network interface • CPU checks whether task is done -- read status register
 output: monitor, printer, network interface Data Registers
 storage: disk, CD-ROM • CPU transfers data to/from device
• data rate: how fast can data be transferred? Graphics Controller
 keyboard: 100 bytes/sec Control/Status
 disk: 30 MB/s CPU Electronics display
 network: 1 Mb/s - 1 Gb/s Output Data

Device electronics
• performs actual operation
 pixels to screen, bits to/from disk, characters from keyboard

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 159 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 160

40
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Programming Interface Memory-Mapped vs. I/O Instructions


How are device registers identified? Instructions
• Memory-mapped vs. special instructions • designate opcode(s) for I/O
• register and operation encoded in instruction
How is timing of transfer managed?
• Asynchronous vs. synchronous

Who controls transfer? Memory-mapped


• CPU (polling) vs. device (interrupts) • assign a memory address
to each device register
• use data movement
instructions (LD/ST)
for control and data transfer

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 161 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 162

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Transfer Timing Transfer Control


I/O events generally happen much slower Who determines when the next data transfer occurs?
than CPU cycles.
Polling
Synchronous • CPU keeps checking status register until
• data supplied at a fixed, predictable rate new data arrives OR device ready for next data
• CPU reads/writes every X cycles • “Are we there yet? Are we there yet? Are we there yet?”

Asynchronous Interrupts
• data rate less predictable • Device sends a special signal to CPU when
• CPU must synchronize with device, new data arrives OR device ready for next data
so that it doesn’t miss data or write too quickly • CPU can be performing other tasks instead of polling device.
• “Wake me when we get there.”

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 163 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 164

41
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Input from Keyboard Basic Input Routine


When a character is typed:
• its ASCII code is placed in bits [7:0] of KBDR
(bits [15:8] are always zero) POLL LDI R0, KBSRPtr
• the “ready bit” (KBSR[15]) is set to one BRzp POLL
• keyboard is disabled -- any typed characters will be ignored new LDI R0, KBDRPtr
NO char?
15 8 7 0
keyboard data ...

KBDR KBSRPtr .FILL xFE00


1514 0 Polling YES KBDRPtr .FILL xFE02
ready bit KBSR
When KBDR is read: read
character
• KBSR[15] is set to zero
• keyboard is enabled

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 165 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 166

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Simple Implementation: Memory-Mapped Input Output to Monitor


When Monitor is ready to display another character:
• the “ready bit” (DSR[15]) is set to one

15 8 7 0
output data
Address Control Logic
determines whether DDR
1514 0
MDR is loaded from
Memory or from KBSR/KBDR. ready bit DSR
When data is written to Display Data Register:
• DSR[15] is set to zero
• character in DDR[7:0] is displayed
• any other character data written to DDR is ignored
(while DSR[15] is zero)

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 167 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 168

42
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Basic Output Routine Simple Implementation: Memory-Mapped Output

POLL LDI R1, DSRPtr


BRzp POLL
screen STI R0, DDRPtr
NO ready? ...
DSRPtr .FILL xFE04
Polling YES DDRPtr .FILL xFE06

write
character

Sets LD.DDR
or selects
DSR as input.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 169 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 170

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Keyboard Echo Routine Interrupt-Driven I/O


Usually, input character is also printed to screen. External device can:
• User gets feedback on character typed (1) Force currently executing program to stop;
and knows its ok to type the next character.
(2) Have the processor satisfy the device’s needs; and
POLL1 LDI R0, KBSRPtr new
(3) Resume the stopped program as if nothing happened.
BRzp POLL1 NO char?
LDI R0, KBDRPtr YES Why?
POLL2 LDI R1, DSRPtr
BRzp POLL2 read • Polling consumes a lot of cycles,
STI R0, DDRPtr
character especially for rare events – these cycles can be used
for more computation.
... • Example: Process previous input while collecting
screen current input. (See Example 8.1 in text.)
KBSRPtr .FILL xFE00 NO ready?
KBDRPtr .FILL xFE02
DSRPtr .FILL xFE04 YES

DDRPtr .FILL xFE06 write


character

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 171 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 172

43
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Interrupt-Driven I/O Priority


To implement an interrupt mechanism, we need: Every instruction executes at a stated level of urgency.
• A way for the I/O device to signal the CPU that an LC-3: 8 priority levels (PL0-PL7)
interesting event has occurred. • Example:
• A way for the CPU to test whether the interrupt signal is set  Payroll program runs at PL0.
and whether its priority is higher than the current program.
 Nuclear power correction program runs at PL6.

Generating Signal • It’s OK for PL6 device to interrupt PL0 program,


• Software sets "interrupt enable" bit in device register. but not the other way around.
• When ready bit is set and IE bit is set, interrupt is signaled.
Priority encoder selects highest-priority device,
interrupt enable bit 1514 13 0
compares to current processor priority level,
and generates interrupt signal if appropriate.
ready bit KBSR
interrupt signal
to processor

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 173 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 174

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Testing for Interrupt Signal


CPU looks at signal between STORE and FETCH phases.
If not set, continues with next instruction.
If set, transfers control to interrupt service routine.

F
Chapter 8
NO
D
TRAP Routines
Transfer to
ISR
YES interrupt EA and
signal?
OP Subroutines
EX

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 175 Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course

44
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

System Calls System Call


Certain operations require specialized knowledge 1. User program invokes system call.
and protection: 2. Operating system code performs operation.
• specific knowledge of I/O device registers
and the sequence of operations needed to use them 3. Returns control to user program.
• I/O resources shared among multiple users/programs;
a mistake could affect lots of other users!

Not every programmer knows (or wants to know)


this level of detail

Provide service routines or system calls


(part of operating system) to safely and conveniently
perform low-level, privileged operations

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 177 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 178

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

TRAP Instruction TRAP

Trap vector
• identifies which system call to invoke
• 8-bit index into table of service routine addresses
 in LC-3, this table is stored in memory at 0x0000 – 0x00FF
 8-bit trap vector is zero-extended into 16-bit memory address

Where to go
• lookup starting address from table; place in PC
How to get back
• save address of next instruction (current PC) in R7
NOTE: PC has already been incremented
during instruction fetch stage.
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 179 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 180

45
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

RET (JMP R7) TRAP Mechanism Operation


How do we transfer control back to
instruction following the TRAP?

We saved old PC in R7.


• JMP R7 gets us back to the user program at the right spot.
• LC-3 assembly language lets us use RET (return) 1. Lookup starting address.
in place of “JMP R7”. 2. Transfer to service routine.
3. Return (JMP R7).
Must make sure that service routine does not
change R7, or we won’t know where to return.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 181 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 182

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example: Using the TRAP Instruction Example: Output Service Routine


.ORIG x0430 ; syscall address
.ORIG x3000 ST R7, SaveR7 ; save R7 & R1
LD R2, TERM ; Load negative ASCII ‘7’ ST R1, SaveR1
LD R3, ASCII ; Load ASCII difference ; ----- Write character
TryWrite LDI R1, CRTSR ; get status
AGAIN TRAP x23 ; input character
BRzp TryWrite ; look for bit 15 on
ADD R1, R2, R0 ; Test for terminate WriteIt STI R0, CRTDR ; write char
BRz EXIT ; Exit if done ; ----- Return from TRAP
ADD R0, R0, R3 ; Change to lowercase Return LD R1, SaveR1 ; restore R1 & R7
TRAP x21 ; Output to monitor... LD R7, SaveR7
BRnzp AGAIN ; ... again and again... RET ; back to user
TERM .FILL xFFC9 ; -‘7’ CRTSR .FILL xF3FC
ASCII .FILL x0020 ; lowercase bit CRTDR .FILL xF3FF
EXIT TRAP x25 ; halt SaveR1 .FILL 0
SaveR7 .FILL 0
stored in table,
.END
.END location x21

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 183 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 184

46
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

TRAP Routines and their Assembler Names Saving and Restoring Registers
Must save the value of a register if:
• Its value will be destroyed by service routine, and
• We will need to use the value after that action.
vector symbol routine
x20 GETC read a single character (no echo) Who saves?
x21 OUT output a character to the monitor • caller of service routine?
 knows what it needs later, but may not know what gets altered by
x22 PUTS write a string to the console called routine
print prompt to console, • called service routine?
x23 IN  knows what it alters, but does not know what will be needed later
read and echo character from keyboard
by calling routine
x25 HALT halt the program

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 185 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 186

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example Saving and Restoring Registers


Called routine -- “callee-save”
LEA R3, Binary
LD R6, ASCII ; char->digit template • Before start, save any registers that will be altered
(unless altered value is desired by calling program!)
LD R7, COUNT ; initialize to 10
AGAIN TRAP x23 ; Get char • Before return, restore those same registers
ADD R0, R0, R6 ; convert to number
STR R0, R3, #0 ; store number Calling routine -- “caller-save”
ADD R3, R3, #1 ; incr pointer • Save registers destroyed by own instructions or
ADD R7, R7, -1 ; decr counter by called routines (if known), if values needed later
BRp AGAIN ; more?  save R7 before TRAP
BRnzp NEXT  save R0 before TRAP x23 (input character)
ASCII .FILL xFFD0 • Or avoid using those registers altogether
COUNT .FILL #10
Binary .BLKW #10
What’s wrong with this routine? Values are saved by storing them in memory.
What happens to R7?

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 187 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 188

47
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Subroutines JSR Instruction


A subroutine is a program fragment that:
• lives in user space
• performs a well-defined task
• is invoked (called) by another user program
Jumps to a location (like a branch but unconditional),
• returns control to the calling program when finished
and saves current PC (addr of next instruction) in R7.
Like a service routine, but not part of the OS • saving the return address is called “linking”
• not concerned with protecting hardware resources • target address is PC-relative (PC + Sext(IR[10:0]))
• no special privilege required • bit 11 specifies addressing mode
Reasons for subroutines:  if =1, PC-relative: target address = PC + Sext(IR[10:0])
• reuse useful (and debugged!) code without having to  if =0, register: target address = contents of register IR[8:6]
keep typing it in
• divide task among multiple programmers
• use vendor-supplied library of useful routines

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 189 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 190

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

JSR JSRR Instruction

Just like JSR, except Register addressing mode.


• target address is Base Register
• bit 11 specifies addressing mode

What important feature does JSRR provide


that JSR does not?

NOTE: PC has already been incremented


during instruction fetch stage.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 191 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 192

48
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

JSRR Returning from a Subroutine

RET (JMP R7) gets us back to the calling routine.


• just like TRAP

NOTE: PC has already been incremented


during instruction fetch stage.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 193 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 194

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example: Negate the value in R0 Passing Information to/from Subroutines


2sComp NOT R0, R0 ; flip bits Arguments
ADD R0, R0, #1 ; add one • A value passed in to a subroutine is called an argument.
RET ; return to caller • This is a value needed by the subroutine to do its job.
• Examples:
To call from a program (within 1024 instructions):  In 2sComp routine, R0 is the number to be negated
 In OUT service routine, R0 is the character to be printed.
; need to compute R4 = R1 - R3  In PUTS routine, R0 is address of string to be printed.
ADD R0, R3, #0 ; copy R3 to R0 Return Values
JSR 2sComp ; negate • A value passed out of a subroutine is called a return value.
ADD R4, R1, R0 ; add to R1 • This is the value that you called the subroutine to compute.
... • Examples:
Note: Caller should save R0 if we’ll need it later!  In 2sComp routine, negated value is returned in R0.
 In GETC service routine, character read from the keyboard
is returned in R0.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 195 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 196

49
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Using Subroutines Saving and Restore Registers


In order to use a subroutine, a programmer must know: Since subroutines are just like service routines,
• its address (or at least a label that will be bound to its address) we also need to save and restore registers, if needed.
• its function (what does it do?)
 NOTE: The programmer does not need to know Generally use “callee-save” strategy,
how the subroutine works, but except for return values.
what changes are visible in the machine’s state
• Save anything that the subroutine will alter internally
after the routine has run.
that shouldn’t be visible when the subroutine returns.
• its arguments (where to pass data in, if any)
• It’s good practice to restore incoming arguments to
• its return values (where to get computed data, if any) their original values (unless overwritten by return value).

Remember: You MUST save R7 if you call any other


subroutine or service routine (TRAP).
• Otherwise, you won’t be able to return to caller.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 197 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 198

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example CountChar Algorithm (using FirstChar)


(1) Write a subroutine FirstChar to:
find the first occurrence save regs R1 <- R2 + 1
of a particular character (in R0)
in a string (pointed to by R1);
return pointer to character or to end of string (NULL) in R2.
(2) Use FirstChar to write CountChar, which: call FirstChar
counts the number of occurrences save R7,
of a particular character (in R0) since we’re using JSR
in a string (pointed to by R1); R3 <- M(R2)
return count in R2.
Can write the second subroutine first, restore
without knowing the implementation of FirstChar!
regs
no
R3=0
return
yes
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 199 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 200

50
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

CountChar Implementation FirstChar Algorithm


; CountChar: subroutine to count occurrences of a char
CountChar yes
save regs R3=R0
ST R3, CCR3 ; save registers
ST R4, CCR4
ST R7, CCR7 ; JSR alters R7
ST R1, CCR1 ; save original string ptr no
AND R4, R4, #0 ; initialize count to zero R2 <- R1
CC1 JSR FirstChar ; find next occurrence (ptr in R2)
LDR R3, R2, #0 ; see if char or null R2 <- R2 + 1
BRz CC2 ; if null, no more chars
ADD R4, R4, #1 ; increment count R3 <- M(R2)
ADD R1, R2, #1 ; point to next char in string
BRnzp CC1
CC2 ADD R2, R4, #0 ; move return val (count) to R2 restore
LD R3, CCR3 ; restore regs regs
LD R4, CCR4
LD R1, CCR1 no
LD R7, CCR7 R3=0
RET ; and return return
yes
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 201 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 202

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

FirstChar Implementation Library Routines


; FirstChar: subroutine to find first occurrence of a char Vendor may provide object files containing
FirstChar useful subroutines
ST R3, FCR3 ; save registers • don’t want to provide source code -- intellectual property
ST R4, FCR4 ; save original char • assembler/linker must support EXTERNAL symbols
NOT R4, R0 ; negate R0 for comparisons (or starting address of routine must be supplied to user)
ADD R4, R4, #1 ...
ADD R2, R1, #0 ; initialize ptr to beginning of string .EXTERNAL SQRT
FC1 LDR R3, R2, #0 ; read character ...
BRz FC2 ; if null, we’re done LD R2, SQAddr ; load SQRT addr
ADD R3, R3, R4 ; see if matches input char JSRR R2
BRz FC2 ; if yes, we’re done ...
ADD R2, R2, #1 ; increment pointer SQAddr .FILL SQRT
BRnzp FC1
FC2 LD R3, FCR3 ; restore registers
LD R4, FCR4 ; Using JSRR, because we don’t know whether SQRT
RET ; and return is within 1024 instructions.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 203 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 204

51
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Stack: An Abstract Data Type


An important abstraction that you will encounter
in many applications.

We will describe three uses:


Chapter 9 Interrupt-Driven I/O
• The rest of the story…
And, Finally... Evaluating arithmetic expressions
• Store intermediate results on stack instead of in registers
The Stack Data type conversion
• 2’s comp binary to ASCII strings

Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 206

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Stacks A Physical Stack


A LIFO (last-in first-out) storage structure.
Coin rest in the arm of an automobile
• The first thing you put in is the last thing you take out.
• The last thing you put in is the first thing you take out.
1995 1996 1998
1998 1982
This means of access is what defines a stack, 1982 1995
1995
not the specific implementation.

Two main operations:


PUSH: add an item to the stack
POP: remove an item from the stack
Initial State After After Three After
One Push More Pushes One Pop

First quarter out is the last quarter in.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 207 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 208

52
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

A Hardware Implementation A Software Implementation


Data items move between registers Data items don't move in memory,
just our idea about there the TOP of the stack is.

Empty: Yes Empty: No Empty: No Empty: No

////// TOP #18 TOP #12 TOP #31 TOP ////// ////// #12 TOP #12
////// ////// #5 #18 ////// ////// #5 #5
////// ////// #31 ////// ////// ////// #31 #31 TOP

////// ////// #18 ////// ////// #18 TOP #18 #18


////// ////// ////// ////// ////// TOP ////// ////// //////
Initial State After After Three After x4000 R6 x3FFF R6 x3FFC R6 x3FFE R6
One Push More Pushes Two Pops
Initial State After After Three After
One Push More Pushes Two Pops

By convention, R6 holds the Top of Stack (TOS) pointer.


Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 209 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 210

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Basic Push and Pop Code Pop with Underflow Detection


For our implementation, stack grows downward If we try to pop too many items off the stack,
(when item added, TOS moves closer to 0) an underflow condition occurs.
• Check for underflow by checking TOS before removing data.
Push • Return status code in R5 (0 for success, 1 for underflow)
ADD R6, R6, #-1 ; decrement stack ptr
STR R0, R6, #0 ; store data (R0) POP LD
R1, EMPTY ; EMPTY = -x4000
ADD R2, R6, R1 ; Compare stack pointer
BRz FAIL ; with x3FFF
LDR R0, R6, #0
Pop ADD R6, R6, #1
AND R5, R5, #0 ; SUCCESS: R5 = 0
LDR R0, R6, #0 ; load data from TOS RET
ADD R6, R6, #1 ; decrement stack ptr FAIL AND R5, R5, #0 ; FAIL: R5 = 1
ADD R5, R5, #1
RET
EMPTY .FILL xC000

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 211 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 212

53
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Push with Overflow Detection Interrupt-Driven I/O (Part 2)


If we try to push too many items onto the stack, Interrupts were introduced in Chapter 8.
an overflow condition occurs. 1. External device signals need to be serviced.
• Check for underflow by checking TOS before adding data. 2. Processor saves state and starts service routine.
• Return status code in R5 (0 for success, 1 for overflow) 3. When finished, processor restores state and resumes program.

PUSH LD R1, MAX ; MAX = -x3FFB Interrupt is an unscripted subroutine call,


ADD R2, R6, R1 ; Compare stack pointer triggered by an external event.
BRz FAIL ; with x3FFF
ADD R6, R6, #-1
STR R0, R6, #0 Chapter 8 didn’t explain how (2) and (3) occur,
AND R5, R5, #0 ; SUCCESS: R5 = 0
because it involves a stack.
RET
FAIL AND R5, R5, #0 ; FAIL: R5 = 1
ADD R5, R5, #1 Now, we’re ready…
RET
MAX .FILL xC005

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 213 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 214

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Processor State Where to Save Processor State?


What state is needed to completely capture the Can’t use registers.
state of a running process? • Programmer doesn’t know when interrupt might occur,
Processor Status Register so she can’t prepare by saving critical registers.
• Privilege [15], Priority Level [10:8], Condition Codes [2:0] • When resuming, need to restore state exactly as it was.

Memory allocated by service routine?


Program Counter • Must save state before invoking routine,
so we wouldn’t know where.
• Pointer to next instruction to be executed.
• Also, interrupts may be nested –
that is, an interrupt service routine might also get interrupted!
Registers
• All temporary state of the process that’s not stored in memory.
Use a stack!
• Location of stack “hard-wired”.
• Push state to save, pop to restore.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 215 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 216

54
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Supervisor Stack Invoking the Service Routine – The Details


A special region of memory used as the stack 1. If Priv = 1 (user),
for interrupt service routines. Saved.USP = R6, then R6 = Saved.SSP.
• Initial Supervisor Stack Pointer (SSP) stored in Saved.SSP. 2. Push PSR and PC to Supervisor Stack.
• Another register for storing User Stack Pointer (USP): 3. Set PSR[15] = 0 (supervisor mode).
Saved.USP. 4. Set PSR[10:8] = priority of interrupt being serviced.
5. Set PSR[2:0] = 0.
Want to use R6 as stack pointer. 6. Set MAR = x01vv, where vv = 8-bit interrupt vector
provided by interrupting device (e.g., keyboard = x80).
• So that our PUSH/POP routines still work.
7. Load memory location (M[x01vv]) into MDR.
8. Set PC = MDR; now first instruction of ISR will be fetched.
When switching from User mode to Supervisor mode
(as result of interrupt), save R6 to Saved.USP.

Note: This all happens between the STORE RESULT


of the last user instruction and the FETCH of
the first ISR instruction.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 217 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 218

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Returning from Interrupt Example (1)


Special instruction – RTI – that restores state.
Program A
Saved.SSP
1. Pop PC from supervisor stack. (PC = M[R6]; R6 = R6 + 1) //////
2. Pop PSR from supervisor stack. (PSR = M[R6]; R6 = R6 + 1) ////// x3006 ADD
3. If PSR[15] = 1, R6 = Saved.USP. //////
(If going back to user mode, need to restore User Stack Pointer.)
//////
//////
RTI is a privileged instruction.
• Can only be executed in Supervisor Mode. PC x3006
• If executed in User Mode, causes an exception.
(More about that later.)

Executing ADD at location x3006 when Device B interrupts.


Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 219 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 220

55
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example (2) Example (3)


Program A ISR for Program A ISR for
Device B
Device B
x6200
////// x6200
//////
////// x3006 ADD ////// x6202 AND
x3007 x3006 ADD
R6 R6 x3007
PSR for A
x6210 RTI PSR for A
RTI
////// x6210
//////

PC x6200
PC x6203

Saved.USP = R6. R6 = Saved.SSP.


Push PSR and PC onto stack, then transfer to Executing AND at x6202 when Device C interrupts.
Device B service routine (at x6200).
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 221 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 222

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example (4) Example (5)


Program A ISR for Program A ISR for
Device B Device B
x6200 x6200
R6 x6203 x6203
PSR for B x6202 AND PSR for B x6202 AND
x3006 ADD x3006 ADD
ISR for ISR for
x3007 Device C R6 x3007 Device C
PSR for A PSR for A
x6210 RTI x6300 x6210 RTI x6300
////// //////

PC x6300 PC x6203
x6315 RTI x6315 RTI

Push PSR and PC onto stack, then transfer to Execute RTI at x6315; pop PC and PSR from stack.
Device C service routine (at x6300).
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 223 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 224

56
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example (6) Exception: Internal Interrupt


When something unexpected happens
Program A ISR for inside the processor, it may cause an exception.
Saved.SSP Device B
x6200
x6203 Examples:
PSR for B x6202 AND • Privileged operation (e.g., RTI in user mode)
x3006 ADD
ISR for • Executing an illegal opcode
x3007 Device C
PSR for A • Divide by zero
x6210 RTI x6300
• Accessing an illegal address (e.g., protected system memory)
//////
Handled just like an interrupt
PC x3007 • Vector is determined internally by type of exception
x6315 RTI • Priority is the same as running program

Execute RTI at x6210; pop PSR and PC from stack.


Restore R6. Continue Program A as if nothing happened.
Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 225 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 226

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Arithmetic Using a Stack Example: OpAdd


Instead of registers, some ISA's use a stack for POP two values, ADD, then PUSH result.
source and destination operations: a zero-address machine.
• Example:
START
ADD instruction pops two numbers from the stack,
adds them, and pushes the result to the stack.

POP POP ADD


Evaluating (A+B)·(C+D) using a stack:
(1) push A
(2) push B
Range
(3) ADD OK? OK?
OK?
Yes Yes Yes
(4) push C
(5) push D Why use a stack? No No
No
(6) ADD • Limited registers.
(7) MULTIPLY • Convenient calling convention Put back first Put back both PUSH
(8) pop result
for subroutines.
• Algorithm naturally expressed
using FIFO data structure. RETURN

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 227 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 228

57
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Example: OpAdd Data Type Conversion


Keyboard input routines read ASCII characters,
OpAdd JSR POP ; Get first operand. not binary values.
ADD R5,R5,#0 ; Check for POP success. Similarly, output routines write ASCII.
BRp Exit ; If error, bail.
Consider this program:
ADD R1,R0,#0 ; Make room for second.
TRAP x23 ; input from keybd
JSR POP ; Get second operand. ADD R1, R0, #0 ; move to R1
ADD R5,R5,#0 ; Check for POP success. TRAP x23 ; input from keybd
BRp Restore1 ; If err, restore & bail. ADD R0, R1, R0 ; add two inputs
ADD R0,R0,R1 ; Compute sum. TRAP x21 ; display result
JSR RangeCheck ; Check size. TRAP x25 ; HALT
BRp Restore2 ; If err, restore & bail. User inputs 2 and 3 -- what happens?
JSR PUSH ; Push sum onto stack. Result displayed: e
RET
Restore2 ADD R6,R6,#-1 ; Decr stack ptr (undo POP) Why? ASCII '2' (x32) + ASCII '3' (x33) = ASCII 'e' (x65)
Restore1 ADD R6,R6,#-1 ; Decr stack ptr
Exit RET

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 229 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 230

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

ASCII to Binary Multiplication via a Lookup Table


Useful to deal with mult-digit decimal numbers How can we multiply a number by 100?
Assume we've read three ASCII digits (e.g., "259") • One approach:
into a memory buffer. Add number to itself 100 times.
• Another approach:
How do we convert this to a number x32 '2' Add 100 to itself <number> times. (Better if number < 100.)
we can use? x35 '5'
• Convert first character to digit (subtract x30)
and multiply by 100. x39 '9' Since we have a small range of numbers (0-9),
• Convert second character to digit and
use number as an index into a lookup table.
multiply by 10. Entry 0: 0 x 100 = 0
• Convert third character to digit. Entry 1: 1 x 100 = 100
• Add the three digits together. Entry 2: 2 x 100 = 200
Entry 3: 3 x 100 = 300
etc.

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 231 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 232

58
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Code for Lookup Table Complete Conversion Routine (1 of 3)


; multiply R0 by 100, using lookup table ; Three-digit buffer at ASCIIBUF.
; ; R1 tells how many digits to convert.
LEA R1, Lookup100 ; R1 = table base ; Put resulting decimal number in R0.
ADD R1, R1, R0 ; add index (R0) ASCIItoBinary AND R0, R0, #0 ; clear result
LDR R0, R1, #0 ; load from M[R1] ADD R1, R1, #0 ; test # digits
... BRz DoneAtoB ; done if no digits
Lookup100 .FILL 0 ; entry 0 ;
.FILL 100 ; entry 1 LD R3, NegZero ; R3 = -x30
.FILL 200 ; entry 2 LEA R2, ASCIIBUF
.FILL 300 ; entry 3 ADD R2, R2, R1
.FILL 400 ; entry 4 ADD R2, R2, #-1 ; points to ones digit
.FILL 500 ; entry 5 ;
.FILL 600 ; entry 6 LDR R4, R2, #0 ; load digit
.FILL 700 ; entry 7 ADD R4, R4, R3 ; convert to number
.FILL 800 ; entry 8 ADD R0, R0, R4 ; add ones contrib
.FILL 900 ; entry 9

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 233 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 234

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Conversion Routine (2 of 3) Conversion Routine (3 of 3)


ADD R1, R1, #-1 ; one less digit LDR R4, R2, #0 ; load digit
BRz DoneAtoB ; done if zero ADD R4, R4, R3 ; convert to number
ADD R2, R2, #-1 ; points to tens digit LEA R5, Lookup100 ; multiply by 100
; ADD R5, R5, R4
LDR R4, R2, #0 ; load digit LDR R4, R5, #0
ADD R4, R4, R3 ; convert to number ADD R0, R0, R4 ; adds 100's contrib
LEA R5, Lookup10 ; multiply by 10 ;
ADD R5, R5, R4 DoneAtoB RET
LDR R4, R5, #0 NegZero .FILL xFFD0 ; -x30
ADD R0, R0, R4 ; adds tens contrib ASCIIBUF .BLKW 4
; Lookup10 .FILL 0
ADD R1, R1, #-1 ; one less digit .FILL 10
BRz DoneAtoB ; done if zero .FILL 20
ADD R2, R2, #-1 ; points to hundreds ...
; digit Lookup100 .FILL 0
.FILL 100
...

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 235 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 236

59
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Binary to ASCII Conversion Binary to ASCII Conversion Code (part 1 of 3)


Converting a 2's complement binary value to ; R0 is between -999 and +999.
a three-digit decimal number ; Put sign character in ASCIIBUF, followed by three
; ASCII digit characters.
• Resulting characters can be output using OUT

BinaryToASCII LEA R1, ASCIIBUF ; pt to result string


Instead of multiplying, we need to divide by 100 ADD R0, R0, #0 ; test sign of value
to get hundreds digit. BRn NegSign
• Why wouldn't we use a lookup table for this problem? LD R2, ASCIIplus ; store '+'
STR R2, R1, #0
• Subtract 100 repeatedly from number to divide.
BRnzp Begin100
NegSign LD R2, ASCIIneg ; store '-'
First, check whether number is negative. STR R2, R1, #0
• Write sign character (+ or -) to buffer and make positive. NOT R0, R0 ; convert value to pos
ADD R0, R0, #1

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 237 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 238

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Conversion (2 of 3) Conversion Code (3 of 3)


Begin100 LD R2, ASCIIoffset End10 STR R2, R1, #2 ; store ASCII 10's digit
LD R3, Neg100 ADD R0, R0, #10 ; restore last subtract
Loop100 ADD R0, R0, R3 ;
BRn End100 LD R2, ASCIIoffset
ADD R2, R2, #1 ; add one to digit ADD R2, R2, R0 ; convert one's digit
BRnzp Loop100 STR R2, R1, #3 ; store one's digit
End100 STR R2, R1, #1 ; store ASCII 100's digit RET
LD R3, Pos100
ADD R0, R0, R3 ; restore last subtract ;
; ASCIIplus .FILL x2B ; plus sign
LD R2, ASCIIoffset ASCIIneg .FILL x2D ; neg sign
LD R3, Neg10 ASCIIoffset .FILL x30 ; zero
Loop100 ADD R0, R0, R3 Neg100 .FILL xFF9C ; -100
BRn End10 Pos100 .FILL #100
ADD R2, R2, #1 ; add one to digit Neg10 .FILL xFFF6 ; -10
BRnzp Loop10

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 239 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 240

60
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

C: A High-Level Language
Gives symbolic names to values
• don’t need to know which register or memory location
Provides abstraction of underlying hardware
• operations do not depend on instruction set
Chapter 10 • example: can write “a = b * c”, even though
LC-3 doesn’t have a multiply instruction

Introduction to Provides expressiveness


• use meaningful symbols that convey meaning

Programming in C • simple expressions for common control patterns (if-then-else)


Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time

Microprocessor and Microcontroller Course 9/23/2009 Microprocessor and Microcontroller Course Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 242

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Compilation vs. Interpretation Compilation vs. Interpretation


Different ways of translating high-level language Consider the following algorithm:
Interpretation • Get W from the keyboard.
• interpreter = program that executes program statements
• X = W + W
• generally one line/command at a time
• Y = X + X
• limited processing
• easy to debug, make changes, view intermediate results
• Z = Y + Y
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell • Print Z to screen.
Compilation If interpreting, how many arithmetic operations occur?
• translates statements into machine language If compiling, we can analyze the entire program and possibly reduce
 does not execute, but creates executable program the number of operations. Can we simplify the above algorithm to
• performs optimization over multiple statements use a single
• change requires recompilation arithmetic operation?
 can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 243 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 244

61
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Compiling a C Program Source and


Header Files Compiler
Entire mechanism is usually called Source Code Analysis
the “compiler” • “front end”
Preprocessor C Preprocessor
• parses programs to identify its pieces
• macro substitution  variables, expressions, statements, functions, etc.
• conditional compilation Compiler • depends on language (not on target machine)
• “source-level” transformations Source Code Code Generation
Analysis
 output is still C • “back end”
Symbol Table
Compiler Target Code • generates machine code from analyzed source
Synthesis
• generates object file • may optimize machine code to make it run more efficiently
 machine instructions • very dependent on target machine
Linker Library
Symbol Table
Linker
Object Files
• combine object files • map between symbolic names and items
(including libraries) • like assembler, but more kinds of information
into executable image
Executable
Image

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 245 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 246

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

A Simple C Program Preprocessor Directives


#include <stdio.h> #include <stdio.h>
#define STOP 0
• Before compiling, copy contents of header file (stdio.h)
into source code.
/* Function: main */
/* Description: counts down from user input to STOP */ • Header files typically contain descriptions of functions and
main() variables needed by the program.
{  no restrictions -- could be any C source code
/* variable declarations */
int counter; /* an integer to hold count values */
#define STOP 0
int startPoint; /* starting point for countdown */
/* prompt user for input */ • Before compiling, replace all instances of the string
printf("Enter a positive number: "); "STOP" with the string "0"
scanf("%d", &startPoint); /* read into startPoint */ • Called a macro
/* count down and print count */ • Used for values that won't change during execution,
for (counter=startPoint; counter >= STOP; counter--) but might change if the program is reused. (Must recompile.)
printf("%d\n", counter);
}

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 247 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 248

62
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Comments main Function


Begins with /* and ends with */ Every C program must have a function called main().

Can span multiple lines This is the code that is executed


Cannot have a comment within a comment when the program is run.
Comments are not recognized within a string
• example: "my/*don't print this*/string" The code for the function lives within brackets:
would be printed as: my/*don't print this*/string main()
{
As before, use comments to help reader, not to confuse /* code goes here */
or to restate the obvious }

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 249 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 250

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Variable Declarations Input and Output


Variables are used as names for data items. Variety of I/O functions in C Standard Library.
Each variable has a type, Must include <stdio.h> to use them.
which tells the compiler how the data is to be interpreted
(and how much space it needs, etc.). printf("%d\n", counter);
• String contains characters to print and
formatting directions for variables.
int counter;
• This call says to print the variable counter as a decimal integer,
int startPoint; followed by a linefeed (\n).

int is a predefined integer type in C. scanf("%d", &startPoint);


• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to the
variable startPoint. (Don't worry about the & yet.)

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 251 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 252

63
Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

More About Output Examples


Can print arbitrary expressions, not just variables This code:
printf("%d\n", startPoint - counter); printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
Print multiple expressions with a single statement printf("43 plus 59 as a character is %c.\n", 43+59);
printf("%d %d\n", counter,
startPoint - counter);
produces this output:
Different formatting options: 43 is a prime number.
%d decimal integer 43 + 59 in decimal is 102.
%x hexadecimal integer 43 + 59 in hex is 66.
%c ASCII character 43 + 59 as a character is f.
%f floating-point number

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 253 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 254

Department of Computer Engineering, University of Information Technology Department of Computer Engineering, University of Information Technology

Examples of Input Compiling and Linking


Many of the same formatting characters are Various compilers available
available for user input. • cc, gcc
• includes preprocessor, compiler, and linker
scanf("%c", &nextChar);
• reads a single character and stores it in nextChar Lots and lots of options!
scanf("%f", &radius); • level of optimization, debugging
• reads a floating point number and stores it in radius • preprocessor, linker options
scanf("%d %d", &length, &width); • intermediate files --
• reads two decimal integers (separated by whitespace), object (.o), assembler (.s), preprocessor (.i), etc.
stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.


(Explained in Chapter 16.)

Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 255 Microprocessor and Microcontroller Course 9/23/2009 Computer Systems 256

64

Vous aimerez peut-être aussi