Professional Documents
Culture Documents
Logic and Digital Systems
Logic and Digital Systems
Logic and
Digital Systems
1. Boolean Logic, Gates & Devices
2. Assembly & Computers
Haroon Chughtai Logic and Digital Systems 17/04/2013
Contents
1.1 Digital Vs. Analogue ............................................................................................................... 7
Advantages of Digital Systems ............................................................................................................ 7
Disadvantages of Digital Systems ....................................................................................................... 7
Basic Logic Principles........................................................................................................................... 7
1.2 Logic Devices .......................................................................................................................... 8
Relays .................................................................................................................................................. 8
Thermionic Valves ............................................................................................................................... 8
Transistors ........................................................................................................................................... 8
Use as Switches ............................................................................................................................... 8
CMOS FET ........................................................................................................................................ 8
1.3 Boolean Logic and Logic Gates ................................................................................................ 9
Boolean Values.................................................................................................................................... 9
Logic Gates .......................................................................................................................................... 9
Truth Tables .................................................................................................................................... 9
Boolean Operators and Gates ............................................................................................................. 9
OR Gate ........................................................................................................................................... 9
AND Gate......................................................................................................................................... 9
NOT Gate ......................................................................................................................................... 9
XOR Gate ....................................................................................................................................... 10
NAND, NOR and XNOR .................................................................................................................. 10
Multi-Input Gates .............................................................................................................................. 11
Boolean Relationships and Forms..................................................................................................... 11
De Morgan’s Theorem .................................................................................................................. 11
Laws of Boolean Algebra ............................................................................................................... 11
Rules of Boolean Algebra .............................................................................................................. 11
Sum of Products (SOP) Form ......................................................................................................... 12
Simplification and Minimisation ....................................................................................................... 13
Minimisation by Boolean Algebra ................................................................................................. 13
Minimisation by Karnaugh Maps .................................................................................................. 13
1.4 Binary Arithmetic ................................................................................................................. 15
Binary Number System ..................................................................................................................... 15
Integer and Fractional Parts .......................................................................................................... 15
Conversion: Decimal to Binary ...................................................................................................... 15
2
Haroon Chughtai Logic and Digital Systems 17/04/2013
3
Haroon Chughtai Logic and Digital Systems 17/04/2013
4
Haroon Chughtai Logic and Digital Systems 17/04/2013
5
Haroon Chughtai Logic and Digital Systems 17/04/2013
6
Haroon Chughtai Logic and Digital Systems 17/04/2013
7
Haroon Chughtai Logic and Digital Systems 17/04/2013
Relays
Electromagnetic device
Allows current through a coil to
close one or more independent set
of switch contacts
Can be NO or NC
Bulky, slow (100 us) and unreliable
Power hungry
Thermionic Valves
Faster (10 us)
Large and hot
Unreliable
Transistors
Fast (10 ns)
Very small (microns), allowing integrated chips
Very reliable
Use as Switches
Transistors are 3-terminal
devices
An input voltage applied to the
control terminal causes a
conducting path between the
other 2 terminals to be closed
(ON) or opened (OFF)
CMOS FET
Current flows between two contact electrodes, the source and the drain, via a
pathway known as a channel.
o Above the channel is a further electrode, the gate.
Field applied across an insulating layer between the gate and the substrate can
be made to control the resistivity of the channel.
o So the source-drain current may be passed or blocked at will
o The device acts as a switch.
Different types of CMOS transistors exist.
o N-channel FETs operate via flow of electrons
Output is HIGH when input is HIGH (and vice-versa)
o P-channel FETs operate using
holes
Output is HIGH when
input is LOW (and vice-
versa)
8
Haroon Chughtai Logic and Digital Systems 17/04/2013
Logic Gates
Logic gates are electronic circuits constructed from transistors
o One or more input wires
o One output wire
The voltage on the output depends on the input
o How it depends is based by the logical function performed by the internal
circuitry
To analyse a circuit we presume every input is either HIGH or LOW
Truth Tables
A circuit’s behaviour can be described concisely by tabulating the output
values for every possible combination of input values
o Examples below
9
Haroon Chughtai Logic and Digital Systems 17/04/2013
XOR Gate
Takes 2 inputs, and
generates an output which is
1 if either A or B is 1 but
not both.
o This is called the exclusive-OR (XOR) function.
NAND, NOR and XNOR
AND, OR and XOR with output inversions
NAND and NOR gates are versatile as they can be used to implement all other
Boolean operations:
o They are functionally complete
NAND gate Inverter
Connecting the two inputs of a NAND creates a NOT gate
o This can be used to create other NAND only gates
NAND gate OR
This arrangement demonstrates
how AND functions can be
converted to OR functions
o By inverting the inputs and
putting them through a
NAND gate we get OR
functionality
o This is known as De
Morgan’s Theorem (see
below)
Using NANDs
10
Haroon Chughtai Logic and Digital Systems 17/04/2013
Multi-Input Gates
The number of potential inputs depends on the gate:
o OR and AND gates (and NOR and NAND) can have any number of inputs
o XOR and XNOR gates can have only two inputs
o The NOT gate (inverter) has only one input
For the multi-input gates, the Truth Table is constructed using a separate
column for each input.
o Each additional input doubles the number of possible combinations
of 1 or 0 states – each combination occupies one row of the table
o Therefore for N inputs, there will be rows
11
Haroon Chughtai Logic and Digital Systems 17/04/2013
8. ̅
o Variable ANDed with its complement is always 0
9. ̿
o Double complement of a variable is always the variable
10.
o Can be proved by applying the distributive law, rule 2 and rule 4
( )
11. ̅
o ̅ ( ) ̅ ( ) ̅ ̅ ̅
( ̅ )( ) ( )
Sum of Products (SOP) Form
When two or more product terms are
summed by Boolean addition (OR) the
resulting expression is a sum-of-products
(SOP)
o E.g.,
̅ ̅ ̅ ̅
o Can be directly translated into gates
but may not be the most efficient
design
E.g. ( )
First requires 3 gates but second requires 2
Canonical Form: Standard SOP Form
A standard (or canonical) SOP expression is one in which all the variables in
the domain appear in each product term in the expression
o E.g.: (̅ ) ( ̅ ) ( )
o Generally: ( ) ̅ ̅ ̅ ̅
In canonical SOP each product term is known as a minterm
Not efficient, but sometimes useful in analysis and design
o E.g. truth table construction and Karnaugh map simplification method
Converting SOP to Canonical SOP
An SOP expression can be forced into
canonical form by ANDing the incomplete
terms with terms of the form ̅ where X
is the missing variable
Converting Canonical SOP to Truth Table Format
A SOP is equal to 1 if any of the product
terms is equal to 1
o So the output is 1 when any minterm is
represented in the table
Where each variable
̅
can be written as the sum of row numbers
having TRUE minterms ∑( )
12
Haroon Chughtai Logic and Digital Systems 17/04/2013
13
Haroon Chughtai Logic and Digital Systems 17/04/2013
14
Haroon Chughtai Logic and Digital Systems 17/04/2013
Binary Addition
Looking at each column in turn, we see that the rules are:
o 0 + 1 = 1, carry out = 0
o 1 + 0 = 1, carry out = 0
o 1 + 1 = 0, carry out = 1
o (and 0 + 0 = 0 , carry out = 0)
We can write these rules as a truth table:
o Clearly and
15
Haroon Chughtai Logic and Digital Systems 17/04/2013
Half Adder
This can be used to construct a half-adder
The half adder will generate the Sum and Carry-out for one column of an
addition sum.
However, it does not allow for a possible Carry-in from a previous column.
o To do this, we must use TWO half-adders: one to form the sum of A
and B, then another to add any carry-in to this intermediate sum.
If EITHER of the two additions generates a carry-out, we must indicate that
fact by setting the final Carry-out to 1.
o The total circuit is called a Full Adder.
Full Adder
16
Haroon Chughtai Logic and Digital Systems 17/04/2013
17
Haroon Chughtai Logic and Digital Systems 17/04/2013
Binary Subtraction
( )
o Now
o So -
o And
Therefore ( )
o
o Note that the carry out of the MSB has been discarded so the binary
word is the same length as the inputs
Sign Extension
Sometimes we need to extend a number to have more bits:
In Decimal:
o Converting 12 into a 4 digit number gives 0012
o We add 0's to the left-hand side
In Unsigned binary:
o Converting 0011 into an 8 bit number gives 00000011
o We add 0's to the left-hand side
In Signed binary we must duplicate the sign bit (MSB):
o Converting 0011 into 8 bits gives 00000011 (duplicate the 0 MSB)
o Converting 1011 into 8 bits gives 11111011 (duplicate the 1 MSB)
o Called "Sign Extension”
Subtraction Machine
We found that A SUB B = (A ADD B ) ADD 1
o This is very easy to implement on our array of full-adders
We just have to pass all of the B-input bits through inverters,
Then we must set Carry-in to
a 1 on the least significant
full-adder (remember that for
addition it was set to 0)
A practical arithmetic processor has a
single control input that switches the B-
inverters in or out as required.
o One way to do this is to use XOR
gates as controllable inverters:
If B' = U XOR B, then B’ = B
when U is LOW, and B' = B
when U is HIGH
18
Haroon Chughtai Logic and Digital Systems 17/04/2013
SET-RESET Latches
NAND S-R Latch
If we put NANDs instead of the inverters, we can
use the two spare inputs to force the bistable
circuit into either of its two stable states:
1. Initially both ̅ and ̅ are high.
X and Y are unknown.
2. A low-going pulse on S will INPUTS OUTPUTS Comments
̅ ̅ ̅
force X high, by the NAND
0 0 1 1 Invalid
action. 0 1 1 0 SET
This is defined as 1 0 0 1 RESET
SETTING the latch. 1 1 NC NC No change:
3. This high X is fed back to the latch remains in previous condition
input of the other NAND gate (unknown initially)
Since R is normally high, that will cause Y to go low.
4. This low at Y is fed back to the first NAND gate, reinforcing the high at X
regardless of what now happens at the S input.
Thus once the latch is SET, any more pulses at the S input will have no
further effect.
5. Once it is set, the only way to change the state of the latch is to assert a low-
going pulse at the R input
This will force Y high, and hence X low, thereby CLEARING the latch.
Once the latch is cleared, subsequent pulses at the R input will have no
further effect.
6. If both S and R are taken low at the same time, both X and Y outputs will go
high,
Because both NANDs will each have one low input.
However, this is an unstable state and will revert.
7. In the stable states, Y is normally the inverse of X
The two outputs are therefore called and ̅
19
Haroon Chughtai Logic and Digital Systems 17/04/2013
Active-Low Inputs
Because ̅ and ̅ produce their effect when they
are taken from high to low, they are called
active-low inputs.
o To show this, they have half-arrowheads
on the logic symbol.
NOR S-R Latch
An S-R Latch can also be made using NOR gates.
In this case the inputs will set or clear the latch
when they are taken from a low to a high state
o So they are active-high inputs.
They are shown without the half-arrowheads on the
logic symbol.
o Also their names do not have bars above them
Application: Switch Denouncing
A common application for S-R latches is in cleaning up multiple pulses which
are often obtained from a mechanical switch or push button
o This is because the spring contacts bounce rapidly several times when the
switch is pressed.
The SR latch gives an output which changes firmly from one state to the
other and stays in the new state until a different pushbutton is pressed.
o This makes the operation of a control panel much more reliable.
20
Haroon Chughtai Logic and Digital Systems 17/04/2013
D Flip-Flop
Similar to the Transparent Latch but the control input is
called CLOCK instead of ENABLE.
o The CLOCK input is edge-triggered
Q takes on the sampled value of the D
(DATA) input
at the instant INPUTS OUTPUTS Comments
̅
when the X 0 ̅ No change from previous output
CLOCK X 1 ̅ No change from previous output
changes from 0 0 1 RESET
low to high. 1 1 0 SET
o At all other times Q
remains unchanged.
The D input is ignored most of the time, and is only sampled for a brief
instant at each CLOCK rising edge.
o The edge sensitivity of the CLOCK input is indicated by the > inside the
logic symbol, and the up arrow in the truth table
Divide-by-2 Circuit
The D input is connected to the INVERTED Q output
At each rising edge of CLOCK, whatever is on D is
stored and becomes the new value of Q
o Since D is always the inverse of Q, the flip-flop
will therefore change state at each CLOCK
rising edge
So Q alternates at a frequency which is half that of the CLOCK input.
Ripple Counters
Ripple Down-Counter
Connecting three divide-by-2 circuits
in a chain will therefore divide an input
frequency by 8
E.g. if CLOCK has a frequency of 8 kHz
o Q0 will change at 4 kHz
o Q1 will change at 2 kHz
o Q2 will change at 1 kHz.
This gives a modulus 8 countdown from
7 to 0 and then repeats
Ripple Up-Counter
If we want to make the counter count up
instead of down,
o We need to connect the CLOCK
input of each stage to the
INVERTED Q output of the
preceding stage
21
Haroon Chughtai Logic and Digital Systems 17/04/2013
22
Haroon Chughtai Logic and Digital Systems 17/04/2013
Synchronous Counter
Using T flip-flops, we can make a more
reliable type of counter, the Synchronous
Counter.
o In this, all the flip-flops change
simultaneously (if required) at the
end of the clock pulse
o Does not suffer from the delays
and glitches inherent in Ripple Counters
For a synchronous counter, each flip-flop is "told" whether to
change or not on the next clock cycle
o This information is obtained from the current state of the
other flip-flops:
o (If all LSB outputs are HIGH then toggle)
We can arrange for a synchronous counter to be reset at any given
count state, so it can have any desired modulus
23
Haroon Chughtai Logic and Digital Systems 17/04/2013
Data Registers
A circuit which can temporarily store
all the bits of a binary number
o Easily made from a row of JK
flip-flops used as D flip-flops
One flip-flop per bit of the number to
be stored
Shared clock, so when the clock pulse arrives the
values of all the D input bits are read in and
stored simultaneously
o A typical personal computer will have
several 16-bit and 32-bit data registers in its
arithmetic unit
The diagram above shows a 3-bit register
o Logic symbol:
Shift Registers
Flip-flops are arranged in a
chain
o Each Q output forms
the input to the next
stage:
Each clock cycle causes the data pattern to shift
one place down the chain.
o New bit values can be fed in at the Data
input
o Bits are lost from the final output (here Q2)
If DATA is set to 0 then each clock pulse will cause
the binary number to double until bits are lost.
24
Haroon Chughtai Logic and Digital Systems 17/04/2013
Binary Multiplication
Example: Let A = 3 (multiplicand), B = 5 (multiplier)
o Then C = A x B = 3 x 5 in decimal
In binary we can write:
o A 00011x
o B 00101=
So C = 1 x (1 x 3) ie. 1 x (1 x A)
+ 0 x (2 x 3) + 0 x (2 x A)
+ 1 x (4 x 3) + 1 x (4 x A)
So we can do the
multiplication by
repeatedly doubling A, and
then adding the new value
to the result,
o But only IF the
corresponding bit of
B is a 1
o A is doubled by
shifting its bits to the
left.
The process works correctly for negative numbers, providing the rules for 2's
complement are obeyed.
o Consistent word length must be used
o And the sign bit is always the MSB.
Machine Multiplication
Binary multiplication can be done efficiently in a machine, using a sequence of
shift, test and add operations
The logic circuits are included in the arithmetic unit of all microprocessors and
personal computers
o The shifts are done by shift registers (NB. must have adequate length!)
o The bit tests can be done using AND gates;
o The additions are done using full-adders
Monostable Flip-Flop
Has only one stable state, Q = 0
o A clock pulse at its input, M,
flips it into its unstable
state, Q = 1, and then after a
known time interval it
reverts ("flops") back into the stable state Q = 0 again
Used to generate pulses or time delays of known duration
This is determined by connecting capacitors and resistors of the
appropriate value into a charging circuit which controls the following actions:
o While Q = 1, current flows from Vcc through R into C
o Voltage across C rises: ( )
o When it reaches some threshold value, Q gets reset to 0
o Upper limit on R, but not C
25
Haroon Chughtai Logic and Digital Systems 17/04/2013
1.6 Multiplexers
Multiplexers aka MUX
o Digital electronic devices
with several data inputs and
one data output
One input is selected
by the "select inputs"
Binary data on the
selected input is fed to
the output
26
Haroon Chughtai Logic and Digital Systems 17/04/2013
MUX/DMUX Pairs
A MUX/DMUX pair is
commonly used in
communication and
logic systems where
some complex piece of
processing circuitry
must be time-shared
between several signal
paths to economise the
design:
27
Haroon Chughtai Logic and Digital Systems 17/04/2013
28
Haroon Chughtai Logic and Digital Systems 17/04/2013
PALs
PALs are programmed like PROMs, using fuses
o One-time programmable
o Blow fuses to break unwanted connections
o Readout is fast
PAL Architecture
Before fuses blown, every input of every AND is
connected to every and ̅
EPLDs
EPLDs are (re-)programmed like EPROMs
o Erasable using UV light (typically 15 minutes' exposure needed)
o Programmed one bit at a time, but only a short time needed per bit
o Readout is slower than PALs
29
Haroon Chughtai Logic and Digital Systems 17/04/2013
RAM Devices
ROM, PROM and EPROM and PLDs are used to hold bit patterns or numbers
which are essentially constant
o In addition to the various types of ROM, computers need to store and
manipulate large arrays of numbers which can be altered at will.
For this purpose we use read/write memory devices in a Random-Access
Memory (RAM)
o RAM is similar to ROM in the way the arrays are organised and the row
and column addressing works
Types of RAM Devices
Two main types of RAM device:
o Static RAM (SRAM): Each bit cell is a small flip-flop made of 2 or 4
transistors
o Dynamic RAM (DRAM): Each bit cell uses a capacitor to store charge,
plus a buffer amplifier to maintain it:
30
Haroon Chughtai Logic and Digital Systems 17/04/2013
In both SRAM and DRAM, the data is maintained only while the power remains
on (ie data is "volatile" )
Static RAM is simple to operate, but more space consuming
Dynamic RAM can
achieve very high
density but the charge
on each tiny capacitor
quickly leaks away
o So DRAM
requires extra
circuitry to refresh the charge in each capacitor
o The process of reading out data also alters the charge
o Hence the need for a buffer amplifier and switching, via transistors
Flash Memory
Compromise between EPROM and RAM to obtain
"non-volatile RAM"
o Charges are stored on an extra, isolated
"floating gate" of a MOSFET so they do not
leak away so rapidly
Can use as RAM while power is on
Behaves as EPROM when power is off
Useful, was expensive but increasingly cheaper
now
31
Haroon Chughtai Logic and Digital Systems 17/04/2013
7 Segment Displays
LCD (liquid crystal display) or LED (light-
emitting diode) devices can display digits made
of up to 7 segments or lines
The decimal character set '0' - '9' needs 4 bits
o So decode 4 bits into 7 control signals
using a BIN/7SEG decoder
A specialised kind of
demultiplexer
The 7 segment decoder is just about the largest
circuit that would be economic to implement
using gates
o Other implementation methods include
ROM, PLD, etc…
32
Haroon Chughtai Logic and Digital Systems 17/04/2013
The Challenge
Given a trigger pulse corresponding to each heartbeat, generate the
instantaneous HR in beats per minute.
o You will need a clock input signal at e.g. 100Hz to give you a reference
(you can assume it is available);
o You will need a circuit, together with the reference signal, to work out
the time interval between two consecutive heart beats;
o You will need a circuit to convert the time interval to an instant heart
rate and store it for display.
A standard way to measure time intervals:
o Feed a REF clock signal (of constant, known frequency, here 100 Hz)
into a counter
o Allow it to count up from zero for the length of the unknown interval
Then the final count value will be
Hence the sequence of operations for the HR meter is:
1. Reset the counter to zero.
2. At first trigger pulse, begin counting the REF clock transitions
3. At next trigger pulse:
a. Stop counting the REF clock
b. Save the final value of the counter, (INTV), in a data register.
c. Reset the counter to zero, and allow it to start counting
immediately.
4. Convert the stored value of INTV to an instantaneous rate, IHR
a. We could use a ROM or EPROM as a reciprocal look-up table
5. Display the value of IHR
6. Repeat from step 3
Circuit Design
The proposed design is:
33
Haroon Chughtai Logic and Digital Systems 17/04/2013
Timing Diagram
System Accuracy
A typical medical instrumentation design requirement:
o "Given a trigger pulse corresponding to each heartbeat, display the
instantaneous heart rate (HR) in beats per minute
o This must be accurate to within 3 beats/min over the range 50-125
beats/min".
To display the instantaneous , we will need to measure the time interval
between successive trigger pulses and then find the reciprocal ( ).
o Working range of heart rates,
o Working range of intervals,
o To preserve an accuracy of 3 bpm over the whole range, we consider
the worst case
Where the , ie.
When interval t= 0.48 sec, we have to distinguish between a rate of 125 and 122
bpm
o ie. between an interval of 0.480 and one of 0.491 seconds
o We can do this if we measure each interval with a resolution of 0.01
seconds,
i.e. to the nearest hundredth of a second.
At the other end of the working range, where the HR = 50, we will be able to
distinguish between an interval of 1.20 and 1.21 seconds, (HR = 49.6 bpm)
o So we will easily satisfy the accuracy specification.
Because the REF clock input is 100Hz, the counter will contain 48 at the end of
an interval of 0.48 sec, and 120 at the end of an interval of 1.2 sec, etc.
o By sending this value to the address lines of the EPROM, we can simply
look up the corresponding heart
rate value as a binary number
from 125 down to 50
o We must program these values
into the EPROM at the correct
locations
34
Haroon Chughtai Logic and Digital Systems 17/04/2013
Hexadecimal Notation
Hexadecimal is more compact notation
o Long binary numbers are tedious and error-prone to write out
o Based on groups of 4 bits (giving 16 possible patterns for each group)
Divide binary into groups of 4 bits, starting with the LSB and working to the left:
o group as
For each group of 4 bits write the hexadecimal value
Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hex 0 1 2 3 4 5 6 7 8 9 A B C D E F
digit
So
o Also written as
Octal Notation
Octal Notation (not used much nowadays):
o Takes the bits in groups of 3 (each group has 8 possible patterns)
o The corresponding octal digits are 0 1 2 3 4 5 6 7
E.g. if (as before),
o Group as:
o So in octal,
ASCII
When word processing we type alphabetic and numeric characters into the
computer and arrange them.
o Inside the computer the characters are treated simply as binary numbers.
o These are indistinguishable from the binary numbers used to perform
calculations
To represent alphabetic / numeric characters in binary, there is a standardised
code: ASCII
o American Standard Code for Information Interchange
In ASCII, every printable character is assigned a unique 8-bit binary
number (a byte) whose value is as shown in the ASCII table.
o E.g. the character 's' has value 0 1 1 1 0 0 1 1 = 115 or 73H
10
35
Haroon Chughtai Logic and Digital Systems 17/04/2013
Structure of a Computer
All computers consist of basic functional
blocks that include a central processing
unit (CPU), memory and input/output
ports
o These are connected together by
three internal buses: the data bus,
the address bus and the control
bus
Overview of Operation
Instructions and data are stored in memory in specific locations determined by
the program
o Each location has a unique address
o Instructions obtained by the CPU placing an address on the address bus
o Instructions transferred via data bus as they are requested
o CPU executes the instructions sequentially
The instructions modify data stored in memory or obtained
through input devices
o Processed data may be stored back in memory or sent to an output device
via the data bus
o Signals on the control bus are generated by the CPU to coordinate all
these operations
Microprocessor/CPU Structure
The microprocessor is a digital IC that can be programmed
to perform various operations on data
o It is the CPU of a computer
o Can do arithmetic and logic operations, move data and
make decisions based on certain instructions
Consists of several units each designed for a specific job
o The specific units, their design and organisation is
called the architecture
o The architecture determines the instruction set and
process for executing those instructions
Four basic units to all microprocessors are the arithmetic
logic unit (ALU), the instruction decoder/register, the
register array and the control unit as well as buses
36
Haroon Chughtai Logic and Digital Systems 17/04/2013
37
Haroon Chughtai Logic and Digital Systems 17/04/2013
38
Haroon Chughtai Logic and Digital Systems 17/04/2013
Program Actions
To run the program, we set the
Program Counter register to 43H
so that the first instruction will be
fetched.
It will automatically be
incremented after each instruction.
So:
We did not place an instruction in location 46H so the action of the processor
when it reaches this location will be unpredictable.
o We must therefore place a STOP instruction in location 46H.
The opcode for STOP might be FFH, and no operand is needed.
So the instruction would be FF00H.
Having done that, when we set the Program Counter to 43H to start the program,
this time it will run correctly and stop with the final value 0035H stored in
location 51H, which is the one we reserved for S.
o The original values of Q and R will remain unchanged.
Programming
Machine Code
This sequence of instructions we built up in the RAM memory is called a
machine code program
o It is just a series of binary numbers, indistinguishable from data
Numbers which are instructions have a very specific meaning to the
processor
o The bits of the opcode act as inputs to the control gates in the
processor.
There are many types of processor, by different manufacturers, all wired up in
different ways,
o So the opcodes of the machine code instructions are specific to a given
family of processors.
Machine code allows the programmer to have complete control of every binary
number inside the machine at any instant.
o But Machine code programming is difficult, slow and error-prone:
A typical processor has 60-200 different opcodes
A program could contain 1000 to 100,000 instructions
o For everyday use, we have a much more convenient method of producing
the machine code program;
This is called Assembly Code (or Assembly Language)
programming
39
Haroon Chughtai Logic and Digital Systems 17/04/2013
Assembly Code
Assembly code is set of mnemonics to represent the opcodes
o Plus some rules for specifying the operands
The assembler is a pre-written machine code program that translates your
own assembly code into machine code, and checks for errors.
o Supplied by the manufacturer
o Specific to a microprocessor architecture
Example: S = Q + R had to be implemented as:
Pseudocode Assembly
1. Instr 1: Fetch the value of Q into 1. LDA Q ("Load the accumulator
the accumulator from its with the value Q")
specified RAM memory 2. ADD R ("Add the value R to the
location; accumulator")
2. Instr 2: Add the value of R from 3. STA S ("Store the accumulator
its specified RAM location to the contents in S")
contents of the accumulator; 4. HLT
3. Instr 3: Store the result in
another RAM location we
reserved for S;
4. Halt.
o Notice that these instructions have the same general form as the binary
machine code instructions, ie. Opcode | Operand.
Equate Directives
The equate directive EQU can be used to assign constants
We can specify these by placing Equate Directives (EQU) at the start of our
program:
o Q EQU A7H
o R EQU A8H
o S EQU 51H
Now whenever the assembler sees the symbol Q as an operand, it can put A7
hexadecimal into the operand part of the machine code instruction.
o Similarly for R and S
Origin Directive
The assembler needs to be told
that we want our first machine
code instruction to be at a
specific memory location 43H
(recall the memory map)
We do this by placing an Origin
Directive (ORG) before the first
instruction:
40
Haroon Chughtai Logic and Digital Systems 17/04/2013
Loading an Running
The assembler will translate the program into the machine code instructions, as
a binary image of the desired memory map
o In small systems, the Assembler will automatically load the machine code
instructions into memory for you
Pre-set the data values for Q and R
Then set PC to the desired start address (here 43H) to run the
program immediately.
The result Q+R will be placed in S.
o In larger systems the Assembler will store the machine code program on
disk, for you to load and run it when required.
Programming Pathways
There are various ways
of producing the
machine code program
o Machine code is
the only form the
processor can
directly act on
Programs written in
high-level languages
are even easier to
write, read and
understand than
assembly language
programs.
Advantages of Assembly
Assembly offers benefits to speed, efficiency and program size
o These are important when programming a MPU as a component, or in a
single-board computer
These have only very small on-board memory, and often a slower
clock rate
High-level languages tend to produce large machine code programs even for
simple applications.
o This is because application program gets translated into binary object
code, which is then linked with other object code modules from a library,
to form the final executable binary program.
o S = Q+R could generate a program needing 5000 to 10,000 memory
locations.
o These large programs inevitably take longer to run than the equivalent
Assembly Code program.
41
Haroon Chughtai Logic and Digital Systems 17/04/2013
Addressing Modes
So far, we have represented operands by the memory address of the data which
is to be operated on (e.g. A7H for Q)
o Most processors offer several different ways of specifying operands.
o These are called the addressing modes.
Register Addressing
The relevant register is specified using a letter.
Example: CLR A (clear the A accumulator to zeros), INC B (increment the B
accumulator by 1).
o Often written as, e.g., CLRA
Immediate Addressing, #
The actual value of the operand, not its address, is supplied as part of the
instruction.
Example: ADDA #7EH means add the value 7EH to the 8-bit A Accumulator.
o [Compare this with: ADDA 7EH which means: add the contents of location
7EH to Accumulator A].
o Immediate mode is used for operations involving constants.
Extended Addressing
The full two-byte address of the data is supplied as the operand part of the
instruction.
Usually we simply specify the data by a label (Example: LDA Q) and let the
assembler decide which addressing mode to use.
6809 Instructions
Operation codes are divided into four categories:
o Data Transfer
o Arithmetic/Logical
o Stack Operations
o Jumps and Branching
Data Transfer
All data transfers are done via the registers.
These instructions may affect the N,Z, and V flags in the Condition Codes (CC)
Register.
o Store register in memory: STA, STB…
o Load memory into register: LDA, LDB…
42
Haroon Chughtai Logic and Digital Systems 17/04/2013
Rotate accum or memory location one place to right or left, via carry: RORA,
RORB, ROR, and ROLA,ROLB, ROL
o Preferred to shift in some cases as no bits lost
43
Haroon Chughtai Logic and Digital Systems 17/04/2013
The most recent entry can be retrieved from the stack using a Pull
instruction (PULS or PULU):
o Example: PULU A,B,X retrieves the registers from the above Push
The programmer has to keep track of what is currently at the top of the stack.
o But the Stack Pointer register automatically decrements itself by the
correct amount during PUSH operations and increments itself correctly
during PULL operations.
Jumps and Branches
Jump and branch instructions alter the value in the PC to change the program
flow.
Unconditional Jumps
Simple Jump : JMP label
o The assembler will decide which addressing mode to use
Relative Branch: BRA signed 8-bit offset value
o The operand indicates the amount by which the PC is to be altered.
o Example: BRA –8H causes a backward jump to instruction 8 locations
earlier in the program.
o We can also use labels, and allow the assembler to calculate the offset
value for the branch instruction.
Conditional Branches
A relative branch occurs if the stated condition of the flag bits in the CC register
is fulfilled.
o This forms the decision making process in computer programs - the real
basis of the power and flexibility of computers.
Generally used following arithmetic, logical or comparison instructions.
Examples:
o BEQ branch if equal (Z=1) or if a result was zero
o BNE branch if not equal (Z=0)
o BMI branch if minus (N=1) ie. if result was negative
o BPL branch if plus (N=0) ie. if result was positive or zero
o BCS branch if Carry flag is set (C=1)
o BVS branch if Overflow occurred (V=1)
44
Haroon Chughtai Logic and Digital Systems 17/04/2013
Subroutines
A subroutine is a section of code which can be used or 'called' several times by
different parts of the main program
o Normally requires some input data (via registers or memory locations)
o Leaves its results in registers or memory locations
We might want to multiply Accumulator A by ten at various points in a main
program.
o We could write out the sequence every time (in-line coding).
o However, this is wasteful
of memory.
o More economical to
code the operation as a
small subroutine, and
give it a suitable name
Eg. AX10, and a
Return instruction:
The AX10 subroutine can now be called from anywhere in
the main program
o Using a special JSR (Jump-To-Subroutine)
instruction:
Each time we jump to the subroutine, we have diverted
away from the main flow of the program to the place where
AX10 is residing in memory.
o The RTS instruction at the end of the subroutine
provides the means of finding our way back to the
point where we left the main program
How JSR and RTS Work
When the JSR AX10 is encountered, (eg. at Instr 46) the CPU
does a PUSH to store the contents of the PC on the
System Stack.
o This is the value currently pointing to the next
instruction, ie. Instr 47
It then sets the PC to point to the address of the
instruction labelled AX10
o I.e. the start of the subroutine, and lets the
subroutine run.
o Called "passing control to the subroutine"
At the end of the subroutine, the RTS instruction causes the CPU to PULL the
topmost value off the System Stack and back into the PC
o This will be the value pointing to the next instruction, ie. Instr 47
o This restores the state that the PC was in just after the call to AX10.
The CPU will therefore get its next instruction from the address of Instr 47.
o So control has passed back correctly to the point where we diverted
from the main program
Essentially upon calling a subroutine, the next PC value is stored in the
stack until RTS is called upon which normal flow resumes
45
Haroon Chughtai Logic and Digital Systems 17/04/2013
Considerations
In general, the advantages outweigh the disadvantages, so subroutines are
widely used in professional coding
Advantages
Facilitates making changes
Reduces the risk of errors (less code to write)
Saves memory space
Simplifies the program layout and documentation
Disadvantages
Slower to execute than in-line coding, due to the "overhead" associated with
the stack operations
More difficult to find intermittent errors if they occur inside a subroutine
46
Haroon Chughtai Logic and Digital Systems 17/04/2013
47
Haroon Chughtai Logic and Digital Systems 17/04/2013
Interrupt-Driven I/O
Ideally, the processor should be able to do some other, background task and deal
with Port A input data as it becomes available.
o Such a facility is provided by a different type of subroutine call, known as
an interrupt.
When an interrupt is received, the program:
o Diverts away from the mainstream,
o Jumps to a designated subroutine called an Interrupt Service
Subroutine (ISR) to deal with the cause of the interrupt
o Then returns to the main program where it left off.
Interrupt Mechanism
Interrupts are implemented using
extra hardware.
o When the PIA has new data
ready, it asserts logic 1 on a
special Interrupt Request
(IRQ) line that goes directly into the processor.
When logic 1 is detected on the IRQ input line, the processor knows that it has to:
1. Complete the current instruction;
2. Save the Program Counter on the System Stack;
3. Save the other registers on the System Stack;
4. Find out the start address of the Interrupt Service Routine;
5. Load this address into the Program Counter.
Interrupt Service Subroutine
Step 5 above passes control to the Interrupt Service Subroutine,
o This may be a portion of code rather like GETINP
o (ie. it deals with the cause of the interrupt)
The ISR looks like a normal subroutine except that instead of ending with an RTS
instruction it ends with a Return from Interrupt (RTI) instruction.
o This RTI tells the processor to reverse the stacking operations done in
Steps 2 and 3 above, so that all the registers get restored to the state they
were in just before the interrupt.
o The main program then resumes from where it left off.
48
Haroon Chughtai Logic and Digital Systems 17/04/2013
Interrupt Vectors
The main difference between an Interrupt Service Routine and a normal
subroutine is that the processor gets the start address of the subroutine, not
from the operand of a JSR instruction but from a pointer location which is at a
fixed address in memory.
o Such a pointer to an ISR is called an interrupt vector.
Most processors have multiple IRQ input lines; each has its own associated
vector, and is assigned a priority level and a distinct name.
o The vectors are usually grouped together at the very
top of memory.
o Their addresses are pre-determined by hard-wiring
in the processor.
o Each vector occupies two bytes, since it has to hold a
16-bit address, e.g. in the Motorola 6809:
o Reset has the highest priority, then NMI (non-maskable interrupt), then
SWI (Software interrupt), etc.
Direct Memory Access (DMA)
Normal interrupt-driven input/output is powerful and flexible
o Allows a number of I/O devices to operate each at its own preferred
speed.
But there is a limitation as all data is being passed through the CPU
accumulators;
o Only one or two bytes at a time can be transferred per machine cycle,
inefficient for transferring large blocks of data as fast as possible to/from
memory.
Direct Memory Access (DMA) solves this by allowing an I/O device to take
control of the bus for a short period.
o A burst of data can be transferred at maximum speed.
o The CPU is taken off the bus during DMA activity.
o Transfer rates of 50-90 million bytes/second can be achieved during
the burst.
The main CPU activity is not slowed down very much if bursts are kept short.
o The DMA controller generates an interrupt to tell the CPU when a
transfer has finished.
o More advanced DMA controllers insert their activity during parts of the
machine cycle when the bus is idle.
Then no perceptible slowing of the CPU or program speed.
49
Haroon Chughtai Logic and Digital Systems 17/04/2013
Serial I/O
All of the I/O devices described so far perform parallel data transfer
o All the bits of a binary value are transferred simultaneously.
Parallel I/O devices require as many interface circuits and transmission paths as
there are bits in the data.
o This can become expensive (multi-way cables, connectors, etc).
An alternative is to use a serial protocol, where the bits are sent in sequence
rather than simultaneously.
o Less peripheral data lines to the outside world are required.
o Thus only one data path is needed.
The transfer did take longer in old designs (RS232), but the speed has improved
immensely with new technologies such as Universal Serial Bus(USB)
RS-232 Serial Transfer
An previous widely used protocol is called RS-232
o The data are 8-bit values, plus bits for START, STOP and PARITY , so
each character involves 11 bits
o Error check, e.g. Parity = the sum of all data bits, ignoring carry-out
Data are read out in sequence, LSB first, to the Transmit line and hence to the
peripheral device (e.g. printer)
In RS-232, a bit value of 1 is indicated by -12 volts on the data line, and a 0 is
indicated by +12 volts.
The time duration T of each bit is pre-set, so that both the ACIA and the
peripheral device can work out when each bit ends and the next bit starts.
o Expressed as 1/T,
The number of bits per second, also called the Baud Rate.
o Typically 9600,19200, 28K, 56K
Example:
o Transmitting the
character 'A' = 41H =
0100 0001, using even
parity ( ):
USB
USB stands for Universal
Serial Bus
o Byte-wise serial
protocol, with error checking
o Much more complex than RS-232
o Much faster than RS-232
USB 2.0 = 480 Mbits/sec, cf. RS-232’s maximum of 112.5 kbits/sec
Each USB device can identify itself to the host computer and obey complex
commands
o Plug-and-play capability requires great complexity inside the USB device
o So, special integrated circuits are made to implement this
50
Haroon Chughtai Logic and Digital Systems 17/04/2013
51
Haroon Chughtai Logic and Digital Systems 17/04/2013
Quantisation Error
There will always be a difference between the actual (analogue) quantity and the
digital value assigned to it
o This is termed quantisation error
o Can be reduced by increasing the number of bits.
E.g. Binary represent 10.48 and 10.52 from analogue values
o 10.50 cannot be represented
Pentium 386
From the programmer's point of view
the Pentium family has the same
register set as the old 80386.
o Allows old programs to be
used with the new machines
Some registers are reserved for special
purposes
Memory access is done via
combinations of Segment Registers, to
generate 20-bit or 32-bit addresses
There are more than 300 different
Opcodes
o However, the format of the assembly code instructions is similar to those
of the Motorola 6809, ie. Opcode|Operand
The 386 and Pentium processors are able to run two or more tasks
concurrently
o Management of the stack is complicated, since the state of each task
must be saved and reclaimed many times.
The stack pointer and the base pointer are used together to
achieve this.
o To manage such a complex processor, plus all the other I/O resources,
interrupts, etc., clearly requires a lot of sophisticated programming
Not sensible to try to write every program from scratch in assembly code
o Instead, we use a set of commercial software which manages all the
hardware, and gives programmers convenient access to services
o This software is called the Operating System (OS).
52
Haroon Chughtai Logic and Digital Systems 17/04/2013
Overview
The best known Personal Computer OS is Windows.
o It was developed from a much simpler system called MS-DOS
("Microsoft's Disk Operating System") created for the first PCs
On other types of computers and workstations, an OS called UNIX is now the
industry standard.
o A version of UNIX is available for Personal Computers too (LINUX )
Tasks performed by the Operating System:
o Giving the user access to hardware functions
o Facilitating input and output of data
o Organising data and programs in filing systems
o Detecting and recovering from errors
o Sharing resources, programs and data between several users
o Organising communications between computers (networking)
o Accounting and billing for resource usage
Structure
The user accesses only via the OS shell
o In older OS, the shell prompts the user
for commands which are typed in from
the keys
o Modern OS use a point-and-click shell
interface
Processes
When the shell has determined what the user
wants, it creates a PROCESS,
o This represents this latest
application
o Remains in existence until the
application is ended.
The shell is constantly creating, managing
and destroying discrete processes.
The kernel provides CPU, memory and I/O services to these processes as they
ask for them.
The user's program does NOT usually deal directly with the hardware, but is
turned into a process, which sends all its service requests via the program
interface in the kernel.
o Advantage: user programs can be easily adapted ("ported") to run on new
hardware systems, provided that the software Program Interface is made
to appear the same.
o Hence a big saving in cost, since hardware keeps evolving
53
Haroon Chughtai Logic and Digital Systems 17/04/2013
Fate of Processes
After a process is created, it is placed in a queue.
Each process is in one of three states:
o Running: it has the use of the CPU
o Ready: it could use a CPU if one were
available
o Blocked: it is waiting for some event to
happen (e.g. an I/O transfer to finish)
before it can continue
OS Multitasking
The method of states and queues allows the OS to maintain a number of
processes (i.e. programs) running concurrently
o This is known as multitasking.
Many separate processes are created by the shell
o Each is allocated a priority level and a separate area of memory for its
code and data, so that they cannot interfere with one another except by
special permission
o Each process is given attention in turn by the OS kernel
Additionally, the kernel must respond to other, "housekeeping" interrupts
such as the time-of-day clock or mouse movements
OS File Organisation
The OS manages disk files and organises them into a
hierarchical tree system for ease of access
o For each logical storage device (e.g. the C: drive), there
is a Root directory and a number of branches bearing
directories and subdirectories ("folders")
This file structure is implemented using logical links, rather
than by physically positioning the data on the disk
o The links are addresses placed in a lookup table
o Each data file on the disk itself is usually distributed
arbitrarily over the disk, to allow efficient use and re-
use of the available space
Disk File Structures
Some viruses work by destroying or
scrambling the information in the File
Allocation Table
o This makes all files inaccessible
o However, the actual file data in the
clusters is not destroyed
o Do the disk can be repaired if the
FAT can be re-built
Most systems keep a backup copy of the
FAT in a different place
o Some viruses find and destroy the
backup copy too
In UNIX, LINUX and later versions of
Windows, the FAT system is replaced by a more secure scheme ("inodes")
54