You are on page 1of 50

EE1A2: Microprocessor

Systems & Digital Logic

2011
Dr S. I. Woolley
Electronic, Electrical and Computer Engineering
EE1A2: Microprocessor Systems &
Digital Logic
CONTENTS
PART A: DIGITAL ELECTRONIC SYSTEM DESIGN................................................................. 4
A1. INTRODUCTION ............................................................................................................ 4
A2. NUMBER SYSTEMS ........................................................................................................ 4
A2.1 Decimal .............................................................................................................................................4
A2.2 Binary................................................................................................................................................4
A2.3 Hexadecimal ...................................................................................................................................4
A3. BINARY ARITHMETIC .................................................................................................... 5
A3.1 Addition ............................................................................................................................................5
A3.2 Subtraction .......................................................................................................................................7
A3.3 Comparison ......................................................................................................................................8
A3.4 Adder/Subtraction Circuit ............................................................................................................9
A4. ARITHMETIC LOGIC UNITS ............................................................................................ 9
A4.1 Building a Calculator .....................................................................................................................9
A4.2 Registers ........................................................................................................................................ 11
A4.3 Tri-State I/O ports and Busses.................................................................................................. 13
A5. MICROPROCESSORS AND MICROCONTROLLERS ...................................................... 15
A5.1 Block Diagram .............................................................................................................................. 15
A5.2 Registers ........................................................................................................................................ 15
A5.3 Programming ................................................................................................................................ 16
A6. INTRODUCTION TO THE PIC MICROCONTROLLER .................................................... 17
A6.1 Registers ........................................................................................................................................ 17
A6.2 Literal Values................................................................................................................................ 17
A6.3 Data Destination .......................................................................................................................... 17
A6.4 Other Features ............................................................................................................................. 17
PART B. MICROPROCESSORS AND ASSEMBLER PROGRAMMING ................................... 18
B1. INTRODUCTORY NOTES .............................................................................................. 18
B2. AN INTRODUCTION TO MICROPROCESSORS AND PIC PROGRAMMING ................ 18
B2.1 Introduction to Microprocessors ................................................................................................. 18
B2.2 Microprocessor Programming .................................................................................................... 18
B2.3 A Simple PIC Program ................................................................................................................ 19
B2.4 Representing numbers in PIC assembler .................................................................................. 19
B2.5 Observations about PIC assembler format ............................................................................. 19

1
B2.4 Introductory Exercises.................................................................................................................. 20
B3. ASSEMBLING TEST.ASM INTO OBJECT CODE IN MPLAB ............................................ 21
B4. MICROCONTROLLERS AND EMBEDDED SYSTEMS ...................................................... 23
B4.1 Microcontrollers and Embedded Processors ........................................................................... 23
B4.2 Watchdog Timers ......................................................................................................................... 23
B4.3 Embedded Controllers/Embedded Systems ........................................................................... 24
B4.4 Applications................................................................................................................................... 24
B5. MICROCONTROLLER ARCHITECTURES AND INSTRUCTION SETS ............................... 24
B5.1 Von-Neuman Architecture ........................................................................................................... 24
B5.2 Harvard Architecture ................................................................................................................... 24
B5.3 Complex Instruction Set Computer (CISC) ............................................................................... 24
B5.4 Reduced Instruction Set Computer (RISC) ................................................................................ 24
B6. AN INTRODUCTION TO THE MICROCHIP PIC16F84 ................................................... 25
B6.1 The PIC16F84 Microcontroller ................................................................................................... 25
B6.2 PIC16F84 Memory ...................................................................................................................... 25
B6.3 Program Memory ......................................................................................................................... 25
B6.4 Data Memory: Registers ............................................................................................................. 26
B6.5 Architecture of the PIC Microcontroller .................................................................................... 27
B7. PIC16F84 PROGRAMMING ......................................................................................... 28
B7.1 Flowcharts ...................................................................................................................................... 28
B7.2 Program Documentation ............................................................................................................. 29
B7.3 Subroutines .................................................................................................................................... 29
B7.4 A Software Time Delay .............................................................................................................. 30
B7.4.1 Why the 3? ............................................................................................................................ 30
B7.4.2 Converting clock cycles into time ........................................................................................ 30
B7.5 Debouncing Switch and Key Inputs ........................................................................................... 31
B8. ACCESSING LOOKUP/DATA TABLES........................................................................... 32
B9. INTERRUPTS................................................................................................................. 33
B9.1 The PIC INTCON Register........................................................................................................... 33
B9.2 Using Interrupts ............................................................................................................................. 34
B9.3 Context Saving ............................................................................................................................. 34
B9.4 Interrupt Code Segment Example ............................................................................................ 34
B10. PIC ADDRESSING MODES .......................................................................................... 36
B10.1 Immediate Addressing .............................................................................................................. 36
B10.2 Direct Addressing ...................................................................................................................... 36
B10.3 Relative Addressing .................................................................................................................. 36
B10.4 Indirect Addressing ................................................................................................................... 36
B11. COMPARING VALUES ............................................................................................... 37
B11.1 Using the STATUS Register ...................................................................................................... 37
B12. BIT MANIPULATION .................................................................................................. 38
B12.1 Changing Bits to 1 ..................................................................................................................... 38
B12.2 Changing Bits to 0 ..................................................................................................................... 38
B12.3 Inverting Bits ............................................................................................................................... 38
B12.4 Testing for Equal Values .......................................................................................................... 38

2
B12.5 Testing for Zero Values ............................................................................................................ 38
B13. ASSEMBLER DIRECTIVES ............................................................................................ 39
B14. PIC OPERATORS AND DIRECTIVES ........................................................................... 41
B15. THE PIC WATCHDOG TIMER (WDT) ........................................................................... 43
B16. PIC RESETS AND RESET VECTORS ............................................................................. 43
B17. THE PIC HARDWARE TIMER (TMR0) .......................................................................... 44
B18. NOTES ON SOME OTHER PIC MICROCONTROLLERS ................................................ 44
B19. SUMMARY ................................................................................................................. 45
APPENDICES: ..................................................................................................................... 46
APPENDIX A. THE PIC16F84 INCLUDE FILE ....................................................................... 46
APPENDIX B. THE PIC16F84 INCLUDE FILE........................................................................ 46
APPENDIX C. SELECTED PAGES FROM THE MICROCHIP PIC16F84A DATASHEET ........... 46
APPENDIX A. THE PIC16F84 INCLUDE FILE ....................................................................... 47
APPENDIX B. THE PIC16F84 INSTRUCTION SET ................................................................ 49
APPENDIX C. SELECTED PAGES FROM THE MICROCHIP PIC16F84A DATASHEET ........... 50

3
PART A: DIGITAL ELECTRONIC SYSTEM DESIGN
(Part A was originally written by Dr Tim Collins)

A1. INTRODUCTION

During the first semester of this year, course EE1A1 provided an introduction to digital electronics. Many
digital devices were introduced from simple combinational logic and arithmetic circuits to sequential logic
circuits and flip-flops. In modern electronics products, it is increasingly rare that these „discrete‟ integrated
circuits are used. Instead, programmable devices containing many gates, flip-flops etc. are used to
perform complicated tasks with a minimal amount of hardware. Programmable gate arrays,
microprocessors and microcontrollers are all examples of such devices.
Course EE1A2 consists of two parts. This first part, part A, begins where EE1A1 left off, extending the
ideas behind some of the primitive digital electronics elements already introduced. Dedicated arithmetic
and logic circuits will be replaced by general-purpose arithmetic and logic units (ALUs); banks of flip-flops
shall be used as digital storage elements and, eventually, a complete microcontroller can be conceived.
The basic elements of a microcontroller will be discussed in readiness for the second part, part B, of this
course that deals with the business of actually programming these devices to do something useful. To begin
with, the fundamentals of binary arithmetic will be reviewed.

A2. NUMBER SYSTEMS


A2.1 Decimal
Before discussing electronic arithmetic, it is worth reviewing a few points about number systems. Having
evolved with ten fingers it was almost inevitable that Homo sapiens would adopt a base-10 number
system, or decimal, as a standard way of counting. Most of us are so used to this system that we do not
even have to think of the digits in a number in terms of hundreds, tens and ones. For the sake of
consistency, however, an example of a base-10 number might be 123; i.e. one hundred (1102), two tens
(2101) and three units (3100). All numbers in other bases express a quantity in the same kind of way.
The only difference is that the 10s are replaced by the base of the number system.

A2.2 Binary
A digital signal has only two possible states – on and off. As such it was equally inevitable that digital
computers would adopt a base-2, or binary, number system. Instead of each digit representing a power
of 10, each one now represents a power of two. Also, instead of using the ten digits from 0-9, binary
systems only use two digits, 0 and 1. As an example, consider the binary number 1111011. This can be
converted to the more familiar decimal form as follows:

1111011  1  2 6  1  2 5  1  2 4  1  2 3  0  2 2  1  21  1  2 0
 1  64  1  32  1  16  1  8  0  4  1  2  1  1
 123
By convention, each digit in a binary number is known as a bit. An eight bit binary number is known as a
byte. Longer binary numbers composed of more than eight bits are known as words.

A2.3 Hexadecimal
Binary to decimal conversion is a laborious process, so much so that many software engineers have
abandoned the base-10 number system altogether. A more convenient system is base-16, or hexadecimal

4
(hex for short). 16 digits are now required, so as well as 0-9, the letters A-F are also used to represent the
digits ten to fifteen. For example, consider the hexadecimal number, 7B:

7 B  7 161  1116 0  123


More importantly, the conversion from hexadecimal to binary and back again is much simpler than
decimal to binary conversion. The 4-bit binary representation of the number 7 is 0111, and of B is 1011.
The 8-bit representation of 7B is just 0111 followed by 1011, 01111011 as shown in the previous section.
As long as you are familiar with the binary representations of the digits 0-9 and A-F, hex to binary and
binary to hex conversion for even quite large numbers is relatively straightforward.

A3. BINARY ARITHMETIC


A3.1 Addition
Addition is the most elementary of arithmetic operations. It was covered in the previous course and will
only be summarized now. It is worth revising as it forms the basis of the other elementary operations:
subtraction, multiplication and division.
To add even the smallest of numbers together, a digital circuit must use a form of long-addition. In base-
10 addition, this means that the units, tens, hundreds etc. are added-up individually and if the result is ten
or more an extra one is carried to the next highest digit. Binary addition works in exactly the same way
except that the columns are now units, twos, fours, eights etc. Figure 1 shows how long addition is used to
add 13 and 9 using base-10 and base-2 arithmetic.

13 1101
+ 9 + 1001
10 Carried digits 10010
22 Result 10110
Base-10 Base-2

Figure 1. Base-10 and base-2 addition

In the base-10 case, the units are added first. 3+9 = 12 which is greater than 9 so a one is carried to the
tens column. In the base-2 case, whenever two or more ones are to be added, a carry bit is also
generated in the next column.
Looking at each individual column in the binary addition, the operation required has three inputs (the two
numbers to sum and the carry bit from the previous column) and two outputs (the sum and the carry bit to
the next column). To construct a full-adder circuit, the first stage is to write the truth table required.

5
Inputs Outputs
A B CIN SUM 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

Table 1. The truth table of a full-adder.

Next, using Boolean algebraic techniques or Karnaugh maps, equations for the two outputs can be
developed and simplified to:

SUM  A  B  C IN
COUT  C IN  A  B   AB

At this stage the combinational logic gates required can be drawn and a single-bit full-adder circuit
constructed. This much was covered during EE1A1 in some detail.
A single-bit adder is of little use. What we would really like to do is add together multiple-bit numbers
(bytes). The full-adder is designed specifically in order to simplify the construction of such parallel adder
circuits as shown in figure 2.

B2 A2 B1 A1 B0 A0
CIN = 0
B A CIN B A CIN B A CIN
Full Adder Full Adder Full Adder
COUT SUM COUT SUM COUT SUM

Q2 Q1 Q0

Figure 2. A three bit parallel adder circuit built using three single-bit full-adders.

In operation, the circuit in figure 2 performs exactly the kind of long addition illustrated in figure 1. At
each stage, the two inputs and the carry bit from the previous stage are added. The sum is generated as
well as a carry bit to be carried to the next highest significance stage.
The „ripple‟ carry operation of the parallel adder presents a potential problem. Each full-adder circuit will
take a non-zero time delay to react to changes in the inputs. As the output of each stage depends on the
carry bit generated, in part, by all previous stages, the time taken for the highest significance stage will
be equal to the sum of the reaction times (or propagation delays) of all the other stages. Typical

6
propagation delays for a full adder are of the order of 30 ns. This may not seem much, but when many
delays add together, the sum may be significant. For example, a 16-bit adder circuit would require
1630 ns (480 ns) to respond to a change in input. This may still not sound like much, but for a circuit
hoping to perform millions of sums per second, it is a very long time.
In order to suppress the accumulation of propagation delays, the serial operation of the adder circuit is
often eliminated using a carry-look-ahead circuit. The idea behind the operation of this circuit can be
described by considering the adder in figure 2. The carry input to the Q0 stage is zero and the carry input
to the Q1 stage is a simple piece of combinational logic based on A1 and B1. The carry input to the Q2
stage, however, can be expressed as:

C IN 2  COUT 1
 C IN 1  A1  B1   A1 B1

But,

C IN 1  COUT 0
 C IN 0  A0  B0   A0 B0

 C IN 2  C IN 0  A0  B0   A0 B0  A1  B1   A1 B1

In other words, the carry input to the Q1 stage can be calculated using a combinational logic circuit that
takes CIN0 and all the previous A and B digits as inputs. Similar equations can be derived for full-adders
of more significant bits. The equations become more complicated, but can still be expressed as a single
Boolean algebra equation. The principle of a carry-look-ahead circuit is to calculate these equations
directly instead of relying on the ripple carry effect of the parallel adder. This requires a significant extra
block of combinational logic, but does eliminate the accumulation of propagation delays suffered by the
simpler circuit.

A3.2 Subtraction
In order to subtract one number from another, the same adder circuits can be used again. For example, to
calculate five minus three the inputs to the adder would be five and negative three. Negative binary
numbers are represented using the two’s complement system. This means that a negative number, say –3
for example, is represented by subtracting 3 from a number one larger than the maximum number that
can be represented by the digits available (i.e. 2n in an n bit system).
As an example, the subtraction, 5 minus 3, can be performed in two stages. The first is to calculate the
two‟s complement representation of –3. Using a 4-bit system, this will be: 2 n  3  16  3  13 So the
required sum is 5 (0101) plus 13 (1101):

0101
+ 1101
Carried digits 11010
Result 0010
Base-2

Figure 3. Binary subtraction

7
The correct answer of 2 is generated. An extra carry bit is also produced indicating that the answer has
overflowed the four bits available. This indicates that the sum of 5 and 13 is actually 18, i.e. greater than
2n-1. As the answer is truncated to four bits, however, the result that appears is 18 mod 16 = 18-16 = 2.
A quick way of obtaining the negative of a binary number is to invert all of the digits in the number and
then add one to the result. Taking –3, for example, the number 3 is equivalent to binary 0011. Inverting
each bit gives 1100 and adding one gives 1101; decimal 13 as above. So to convert the parallel adder
into a parallel subtractor, the argument to be subtracted must be inverted (complemented) and an extra
one added. The extra addition can be simply accomplished by setting the carry-in signal as shown in
figure 4.

B2 A2 B1 A1 B0 A0
CIN = 1
B A CIN B A CIN B A CIN
Full Adder Full Adder Full Adder
COUT SUM COUT SUM COUT SUM

Q2 Q1 Q0

Figure 4. A three-bit subtraction using a parallel adder.

A3.3 Comparison
As the result of 5-3 was positive, a carry-out signal was generated in figure 3. If, however, the subtraction
was 1-3, the result would have been –2 (1110) and the carry-out bit would be zero. In other words, COUT
= 1 indicates that A  B and COUT = 0 indicates that A < B. In many cases, a comparison between two
binary numbers to determine which is largest is required. This can be accomplished using the subtraction
circuit, ignoring the result and only paying attention to the carry-out bit (also known as the carry flag).
Another flag often produced by adder circuits is a zero flag. This is a single bit again that is only set when
the result of an operation is exactly zero. Using the subtraction circuit again, the zero flag and carry flag
can be combined together to determine the inequalities A > B and A  B. Alternatively, it can be used on
its own as it will only be set when A  B.

8
A3.4 Adder/Subtraction Circuit
With a minor modification, the parallel adder can be converted into a circuit that is capable of addition
or subtraction, depending on the state of an extra control input.

B2 A2 B1 A1 B0 A0

ADD/SUB

B A CIN B A CIN B A CIN


Full Adder Full Adder Full Adder
COUT SUM COUT SUM COUT SUM

Q2 Q1 Q0

Figure 5. An adder/subtraction circuit

When the control input is low (the „add‟ state), the carry input is low and the output of each XOR gate will
be the same as the corresponding B input (since X  0  X ). In other words, all the inputs to the adders
are the same as they are in figure 2; the result is addition. When the control input is high, however, the
carry input is high and the output of each XOR gate is the complement of the corresponding B input
( X 1  X ). Now the inputs to the adders are the same as they are in figure 4; the circuit performs
subtraction instead.

A4. ARITHMETIC LOGIC UNITS


A4.1 Building a Calculator
The adder/subtraction circuit of figure 5 could be used as the basis of a very primitive pocket calculator.
It allows the user to input two operands, A and B as well as specifying the arithmetic operation required
(addition or subtraction). With some extra combinational logic, the capabilities of the circuit could
conceivably be extended to perform other arithmetic or logic functions (e.g. ANDing or ORing each of the
input bits together). This kind of general-purpose circuit forms an important part of all microprocessors and
is known as an arithmetic logic unit, or ALU.
An example of a simple ALU integrated onto a single chip is the 74F382. This is a 4-bit device capable of
performing a choice of three arithmetic and three logical operations on the two input numbers. The inputs
and outputs of the device are illustrated in figure 6.

9
B3 B2 B1 B0 A3 A2 A1 A0
CIN
S2
S1 74F382
S0
F3 F2 F1 F0 COUT

Figure 6. The 74F382 4-bit arithmetic logic unit.

The two operands are represented by the bits A0 to A3 and B0 to B3. CIN and COUT are the carry inputs
and outputs respectively and the result of the arithmetic or logical operation appears at the output F. The
operation performed by the chip depends on the states of the three select input pins S0 to S2 as
summarised in table 2.

S2 S1 S0 Operation
0 0 0 Clear
0 0 1 B minus A
0 1 0 A minus B
0 1 1 A plus B
1 0 0 A XOR B
1 0 1 A AND B
1 1 0 A OR B
1 1 1 Set

Table 2. Operations of the 74F382.

The operations performed by the 74F382 are mostly self-explanatory with the possible exceptions of
„Clear‟ and „Set‟. These two operations set the output, F, to 0000 or 1111 respectively no matter what is
presented to the A and B inputs.
Taking the five minus three example again. To perform the calculation using this device, the A input could
be set to five (0101), the B input to 3 (0011) and the S input to „A minus B‟ (010 from table 2). The answer
then appears at the F output along with any carry bit at COUT.
As stated, this device is a particularly simple ALU. More elaborate varieties have been designed capable
of a wider range of arithmetic and logical operations (obviously requiring more S inputs to control them).
Also, most systems work with at least eight bit number representations. This can be achieved by cascading
two 4-bit devices or by investing in a more expensive 8-bit ALU.

10
A4.2 Registers
Even the most complex ALUs of the kind described so far are essentially nothing more than a large array
of combinational logic gates. Using an 8-bit ALU, the inputs are two bytes of binary input data and a set
of control signals. The outputs are a single byte for the result and a single carry bit. To use this ALU as a
pocket calculator, all of the input signals must be present simultaneously. In order to, say, add three and
five together, the user would have to hold down the three key on one keypad, the five key on another and
the „+‟ key on a third.
This arrangement is both clumsy and limiting. Supposing instead of adding two numbers together, we
wished to sum a list of one hundred numbers. It would be impossible to simultaneously input every number
on the list. Instead, they would be inputted to a calculator one number at a time in a sequential fashion.
Even in the simple 3+5 example, the information would usually be inputted sequentially. The number three
would be input first. The calculator remembers this number whilst the „+‟ key is pressed and the five
inputted before the result is finally obtained. For our ALU to operate in this way, it requires a short-term
„memory‟ circuit, or register, to remember the first input (and, for that matter, the required operation).
A digital electronic device capable of storing one-bit of information has been introduced in the form of the
D-type flip-flop. This circuit has a single input, D, an output, Q, and (being a synchronous logic device) a
clock input, CLK. The complement of the output is also often available. Once every clock cycle, the D input
is read by the device and the Q output is set to be in the same state (low or high). This „latching‟ occurs on
either the rising or the falling edge of the clock pulse, depending on the device. Importantly, the output
then remains in the same state until the next clock cycle, regardless of further changes in the input. In other
words, the circuit remembers the state of the input signal.

CLK
Q
D
Q

D
CLK
Q

Figure 7. A D-type flip-flop (positive edge triggered).

To use this circuit to remember a whole byte of bits, it simply needs to be duplicated so that instead of
using a single flip-flop with one input and output, we use eight flip-flops with eight inputs and outputs. All
of the clock inputs are connected together so that on each clock cycle, the circuit remembers all eight input
bits.

11
CLK

CLK
D7 D Q Q7
CLK
D6 D Q CLK
Q6
CLK
D5 D Q Q5
CLK
8 CLK 8
D4 D Q Q4 D0-7 D0-7 Q0-7 Q0-7
CLK
D3 D Q Q3
CLK
D2 D Q Q2
CLK
D1 D Q Q1
CLK
D0 D Q Q0

Figure 8. An eight-bit memory circuit, or register (left) and a shorthand representation of the same structure
(right).

Using this register, it is now possible to operate our ALU using only a single input byte. An extra control
signal is required for the clock inputs to the register flip-flops.

Two input bytes Single input byte

8
Working
regis ter
CLK
8 8
D
Q

A B A B

Cont rol S ALU Cont rol S ALU


inputs inputs
COUT F COUT F

8 8

Carry Result Carry Result


output output

Figure 9. An ALU before and after the addition of a working register.

12
A4.3 Tri-State I/O ports and Busses
Although the addition of a working register has simplified the input/output requirements of the ALU
considerably, there is still some room for further improvement. In the current configuration, a separate set
of connections is used for the input to the ALU than is used for the output. The same is true of the working
register as well. The next stage of simplification is to transform the circuit so that only a single set of eight
wires is required to read from and write to the ALU or the working register. Furthermore, this same set of
eight wires will be used to read from and write to all other components within a larger circuit that will
become a microprocessor.
Taking the working register, the aim is to combine the D inputs and Q outputs into a single set of eight bi-
directional connections. In the simplest terms, this can be accomplished using a digitally controlled switch.
The circuit is not changed in terms of the memory operation. However, there is now only a single
input/output connection. In addition, there is a control input that sets whether the register is to input (read
information from the bus) or output (write information to the bus). The total number of connections required
to the register is, therefore, reduced from 17 (8 in, 8 out, 1 clock) to 10 (8 in/out, 1 clock, 1 input/output
control).

Input / Output
CLK Control

8 CLK 8
D 0-7 Q 0-7
8
Input / Output

Set of 8 digitally
controlled switches

Figure 10. Simplifying the connections to the working register using bi-directional input/output connections.

This arrangement is often referred to as a tri-state port. Unlike binary outputs, each of the eight
input/output terminals can now have one of three possible states. These are high and low, for the two
output states, and a third high-impedance state.
In a more elaborate system, there will be more than just one register. Using the tri-state input/output
arrangement, however, only one set of eight connections is required to transfer information from any
register to any other. This set of common connections is known as a bus.

13
CLK 8
A I/O
I/O
8

Control Inputs
CLK 8
B I/O Data
Bus
I/O

CLK 8
C I/O
I/O

Figure 11. Three registers interconnected by a common data bus.

Figure 11 shows how a common bus can interconnect three registers. Normally, all three of the tri-state
input/output ports of the registers would be in the high-impedance (or „input‟) state. In order to transfer
data from one register to another, however, one of the registers would be set to the „output‟ mode. Each
of its eight input/output connections would be in the „output‟ state, held either high or low depending on
the contents of the register. All of the other registers will be in the high-impedance state; they will look like
open circuits and will not interfere with the logic levels on the bus. Now, if the clock input of one of the
registers rises, the data on the bus will be transferred and copied into that register.
Using a bus, the connections to the ALU become greatly simplified as both the input and the output
connections can share the same bus. As the bus can only be used for one data transfer at a time, however,
this does mean that temporary storage is required for the result whilst the second operand is inputted. A
convenient solution is to store the result back in the working register.

Bus

8
Working
regis ter

A B

Cont rol S ALU 8


inputs
COUT F

Carry
output

Figure 12. An ALU and working register accessed by a single bus

(read/write and clock signals are omitted for clarity).

14
Taking the example of adding five and three together, the sequence of operations required is:
 The number five is written to the working register, W, via the bus.

 The number three is written to the other ALU input via the bus. The result now appears at the ALU
output and, when clocked, will be written back into the working register, W.

 The result (eight) is read from the working register, W, using the bus again and is presented back to
the user.

The important point to note in each of these stages is that the bus can only ever be used for one data
transfer at a time. Also note that as the result is placed back in W, this could be used again as one of the
inputs to another operation. With this arrangement, long lists of numbers can be easily added together.

A5. MICROPROCESSORS AND MICROCONTROLLERS


A5.1 Block Diagram
Figure 13 shows a block diagram of the basic elements of a microcomputer (based on either a
microprocessor or microcontroller). At the centre of the system is the ALU and working register described
previously. These are connected to a system bus, shared with a number of other registers, some of which
have specialised functions.
The flow of information along the bus (reading, writing, arithmetic and logical operations) is controlled by
a central control unit. These control signals are generated by reading a list of coded instructions (or a
program) stored in a special block of program memory.

8 System Bus

PC W SR I/O

General Purpose
ALU Registers
Program
Memory

Inputs / Outputs
Instruction Cont rol signals to
Cont rol Unit
Register registers, ALU, etc.

PC = Program Counter (register)


W = Working Register
SR = Status Register

Figure 13. A microcontroller.

A5.2 Registers
The function of the working register, W, (sometimes also referred to as the accumulator) has already been
described. In addition, several general-purpose registers for temporarily storing data are available. Also,
several special purpose registers can be accessed through the system bus.
The status register, SR, is a second output from the ALU. This register is used to store the carry output bit (or
carry flag) from any arithmetic operations. Several other flags like the zero flag are also stored in SR.

15
Some instructions are conditional on the state of one or more flag in SR so the sequence of instructions can
be controlled.
The program counter, PC, is another special purpose register. It holds the address, in program memory, of
the next instruction to be executed. Normally this register is incremented automatically after each clock
cycle. It is possible, however, to access PC via the system bus and therefore jump to any section of the
program, possibly conditionally on the state of SR. In this way, loops, sub-routines and „if-then‟ operations
can be realised.
The instruction register is a dedicated temporary storage register that simply stores the current instruction
to be executed. It is written to from the program memory and read by the control unit. The control unit
interprets the coded instructions and sends appropriate signals (read/write) to the registers connected to
the system bus and also controls the operation of the ALU.
A final set of special purpose registers are the input/output registers, I/O. These behave exactly alike the
general purpose registers except that the logic levels they contain can be read from or written to using
external pins on the chip housing the device. In some ways, these are the most important registers as they
provide the only way that the processor can communicate with the outside world and actually perform a
useful task.

A5.3 Programming
One of the distinctive features of a computer that sets it apart from the simple pocket calculator
developed previously is its ability to follow a pre-set list of instructions, or a program. In the
microcontroller of figure 13, these instructions are stored in the form of a list of coded binary numbers in a
special block of program memory. The position of the next instruction (or address) is held in the program
counter register, PC, and the instructions, when read from memory, are held in the instruction register.
Each possible instruction code number represents a specific permutation of control signals connected to:

 The ALU selection inputs that determine the operation to perform.

 The read/write control inputs of the tri-state ports of each register.

 The enable inputs of each register, determining which one will be written to during the next clock
cycle.

There are a huge number of possible permutations of these signals. Not all of them are allowed, however,
so the length of the code-word can be restricted, usually to between 8 and 16 bits (12 in the case of the
PIC devices). These code-words are known as operation codes, or op-codes for short.
A computer program, in its most primitive form, is just a list of op-codes. When executed by the
microcontroller, these will be interpreted as a list of operations to be performed by the registers, ALU etc.
Such lists of numbers are not particularly readable by human programmers however. Instead, they are
usually written in the form of mnemonics, i.e. short human readable terms that describe the operations to
be performed (e.g. ADD, SUB, GOTO). These mnemonics can be typed into a computer and then
translated into the corresponding op-codes by a program known as an assembler. The list of op-codes
(also known as machine code) produced by the assembler can then be written into the program memory of
the microcontroller, ready to be executed. Writing programs using mnemonics (or assembly language)
forms the second half of this course.

16
A6. INTRODUCTION TO THE PIC MICROCONTROLLER
During the second part of this module, you will learn about the specifics of programming a PIC
microcontroller referencing the well-known PIC16F84. This is basically a device with a very similar
architecture to the simple microcontroller illustrated in figure 13. It does, however, have a number of extra
features, the most significant of which will be outlined here for clarity.

A6.1 Registers
In addition to the working register, W, the PIC 16F84 has a bank of registers that can be accessed
directly via the system bus. These registers are referred to by number and are known as „file registers‟. Of
these file registers, most are general-purpose registers whilst the remainder have specific functions. Some
of these functions have been covered in this part of the module (program counter, status register, I/O
registers); the others will be explored in the remainder of the module.

A6.2 Literal Values


In the simple microcontroller, all ALU operations take their inputs from the working register and one other
register (via the system bus). The PIC 16F84 also allows the programmer to use a „literal‟ value for one of
the arguments instead of the contents of a file register (the working register provides the other input). A
„literal‟ value is a fixed constant that is embedded in the op-code and is set at the time the program is
written and compiled.

A6.3 Data Destination


The simple microcontroller always stored the results of ALU operations in the working register. When
performing operations on file registers, the architecture of the PIC 16F84 also allows the programmer to
store the result directly back in the file register instead of W. NB. This is not an option when performing
operations on literals where the result is always stored in W.

A6.4 Other Features


The PIC 16F84 has several other enhanced features compared with the simple model in figure 13.
Examples are:

 Stack: values of the program counter can be temporarily stored and later retrieved using a first-in-
last-out stack; essential for sub-routine programming
 Timer: accurate hardware-based timing is provided
 Interrupts: various external influences can be made to redirect program flow at any time using
interrupts
 EEPROM: a bank of non-volatile data memory accessed via special purpose registers

This concludes part A of the course material. In part B we will consider practical aspects of
microcontrollers, embedded systems and assembler programming using PIC microcontrollers.

17
PART B. MICROPROCESSORS AND ASSEMBLER PROGRAMMING

B1. INTRODUCTORY NOTES


In this part of the course we will consider the more practical aspects of microcontrollers, embedded
systems and assembler programming using PIC microcontrollers. The objectives here are to

 develop an understanding of the basic principles of microprocessors and appreciate the


difference between microprocessors, microcontrollers and DSPs (digital signal processors),
 achieve a working knowledge of the PIC microcontroller,
 have experience of assembler programming and a basic appreciation of embedded systems.

The PIC microcontrollers we will study are made by a company called Microchip. They are low-cost,
single-chip, 8-bit processors. We will program a PIC microcontroller in the laboratory sessions.

B2. AN INTRODUCTION TO MICROPROCESSORS AND PIC


PROGRAMMING
B2.1 Introduction to Microprocessors
As we have seen, a microprocessor is a programmable logic device with a designed set of instructions. It
contains three primary components; a processing unit, memory, and, input and output (I/O).

 Arithmetic/Logic Unit (ALU). This processing unit performs arithmetic operations such as addition
and subtraction, and, logic operations such as AND, IOR and XOR.

 Memory. Program and data memory.

 Input and Output. (I/O). Analogue or digital for external communication.

B2.2 Microprocessor Programming


A program is a set of instructions written in a specific sequence for a processor to accomplish specified
tasks. An instruction is defined as a complete task (such as addition) performed by the microprocessor.
Each microprocessor has its own set of instructions. To be intelligible to the microprocessor, instructions must
be supplied in binary, i.e., as machine language.
Assembly language is a symbolic language which represents instructions with short human-readable
mnemonics. For example, in PIC assembler a null operation or „no operation‟ is represented by the
mnemonic „NOP‟. There is a one-to-one correspondence between the assembly language mnemonics and
machine code instructions. Assembly languages (also called assembler languages) are specific to a given
microprocessor, i.e., not transferable from one processor to another.
An assembler is a software tool that converts assembly source programs into machine language object
files. Like interpreters and compilers, assemblers contain some built-in debugging tools which can detect
errors in syntax. MPLAB is Microchip's freeware PIC development environment which includes an
assembler that generates assembled files (object files) with .HEX extensions which are used to program PIC
chips. MPLAB is provided as freeware by Microchip and can be downloaded from the Microchip website.
Machine and assembly languages are referred to as low-level languages. Programs written in these
languages are generally faster and more compact than higher-level language programs but are not
transferable to other processors.

18
High-level languages such as C, Pascal and BASIC are machine-independent. Programs (source code)
written in these languages are translated by compilers or interpreters into machine language compatible
with the given processor. The translated code is called object code. Each microprocessor needs its own
compiler or interpreter. The main difference between a compiler and an interpreter is the process by
which it generates the machine code. A compiler reads the entire program then generates the object
code. An interpreter translates one instruction at a time, producing and executing the object code before
reading the next instruction. An important advantage of high-level languages is that they are much easier
to debug.

B2.3 A Simple PIC Program


The listing below is a very simple example of a PIC program written in the PIC assembler language we
will be studying later. You are not expected to be able to understand the program at this stage,
however, study the layout, read the comments on the right-hand side and the notes below and then try the
introductory exercises.
; WRITTEN BY SIW
; DATE 01/01/10
; FILE SAVED AS TEST.ASM
; DEVICE PIC16F84
; OSCILLATOR XT (4MHZ)
; WATCHDOG DISABLED
; FUNCTION OUTPUTS THE VALUE 0XF1 TO 8 LEDS CONNECTED TO PORTB
; ----------------------- EQUATES ------------------------------------
PORTB EQU 0X06 ;ASSIGN THE PORTB REGISTER TO THE LABEL 'PORTB'
; ----------------------- MAIN PROGRAM ------------------------------------
START ORG 0X00 ;'ORG' SPECIFIES THE MEMORY LOCATION OF THE PROGRAM
CLRF PORTB ;CLEAR THE PORTB REGISTER
MOVLW 0X00 ;MOVE THE VALUE 00, I.E., ALL 0'S TO W
TRIS PORTB ;CONFIGURE PORTB WITH THE VALUE IN W (THE
;WORKING REGISTER) 1=INPUT AND 0=OUTPUT.
;SO 00 (ALL 0'S) MAKES ALL PORTB LINES OUTPUTS.
MOVLW 0XF1 ;MOVE THE HEX VALUE F1 TO THE WORKING REGISTER
MOVWF PORTB ;MOVE THE VALUE OF W TO THE OUTPUT (PORTB)
LOOP GOTO LOOP
END

B2.4 Representing numbers in PIC assembler


“0x” indicates a hexadecimal number. 0xF1 is F116. We can also write this as H‟00F1‟.
The assembler will also understand our number in binary if we write it as B‟11110001‟ or in decimal if we
write it as D‟241‟ (0xF1 is (15x16) +1 = 240+1=241).
You are encouraged to use hexadecimal in your assembler code but to use binary where it makes the
ON/OFF state of devices more visible.

B2.5 Observations about PIC assembler format


1. Instruction lines are arranged in columns; labels, operators, operands.

2. So “START” and “LOOP” are labels.

3. “CLRF” is an operator. It is a PIC assembler instruction.

4. “PORTB” is an operand. It is the information required for the “CLRF” instruction.

5. There are two types of instructions in the program; assembler instructions which are instructions for the
target device, and, assembler directives, i.e., instructions for the processor program and instructions to

19
the assembler software. We will study these in detail later. For now it will be useful to know that
“EQU”, “ORG” and “END” are assembler directives. So they will not be found in the list of PIC
assembler instructions.

6. Our simple example program is purposely over-commented. In your lab exercises, you will be
encouraged to write fewer and shorter comments that describe the more general function of the code.

7. The program header provides information about the code, target device and configuration. The
function statement provides details about the functionality of the program and connected inputs and
outputs.

B2.4 Introductory Exercises


1. What symbol is used as a delimiter to distinguish a comment from assembler code?

2. What does the MOVLW instruction do? (You will need to find the PIC assembler instruction set and
check the description.

3. What do MOVWF, and GOTO do?

4. Where is PORTB in the register file (data memory) map? (This isn‟t easy. I will explain in the
lecture how to find the „register file map‟ in the notes and the more detailed map in the PIC
reference data at the back of this study guide.)

5. What are the physical locations of the PORTB pins on the PIC microcontroller? (Again, we will look
at the PIC reference data sheets at the back for a pin diagram).

20
B3. ASSEMBLING TEST.ASM INTO OBJECT CODE IN MPLAB

Figure 14. TEST.ASM in the Microchip’s MPLAB

The “Output” window at the bottom reports on the assembling process.

21
Figure 15 TEST.LST - The listing file produced as part of the assembling process. The actual hexadecimal
values of the machine language object file are shown on the left-hand side.

(For example, MOVLW can be seen to map to value “30”)

22
B4. MICROCONTROLLERS AND EMBEDDED SYSTEMS
B4.1 Microcontrollers and Embedded Processors

 Microprocessors are general-purpose processors.

 DSPs (digital signal processors) are processors designed specifically for efficient mathematical
operations required by signal processing applications.

 Microcontrollers are processors designed specifically for embedded system and control
applications. They are more robust processors, have good I/O control and low power modes.

A controller is used to control some process or aspect of the environment. At one time, controllers were
built exclusively from logic components, and were usually large heavy boxes. With the advent of
microprocessors entire controllers could fit on a small circuit board. Some controllers still use
microprocessors (e.g., the Zilog Z80 or Motorola 68000). As the process of miniaturization continued, all
of the components needed for a controller were built onto one chip.
A microcontroller is a highly integrated chip which includes, on one chip, all or most of the parts needed
for a controller. The microcontroller could be called a "one-chip solution". It typically includes:

 a central processing unit (CPU)

 Random Access Memory (RAM)

 Erasable Programmable Read Only Memory (EPROM) or Electrically EPROM

 I/O (input/output) - serial and/or parallel

 timers

 interrupt control

A typical microcontroller has easy and direct access to I/O (input/output), bit manipulation instructions,
and quick and efficient interrupt processing.
Microcontrollers are available with a wide range of features, for example, watchdog timers,
sleep/wakeup modes, power management, powerful I/O channels supporting a range of protocols, etc.
We are using a Microchip PIC microcontroller as an example processor on this course. The PIC16F84 is a
low-cost, single-chip, 8-bit microcontroller.

B4.2 Watchdog Timers


Watchdog timers are very useful microcontroller features. A watchdog timer provides a means of
graceful recovery from a system problem. This could be a program that goes into an endless loop, or a
hardware problem that prevents the program from operating correctly. If the program fails to reset the
watchdog timer (see the CLRWDT instruction) at some predetermined interval, a hardware reset will be
initiated. The bug may still exist, but at least the system has a way to recover. This is particularly useful
for unattended systems.
The watchdog timer is an example of a “configuration fuse” (a configuration setting made when the device
is programmed).

23
B4.3 Embedded Controllers/Embedded Systems
An embedded controller is a controller that is embedded in a greater system. A precise definition is
difficult; we could say that an embedded controller is a controller (or processor) that is embedded into
some device for some purpose other than to provide general-purpose computing. The system is referred
to as an embedded system.

B4.4 Applications
Embedded microcontrollers are frequently found in appliances (microwave ovens, refrigerators, televisions,
VCRs and stereos), computers and computer equipment (laser printers, modems, disk drives), cars (engine
control units, diagnostics, climate control), environmental control (greenhouse, factory, home),
instrumentation, aerospace, and many more. In many systems, more than one processor can be found.
Microcontrollers are typically used where processing power is not so important.
Microcontrollers are well-suited to data logging applications. For example, monitoring and/or recording
environmental parameters such as temperature or humidity. Their small size, low power consumption, and
flexibility make them ideal for unattended data monitoring and recording.
The automotive market has been an important driving force in the microcontroller market, especially at the
high end. Several microcontroller families were developed specifically for automotive applications and
were subsequently modified to serve other embedded applications. The automotive environment is
demanding. Electronic components must operate under extreme temperatures and be able to withstand
vibration, shock, and electromagnetic interference (EMI).

B5. MICROCONTROLLER ARCHITECTURES AND INSTRUCTION SETS


B5.1 Von-Neuman Architecture
Microcontrollers based on the Von-Neuman architecture have common data and program memory. A
"data" bus is used to fetch both instructions and data. It first fetches an instruction, and then it fetches the
data to support the instruction.

B5.2 Harvard Architecture


Microcontrollers based on the Harvard Architecture have a separate data and instruction memories and
buses. This allows accesses to occur in parallel. The PIC16F84 is a Harvard architecture microcontroller.

B5.3 Complex Instruction Set Computer (CISC)


The typical CISC microcontroller has over 80 instructions, many of them very powerful and specialized for
specific tasks. It is quite common for the instructions to all behave quite differently. Some might only
operate on certain address spaces or registers, and others might only recognize certain addressing modes.
The advantages of the CISC architecture is that many of the instructions are macro-like, allowing the
programmer to use one instruction in place of many simpler instructions.

B5.4 Reduced Instruction Set Computer (RISC)


The PIC16F84 is a RISC processor with just 35 (37 including the two 'obsolete' instructions) very basic
instructions most of which operate in a single clock cycle.

24
B6. AN INTRODUCTION TO THE MICROCHIP PIC16F84
B6.1 The PIC16F84 Microcontroller
'PIC' was originally an abbreviation of 'Programmable Interface Controller'. The Microchip PIC16F84 is a
member of the large family of PIC microcontrollers produced by Microchip. The PIC16F84 is a low-cost,
single-chip, 8-bit microcontroller. It is a simple and very popular microcontroller.

B6.2 PIC16F84 Memory


There are two memory blocks in the PIC16F84; program memory and data memory, i.e., the PIC16F84
is a Harvard processor.
Each block has its own bus, so that access to each can occur during the same clock cycle.
The data memory consists of general purpose registers (GPRs) and special function registers (SFRs.)

B6.3 Program Memory


The PIC16F84 program memory is 14 bits wide and IK words long. This memory is read-only at run time.

Pointed to by reset vector 0x00


0x01
0x02
0x03
Pointed to by interrupt vector 0x04

0x3FF

Figure 16 PIC16F84 Program Memory

25
B6.4 Data Memory: Registers
Registers are memory locations used to store data temporarily during the execution of a program.
(BANK 0)

0x00 Indirect address.


0x01 TMR0
0x02 PCL Special Function
0x03 STATUS Registers
0x04 FSR Indirect pointer
0x05 PortA data PORTA
0x06 PortB data PORTB
0x07 Not used
0x08 Used for EEPROM Prog
0x09 “
0x0A PCLATH Program counter latch
0x0B INTCON For interrupt control
0x0C .. \
.. \ General Purpose
.. | Registers
.. /
0x4F .. /

Figure 17 PIC16F84 File Registers

(Note: this is a simplified memory map that excludes bank1.


Study the memory banks in the Microchip data sheets).

Notice the register-mapped I/O : When ports are configured as outputs, bits sent to the PORTA and
PORTB registers are automatically output. When configured as inputs, any received inputs affect the
values of the corresponding register contents.
PORTA is 5 bits wide and PORTB is 8 bits wide. Each port can be programmed as an input or an output.
(Bit 4 of port A can be used for an external timer input.)
PORTA has pins/bits labelled RA4:RA0 and PORTB has pins/bits labelled RB7:RB0 (msb:lsb)*
Referencing bits …. Bits are numbered 7-0 from left to right, i.e., msb-lsb. One of the most common
programming errors is incorrect specification of bit numbers. E.g., programmers reference the msb as bit
8, rather than 7 (an easy mistake given that there are 8 bits in a byte.)
In the PIC the working register (W) is used for ALU instructions. It is an 8-bit register which functions like
an „accumulator‟ in other processors.

(*msb - most significant bit, lsb - least significant bit)

26
B6.5 Architecture of the PIC Microcontroller
Before we can begin programming in assembler we need to consider the internal processor architecture,
and specifically the PIC16F84 internal architecture, in more detail.

Figure 18 Microchip’s architectural block diagram of the PIC16F8X

Buses- Buses are the communication lines for transferring data within the processor.
Oscillator -Used to drive the microprocessor, clocking data and instructions in the processor.
Timing - The PIC has an internal divide by 4 connected between the oscillator and the internal clock bus.
This makes instruction times easy to calculate. Most instructions (except calls and returns and other
instructions involving jumps and branches) take one clock cycle, so with a 4MHz oscillator (divided by 4),
instructions take1s.
The calculation of execution times is important. We will use timed delay subroutines in the laboratory to
slow down traffic light LED sequences (otherwise pedestrians will have 1s to cross the road!) The
PIC16F84 also has a hardware timer, TMR0, which we will consider later.
Program Counter -The program counter stores the current program position. After each instruction the
program counter is incremented automatically so that it points to the location of the next instruction or data
in memory. The PIC16F84 has a 13-bit program counter.

27
Status Register - The STATUS register is a very important register which contains all the arithmetic status of
the ALU and Reset status. For example the zero bit in the register indicates whether the previous arithmetic
or logic operation resulted in a zero.
Stack - The stack is used to save the program counter contents when subroutines are called, so that the
processor knows where to resume program execution when it returns from a subroutine. The PIC16F84 has
an 8-level stack. (It is not accessible to the programmer.)
Reset Vector - On power-up or reset, the PIC16F84 will go to program memory and begin executing
instructions sequentially.
Interrupt Vector - Interrupts are used to change the normal flow of a program so that it can perform
another (specified) function. In the PIC16F84 the 'interrupt vector' points to program memory location
0x04, so that if an interrupt occurs, the first instruction to be executed will be at this location. Interrupts
are configured in the interrupt control register (INTCON).

B7. PIC16F84 PROGRAMMING


B7.1 Flowcharts
Flowcharts are simple graphical representations of program steps and flowlines which define the sequence
of those steps. Sketching flowcharts can help in the design of new programs and are a useful form of
documentation for existing programs.
Flowcharts are not appropriate for use in all circumstances. For example, interrupts and resets cannot
easily be represented. Other design representations exist that are tailored to specific application
domains. However, for assembler programming, flowcharts are generally preferred.

T F
First task
Condition

Condition Case #1
T
Next task
F
Task #1 Task #2

Condition Case #2
T

F Task sequence
... ... Selection (if..then.else)
T
Loop Task
F

Condition Case #N
T
Condition Condition Loop Task
F F T

T F

Selection (switch) Repetition (do..while) Selection (while)

Figure 19 Flowchart Examples

28
B7.2 Program Documentation
Good code documentation is essential if programs are to be maintained.
The header should provide all the important processor details and identify the programmer. Most
importantly, it should contain a FUNCTION statement that tells the reader what the processor needs to be
connected to, exactly which I/O pins are connected to which devices and very clearly what the program
does when it is working correctly.
Labels should be meaningful. They should help to make your code more readable. Try to avoid using
labels which may be reserved words (see assembler directives).
Comments should be clear and concise. They should summarise important functionality. Comments often
summarise the function of several lines by using \ and / characters to tie lines together (see code
examples).
A clear column structure also helps code to be more readable. Separating equate and sub-routine
components and providing short headings for each also makes the code easier to understand.

B7.3 Subroutines
Subroutines are a sequence of instructions for performing a particular task. They generally make code
more efficient because their functions can be re-used.
Subroutines are normally placed before the main program after the ORG and GOTO lines.

They are implemented using CALL and RETURN (or RETLW).

When a CALL instruction is encountered, the program counter is “pushed” onto the stack. A new value is
loaded into the program counter and instruction execution starts from the new address.

When a RETURN or RETLW instruction is encountered, the program counter is restored by “popping” the
stack.
You should use a subroutine when you need to perform a task, and then continue with a previous task
(otherwise, use GOTO.)

Can a subroutine be called from within another? Yes. The limit to the depth of nesting is the depth of the
program counter stack. The PIC16F84 has a program stack depth of 8.

29
B7.4 A Software Time Delay
In this section we will consider a software time delay subroutine. It can be CALLed to generate a software
time delay (later we will consider the PIC's on-board hardware timer, TMR0.)
Study the example below very carefully. Use the reference data at the back to identify exactly what
each instruction does.
Example:-
DELAY MOVLW 0XFF ;0.2 sec delay
MOVWF MCOUNT
GET_N MOVLW 0XFF
MOVWF NCOUNT
DEC_N DECFSZ NCOUNT,F
GOTO DEC_N
DECFSZ MCOUNT,F
GOTO GET_N
RETURN

The DELAY subroutine will generate a time delay when called from the main program (CALL
DELAY)or from another subroutine.

The subroutine contains two nested loops. The time taken for the delay can be changed by altering the
contents of two loop counters; MCOUNT and NCOUNT.

In our example, MCOUNT =NCOUNT=0xFF=255.

So the time taken is approximately 3xMCOUNTxNCOUNT= 3x(255x255) = 195,075 clock cycles.

B7.4.1 Why the 3?


 The delay subroutine spends most of its time inside the inner loop, and much, much less of the time
in the outer loop. So the time spent executing the inner loop should give us a good approximation
of the total time delay created.

 The inner loop contains two instructions that take 3 clock cycles; DECFSZ (normally 1 clock cycle)
and a GOTO (always 2 clock cycles.)

 Because this inner loop is repeated (MCOUNT X NCOUNT) times, the total time delay is
approximately 3xMCOUNTxNCOUNT clock cycles.

B7.4.2 Converting clock cycles into time


Each clock cycle takes 1s with a 4MHz oscillator. We will be using a 4MHz oscillator to provide timing
pulses for the PIC instruction clock in the laboratory. Although the PIC will go faster, slower speeds are
easier for introductory development work. Importantly, 4MHz oscillator circuits will work in a breadboard
circuit, but faster circuits would have problems with capacitance between the tracks.
The PIC has an internal “divide by 4”, which means that 4 oscillator pulses are used to generate each clock
cycle. Each 4MHz pulse has a duration of ¼s. The PIC uses four of these pulses to obtain the 1s clock
cycle.

So with a 4MHz oscillator, 195,075 clock cycles = 195,075s = 0.195075s = approximately 0.2s

Hence the delay above takes approximately 0.2 seconds with a 4MHz oscillator.

30
Note: Longer delays can be generated with a triple loop. The outer loop counter can be preloaded and
the subroutine entered at the second loop to generate delays of different lengths.
A private study exercise
Calculate the delay exactly. Substitute low values (2 or 3) for m and n, and manually step through the
code line by line decrementing the counters. You should find information about the exact time delay on
the course web page.

B7.5 Debouncing Switch and Key Inputs


A problem with mechanical switches is that the contacts often „bounce‟, making contact then oscillating
between open and closed for a short time.
A simple way to avoid multiple bounce inputs is to wait a short time (a few msecs) after the initial closure
for the switch to stop bouncing and then test for release.
Time delays, like the one above, are often used to slow down processor responses.

31
B8. ACCESSING LOOKUP/DATA TABLES

Data (or lookup) tables can be very useful for data conversion and reference. To implement data tables,
the PIC programmer has to enter data values as dummy instructions in program memory. This is done using
a subroutine call that modifies the program counter with an appropriate offset specifying the location of a
RETLW command. In this way the required data value is returned by assigning a literal to W on return.

Example: The 8 bits of a byte can be used to represent the on or off status of the individual segments
(and decimal point) of a seven-segment display.
The following program segment looks-up the bit configuration to enable direct display of values between
0-9.
;---------------------GENERAL EQUATES----------------------
W EQU 0
F EQU 1
;---------------------I/O EQUATES ------------------------
PORTB EQU 0X06
;---------------------REGISTER EQUATES --------------------
PC EQU 0X02
;---------------------MAIN PROGRAMME ----------------------
ORG 0X00
START CLRF PORTB ;\
MOVLW 0X00 ; - CONFIGURE PORTB AS OUTPUTS
TRIS PORTB ;/
CHAR MOVLW 0X03 ;A TEST VALUE
CALL SEG_TABLE ;GET BIT CONFIG. (IN W)
MOVWF PORTB ;OUTPUT TEST VALUE
LOOP GOTO LOOP ;FINISH WITH LOOP
;
SEG_TABLE ADDWF PC,F ;ADD OFFSET TO PC
RETLW 0X3F ;0 SEVEN SEGMENT
RETLW 0X06 ;1 SEVEN SEGMENT
RETLW 0X5B ;2 SEVEN SEGMENT
RETLW 0X4F ;3 SEVEN SEGMENT
RETLW 0X66 ;4 SEVEN SEGMENT
RETLW 0X6D ;5 SEVEN SEGMENT
RETLW 0X7D ;6 SEVEN SEGMENT
RETLW 0X07 ;7 SEVEN SEGMENT
RETLW 0X7F ;8 SEVEN SEGMENT
RETLW 0X6F ;9 SEVEN SEGMENT
;
END

Important note :-
The program counter is always incremented automatically after an instruction so an offset of 0 will result in
an access to the 1st data table entry.

32
B9. INTERRUPTS

Interrupts are used to change the normal flow of a program so that it can perform another (specified)
function. They are useful features of microprocessors (and essential in most microcontrollers) because they
allow external events to change (interrupt) the normal flow of the software, executing code specifically
designed for a response to the change.
Processors without in-built interrupt support require programs that regularly inspect selected input lines.
This is called „polling‟. Polling is very expensive in terms of processing. Interrupts enable processors to
automatically respond to specified events and concentrate processing power on executing a main
program.
The PIC16F84 supports 4 in-built interrupt sources:
RB0 interrupt: Edge-triggered interrupt (via RB0/INT pin)
TMR0 overflow: Timer/counter overflow interrupt
PORTB change (bits 7-4): PORTB logic level change on bits 7,6,5,4
EEPROM write complete
When an interrupt occurs the instruction currently being executed is completed.

The program counter then jumps to address 0x04 in program memory and executes the instruction stored
there.
Interrupt lines are INPUTS into the microprocessor. Their lines must be configured as INPUTS. Interrupts
can be enabled or disabled (masked) individually or globally (all disabled regardless of source.) This is
done via the interrupt control register (INTCON.)
Only 5 PORTB pins support interrupts, these are RB0 and RB7-4. There are no interrupts on PORTA.

B9.1 The PIC INTCON Register


7 6 5 4 3 2 1 0

GIE EEIE TOIE INTE RBIE TOIF INTF RBIF

Global EE write Timer INTerrupt RB port Timer INTerrupt RB port


Interrupt complete Overflow Enable change Overflow Flag change
Enable Interrupt Interrupt Interrupt Interrupt Interrupt
Enable Enable Enable Flag Flag
(RB0) (RB7:4) (RB0) (RB7:4)

Figure 20 The PIC INTCON Register

The RB0/INT is an edge-triggered interrupt. It can be enabled and disabled using the INTE flag in the
INTCON register. It can be configured to respond to a leading or falling edge (see bit 6 of the OPTION
register).
PORTB pins (RB7 to RB4 inclusive) can be used as external interrupts. When configured as inputs, these
pins can trigger an interrupt on change. Their values are compared with previous values on the last read
of port B and if a change is detected the RBIF interrupt flag (bit 0 of INTCON) is set.

33
When an interrupt occurs, a pre-determined sequence of events occurs:

 The instruction being executed is completed

 The current value of the program counter is stored

 The program counter is then changed to 0x04

 The code (interrupt service routine) is executed

 The program counter is restored to its previous value

 Code execution continues from where it was before

Normally, the interrupt service routine would need to save/restore state (context)

B9.2 Using Interrupts


Interrupts are dealt with by a special subroutine called the interrupt service routine. This needs to be
implemented as shown below. 0x04 is the position of the PIC16F84 interrupt vector in program memory,
so all PIC16F84 programs using interrupts need the line” ORG 0X04”. Using both ORG directives, as
shown below, enables the assembler to locate the main program and interrupt service routine in program
memory.
RETFIE is the special return instruction required by the interrupt service routine. Note, that the interrupt
service routine is never CALLed. This subroutine will run itself automatically when the microcontroller
detects an interrupt.
ORG 0X00
GOTO START
;
ORG 0X04
GOTO INT_SERVICE

INT_SERVICE ; INT. SERVICE ROUTINE HERE


...
RETFIE ; RETURN FROM INTERRUPT
;
START ; MAIN PROGRAM GOES HERE
...
END

B9.3 Context Saving


It is often essential that the contents of the working and STATUS registers are backed up and restored
inside the interrupt service routine. This is called “saving context”.

B9.4 Interrupt Code Segment Example


Writing a program that uses interrupts requires the following

 Setting the GIE bit in INTCON. This is usually done early in the main program.

 Setting the enable bit in INTCON for the selected type of interrupt (one of the four types). Note.
All other interrupt enable bits will be clear by default. It is possible to have all 4 types of

34
interrupts active at one time, however, the interrupt service routine will need to be carefully written
to log and prioritise events if they happen at the same time.

 In the clock cycle after these bits are set, the processor can and will now automatically respond to
the selected type of interrupt events by running the code inside the interrupt service routine.

 The code in the interrupt service can, for example, call other subroutines, inspect the current status,
increment counters (perhaps keeping track of the number of interrupts that happen), it can also
work out which type of interrupt happened if more than one is enabled. It can do this by
inspecting the interrupt flags in INTCON.

 The interrupt flag that was set by the interrupt event needs to be cleared by the interrupt service
routine. If these flags aren‟t cleared the interrupt service routine will automatically be repeated
and the program will lock into an endless loop.

 After clearing the interrupt flag, the interrupt service routine is completed with the special
RETFIE instruction and the program can now resume from where it was before the interrupt
event.

Here is a simple code segment that shows this being done. It enables an RBIE interrupt. The important bit
setting and bit clearing operations are shown in bold. The interrupt service routine (INT_SER) backs up
and restores the contents of the working register and generates a PORTA output.

; ---------------- REGISTER EQUATES ------------------------------


INTCON EQU 0X0B ;INTERRUPT CONTROL REGISTER
MCOUNT EQU 0X0C ;
NCOUNT EQU 0X0D ;
LED_VAL EQU 0X0E ;
TEMP_W EQU 0X0F ;
; ----------------------------------------------------------------
ORG 0X00
GOTO START
ORG 0X04
GOTO INT_SER
; ---------------- INTERRUPT SERVICE SUBROUTINE ------------------
INT_SER MOVWF TEMP_W;BACKUP CONTENTS OF W
MOVLW 0X0F ;
MOVWF LED_VAL ;SET OUTPUT VALUE FOR PORTA
MOVWF PORTA ;SEND OUTPUT TO PORTA
MOVF TEMP_W,W ;RESTORE W
BCF INTCON,RBIF ;CLEAR INTERRUPT FLAG IN INTCON
RETFIE
; ------------------------ MAIN PROGRAMME ------------------------
START CLRF PORTA ;\
MOVLW 0X00 ; - CONFIGURE PORTA AS OUTPUTS
TRIS PORTA ;/
CLRF PORTB ;\
MOVLW 0xFF ;- CONFIGURE PORTB AS INPUTS
TRIS PORTB ;/
BSF INTCON,GIE ;ENABLE INTERRUPTS
BSF INTCON,RBIE ;ENABLE PORTB CHANGE INTERRUPT

35
B10. PIC ADDRESSING MODES

The PIC16F84 supports four addressing modes:

 immediate
 direct
 relative
 indirect

B10.1 Immediate Addressing


Addressing data is built into the instruction word. E.g., Literal instructions.
E.g.,
MOVLW 0X1E ;MOVE THE HEX VALUE 1E INTO W

B10.2 Direct Addressing


The address is specified after the instruction.
E.g.,
CLRF MYREG

B10.3 Relative Addressing


This mode of addressing involves altering the contents of the program counter producing a computed jump
from the current program location to some address relative to this point. GOTO and CALL instructions
handle this automatically. As we have seen, relative addressing via calculated jumps is usefully employed
to access data tables.

B10.4 Indirect Addressing


The first file register (INDF, indirect file address at 0x00) acts as an address pointer. It is not physically
implemented. Using this address actually calls the contents of the file select register (FSR) at 0x04 to be
used as the address of a file register.
To use a file register address relative to the a given file register, add an offset (or index) to the its
address, store the result in the FSR and use 0x00 as the file register designator for the instruction. This will
then find the necessary address. This procedure is like „indexed addressing‟ in other processors. However,
since there are only 68 general-purpose file registers in the PIC16F84 this addressing mode is not usually
required.

36
B11. COMPARING VALUES
B11.1 Using the STATUS Register
The contents of a file register can be compared with the contents of the working register to determine their
relative magnitudes. This can be done by subtracting the contents of W from the selected register and
testing the STATUS register.
For example:
MOVLW 0X2A ;LOAD W WITH 2A
SUBWF MY_REG,F ;SUBTRACT W FROM MY_REG
;
BTFSC STATUS,2 ;TEST Z-FLAG IN STATUS REG. SKIP
GOTO EQU_SUB ;GOTO SUBROUTINE

The zero flag in the STATUS register can test for equality (if W=F then zero flag is set, clear otherwise.)
The carry flag can test if W<=F (carry set) or if W>F (carry clear.) (See the instruction set handout for
examples.)
A method of testing a byte in a file register to see if it is zero is to use the MOVF instruction and place the
result in the register it came from. (See „status affected‟ for MOVF in the PIC16F84 instruction set.) Note
that the Z-flag is affected; if it is set after a register value is replaced by itself then the value must be 0.
Example:
MOVF MY_REG,F ;REPLACE VALUE WITH ITSELF
BTFSS STATUS,2 ;TEST Z IN STATUS REG. SKIP IF SET
GOTO MY_SUB ;GOTO SUBROUTINE IF NON-ZERO

37
B12. BIT MANIPULATION

The PIC16F84 has two bit manipulation instructions, BSF and BCF, which can be used to set and clear
individually specified bits. (Note : We have already used the bit test instructions BTFSS and BTFSC.)
… using logic instructions
Logical operations (and shifts) can also be usefully employed to change or test given bits. These methods
are particularly useful when two or more bits must be changed in one instruction cycle.
A Reminder
Bits are numbered 7-0 from left to right, i.e., msb-lsb. One of the most common programming errors is
incorrect specification of bit numbers. E.g., programmers reference the msb as bit 8, rather than 7 (an
easy mistake given that there are 8 bits in a byte.)

B12.1 Changing Bits to 1


MOVLW B’00000000’ ;MOVE TEST VALUE TO W
IORLW B’00100000’ ;IOR TO MAKE BIT 5 A 1
MOVWF PORTB ;DISPLAY RESULT
LOOP GOTO LOOP ;FINISH WITH LOOP

B12.2 Changing Bits to 0


MOVLW B’00100000’ ;MOVE TEST VALUE TO W
ANDLW B’11011111’ ;AND TO MAKE BIT 5 A 0
MOVWF PORTB ;DISPLAY RESULT
LOOP GOTO LOOP ;FINISH WITH LOOP

B12.3 Inverting Bits


MOVLW B’00000000’ ;MOVE TEST VALUE TO W
XORLW B’00100000’ ;XOR TO INVERT BIT 5 A 1
MOVWF PORTB ;DISPLAY RESULT
LOOP GOTO LOOP ;FINISH WITH LOOP

B12.4 Testing for Equal Values


MOVLW B’01010101’ ;MOVE TEST VALUE TO W
XORLW B’01010101’ ;XOR TEST VALUE
MOVWF PORTB ;DISPLAY RESULT
LOOP GOTO LOOP ;FINISH WITH LOOP
(Note: equality will set the Z flag in the STATUS register)

B12.5 Testing for Zero Valu es


MOVLW B’00000000’ ;MOVE TEST VALUE TO W
IORLW B’00000000’ ;IOR WITH ZERO
MOVWF PORTB ;DISPLAY RESULT
LOOP GOTO LOOP ;FINISH WITH LOOP
(again note: a zero value will set the Z flag in the STATUS register)

38
B13. ASSEMBLER DIRECTIVES

It is good practise to start assembler programming using the minimal set of programming tools. This gives
the programmer a better insight into the architecture of the device and an appreciation of program flow.
It also puts the programmer directly in control of memory allocations and program behaviour. However,
when longer more sophisticated programs are required, the programmer can make good use of advanced
assembler tools.
In addition to the PIC instruction set there are a number of assembler directives available to the
programmer. Assembler directives are commands written in the source code that control or direct the
program assembler progress. The result of using assembly directives can be observed in detail by
examining the .lst files.
From Microchip Userguide.txt : “Directives provide control of the assembler's operation by telling the
assembler [MPLAB] how to treat mnemonics, data references and format the listing file. Directives make
coding easier and provide custom output according to specific needs.”

We have already used three assembler directives; ORG, EQU and END. The following are some
examples of other assembler directives:
#DEFINE
Use to substitute a number of strings into one, e.g. combining port and bit information into one name which
can be used throughout the program.
Example:
#DEFINE MY_SWITCH PORTA,0

INCLUDE
Used to include code from external files.
Example:
INCLUDE “Y:\PIC\MY_CODE.ASM”

LIST
Can be used to pass information to the assembler regarding the processor type, and the format the
program has been written in (radix.)
Example:
LIST P=16F84 R=HEX

39
IF ELSE and ENDIF
These directives can be used to customise the program at the assembly stage. For example, selection of
the correct reset vector based on the given part number.
Syntax:
IF ..
..
ELSE
..
ENDIF

MACROs
Macros are user defined sets of instructions and directives that will be included in-line with the assembler
source code whenever the macro is invoked. The macro directive can be used to speed up code
generation
Macros consist of sequences of assembler instructions and directives. They can be written to accept
arguments, making them flexible. Forward references to macros are not permitted.
Example:
MY_MACRO MACRO
.. ;YOUR CODE HERE
ENDM

To use your code:


MY_MACRO ;EXECUTE MY_MACRO CODE

Recursive Macros. Macros may invoke themselves. Care should be exercised, as in all cases of recursion,
to avoid infinite loops.

40
B14. PIC OPERATORS AND DIRECTIVES

These lists are provided for reference only. Please note that directive names are reserved words which
cannot be used as labels in programs. For example, the words “HIGH” and “LOW” are directives and
therefore cannot be used as labels in your program. PIC programmers often use “HI” and “LO” as
alternatives.
For advanced assembly programming a range of arithmetic operators are required. The following list is
taken from the MPASM PIC assembler user guide and serves as an example of the range of operators
available to the PIC programmer.
Operator Example
( Left Parenthesis 1 + ( d * 4 )
) Right Parenthesis ( Length + 1 ) * 256
! Item NOT (logical if !( a - b )
complement)
- Negation (2's -1 * Length
complement)
high Return high byte movlw high CTRTable
low Return low byte movlw low CTRTable
* Multiply a = b * c
/ Divide a = b / c
% Modulus entry_len = tot_len % 16
+ Add tot_len = entry_len * 8 + 1
- Subtract entry_len = ( tot - 1 ) / 8
<< Left shift << flags
>> Right shift >> flags
>= Greater or equal if entry_idx >= num_entries
> Greater than if entry_idx > num_entries
< Less than if entry_idx < num_entries
<= Less or equal if entry_idx <= num_entries
== Equal to if entry_idx == num_entries
!= Not equal to if entry_idx != num_entries
& Bitwise AND flags = flags & ERROR_BIT
^ Bitwise exclusive flags - flags ^ERROR_BIT
OR
| Bitwise inclusive flags = flags |ERROR_BIT
OR
~ Complement flags = flags ~ERROR_BIT
&& Logical AND if ( len == 512 ) && b == c
|| Logical OR if ( len == 512 ) || b == c
= Set equal to entry_index = 0
+= Add to, set equal entry_index += 1
-= Subtract, set entry_index -= 1
equal
*= Multiply, set equal entry_index *= entry_length
/= Divide, set equal entry_total /= entry_length
%= Modulus, set equal entry_index %= 8
<<= Left shift, set flags <<= 3
equal

41
>>= Right shift, set flags >>= 3
equal
&= AND, set equal flags &= ERROR_FLAG
|= Inclusive OR, set flags |= ERROR_FLAG
equal
^= Exclusive OR, set flags ^= ERROR_FLAG
equal
$ Return program goto $ + 3
counter

Directive Description
CBANK Future Feature
CBLOCK Define a Block of Constants
CONSTANT Declare Symbol Constant
DATA Create Numeric and Text Data
DB Declare Data of One Byte
#DEFINE Define a Text Substitution Label
DW Declare Data of One Word
ELSE Begin Alternative Assembly Block to IF
END End Program Block
ENDC End an Automatic Constant Block
ENDIF End conditional Assembly Block
ENDM End a Macro Definition
ENDW End a While Loop
EQU Define an Assembly Constant
ERROR Issue an Error Message "<text_string>"
EXITM Exit from a Macro
EXPAND Expand Macro Listing
FILL Specify Memory Fill Value
IF Begin Conditionally Assembled Code Block if
IFDEF Execute If Symbol has Been Defined
IFNDEF Execute If Symbol has not Been Defined
INCLUDE Include Additional Source File
LIST Listing Options
LOCAL Declare Local Macro Variable
MACRO Declare Macro Definition
MESSG Create User Defined Message
NOEXPAND Turn off Macro Expansion
NOLIST Turn off Listing Output
ORG Set Program Origin
PAGE Insert Listing Page Eject
PROCESSOR Set Processor Type
RADIX Specify Default Radix
RES Reserve Memory
SET Define an Assembler Variable
SPACE Insert Blank Listing Lines
SUBTITLE Specify Program Subtitle
TITLE Specify Program Title
#UNDEFINE Delete a Substitution Label
VARIABLE Declare Symbol Variable
WHILE Perform Loop While Condition is True

42
B15. THE PIC WATCHDOG TIMER (WDT)

During normal operation a WDT time-out generates a device reset. If the device is in SLEEP mode, the
watchdog timer can wake it and the device will continue with normal operation. (External resets, RB0/INT, RB
port change and EEPROM interrupts will also wake the device.)
The watchdog timer is configured via the OPTION register. It has a nominal time-out of 18ms which can be
increased to ~2.5s by use of the prescaler bits in the OPTION register. The prescalers divide the clock input
by one of 8 values which effectively reduce the clock frequency.
The WDT is cleared by SLEEP and CLRWDT instructions. Bits 2-0 of the OPTION register define the
prescaler value and hence the WDT time-out period. Bit 3 is the prescaler assignment. When this bit is set the
prescaler is assigned to the WDT. When it is clear the prescaler (note the different values) is assigned to
TMR0, the timer counter (TMR0 was previously called the RTCC, real time clock counter.) The /TO bit in the
STATUS register is cleared by a WDT time-out.
The OPTION register can be written to using the OPTION instruction (this is the second of the „obsolete‟
instructions - it is commonly used to avoid the need for bank switching.)
A CLRWDT instruction should be included in sections of the code where there is a possibility of a WDT
time-out. Ideally this would be in the main program loop.

B16. PIC RESETS AND RESET VECTORS

The PIC16F84 can differentiate between different kinds of resets:

 Power-On Reset (POR)


_________
 MCLR reset during normal operation
_________
 MCLR reset during sleep
 WDT time-out during normal operation
 WDT time-out reset during sleep

Reset Vectors
After a reset occurs the PIC program counter moves to a preset value (address). In the PIC16F84 the reset
vector is 0x00. Other PICs have different reset vector values.
B17. THE PIC HARDWARE TIMER (TMR0)

This is the on-board timer/counter. It can use either the internal or an external clock. It has an interrupt on
overflow from 0XFF to 0x00 (see TOIE and TOIF in the INTCON register.) Notice that the prescaler is
assigned either to the WDT or the timer/counter.
Here is a simple example which uses TMR0 to produce a time delay. When bit 5 is set the count has reached
32. The prescaler selected is 256.
Note that this delay is achieved by polling bit 5 of TMR0. A longer delay could be achieved by allowing
TMR0 to overflow, in this case TOIF could be poled or if TOIE and GIE are set (enabled) an interrupt could be
serviced.

Using the internal clock therefore produces 256x32s = 8.2ms delay.

;A Simple (Non-interrupt) Example of TMR0 Implementation


;------------GENERAL EQUATES-----------------------------------
W EQU 0
F EQU 1
;------------ I/O EQUATES -----------------------------------
PORTB EQU 0X06
;------------REGISTER EQUATES ---------------------------------
TMR0 EQU 0X01
COUNT EQU 0X0C
;-------------MAIN PROGRAMME ----------------------------------
ORG 0X00
START CLRWDT ;PREPARE FOR PRESCALER ASSIGNMENT
MOVLW B’11010111’ ;PREPARE PRESCALER
OPTION ;ASSIGN PRESCALER
CLRF PORTB ;\
MOVLW 0X00 ; -CONFIGURE PORT B AS OUTPUTS
TRIS PORTB ;/
CIRCLE BSF PORTB,0 ;TURN ON LED
CALL DELAY
BCF PORTB,0 ;TURN OFF LED
CALL DELAY
GOTO CIRCLE
;
DELAY CLRF TMR0 ;CLEAR TMR0, START COUNTING
AGAIN BTFSS TMR0,5 ;TEST IF BIT 5 IS SET
GOTO AGAIN
RETURN
;
END

B18. NOTES ON SOME OTHER PIC MICROCONTROLLERS


44
As we have seen the PIC microcontroller family use different reset vectors. There are other much more
important differences between members of the PIC family. Here are just a few:

 The PIC10 series have only 6 pins and the PIC12 series have only 8 pins. Some have on-board A/D.

 The PIC16 range has expanded significantly over the years. The PIC16F877 is an example of a fuller
featured processor. It has 8 10-bit A/Ds, 3 timers, 33 lines of I/O, 2 PWM lines and many other
useful features.

 The mid-range PIC17CXXXs have 40- to 84-pins (33-66 I/O lines) supporting a range of various
serial interface capabilities, up to 16 channels of 10-bit A/Ds, an on-board 8-bit multiplier and multi-
timers. For example, the PICs 17C42, 17C43 and 17C44 have 11 interrupt sources, 33 I/O pins, 55
instructions, 2K EPROM and can operate at a maximum frequency of 25MHz.

 The newer PIC18XXXX were designed with C programming in mind. They have a broad range of
useful features, some including USB interfacing.

 Originally the PIC microcontroller range were all 8-bit processors. The new Microchip dsPIC is a 16-
bit controller with digital signal processing capability. The PIC24 series is also 16-bit and the PIC32
are 32-bit.

B19. SUMMARY
This concludes part B of the course handbook. Additional course materials for tutorials, laboratory exercises
and revision can be found on the course web page http://www.eee.bham.ac.uk/woolleysi/teaching/pic/ This
page can be accessed via webCT. Reference material can be found in the following pages of the appendix
and additional reference material can also be found on the course web page.

45
APPENDICES:

APPENDIX A. THE PIC16F84 INCLUDE FILE

APPENDIX B. THE PIC16F84 INCLUDE FILE

APPENDIX C. SELECTED PAGES FROM THE MICROCHIP PIC16F84A


DATASHEET

46
APPENDIX A. THE PIC16F84 INCLUDE FILE

This file can be included in a PIC program (using the INCLUDE assembler directive). It provides a
comprehensive list of standard equates for all registers and bits, for example, “GIE” the General Interrupt
Enable bit in the Interrupt Control Register. This file is provided within MPLAB.
LIST
; P16F84A.INC Standard Header File, Version 2.00 Microchip Technology, Inc.
NOLIST

; This header file defines configurations, registers, and other useful bits of
; information for the PIC16F84 microcontroller. These names are taken to match
; the data sheets as closely as possible.

; Note that the processor must be selected before this file is


; included. The processor may be selected the following ways:
; 1. Command line switch:
; C:\ MPASM MYFILE.ASM /PIC16F84A
; 2. LIST directive in the source file
; LIST P=PIC16F84A
; 3. Processor Type entry in the MPASM full-screen interface
;==========================================================================
; Revision History
;==========================================================================
;Rev: Date: Reason:
;1.00 2/15/99 Initial Release
;==========================================================================
; Verify Processor
;==========================================================================
IFNDEF __16F84A
MESSG "Processor-header file mismatch. Verify selected processor."
ENDIF
;==========================================================================
; Register Definitions
;==========================================================================
W EQU H'0000'
F EQU H'0001'
;----- Register Files------------------------------------------------------
INDF EQU H'0000'
TMR0 EQU H'0001'
PCL EQU H'0002'
STATUS EQU H'0003'
FSR EQU H'0004'
PORTA EQU H'0005'
PORTB EQU H'0006'
EEDATA EQU H'0008'
EEADR EQU H'0009'
PCLATH EQU H'000A'
INTCON EQU H'000B'

OPTION_REG EQU H'0081'


TRISA EQU H'0085'
TRISB EQU H'0086'
EECON1 EQU H'0088'
EECON2 EQU H'0089'
;----- STATUS Bits --------------------------------------------------------
47
IRP EQU H'0007'
RP1 EQU H'0006'
RP0 EQU H'0005'
NOT_TO EQU H'0004'
NOT_PD EQU H'0003'
Z EQU H'0002'
DC EQU H'0001'
C EQU H'0000'
;----- INTCON Bits --------------------------------------------------------
GIE EQU H'0007'
EEIE EQU H'0006'
T0IE EQU H'0005'
INTE EQU H'0004'
RBIE EQU H'0003'
T0IF EQU H'0002'
INTF EQU H'0001'
RBIF EQU H'0000'
;----- OPTION_REG Bits ----------------------------------------------------
NOT_RBPU EQU H'0007'
INTEDG EQU H'0006'
T0CS EQU H'0005'
T0SE EQU H'0004'
PSA EQU H'0003'
PS2 EQU H'0002'
PS1 EQU H'0001'
PS0 EQU H'0000'
;----- EECON1 Bits --------------------------------------------------------
EEIF EQU H'0004'
WRERR EQU H'0003'
WREN EQU H'0002'
WR EQU H'0001'
RD EQU H'0000'
;==========================================================================
; RAM Definition
;==========================================================================
__MAXRAM H'CF'
__BADRAM H'07', H'50'-H'7F', H'87'
;==========================================================================
; Configuration Bits
;==========================================================================
_CP_ON EQU H'000F'
_CP_OFF EQU H'3FFF'
_PWRTE_ON EQU H'3FF7'
_PWRTE_OFF EQU H'3FFF'
_WDT_ON EQU H'3FFF'
_WDT_OFF EQU H'3FFB'
_LP_OSC EQU H'3FFC'
_XT_OSC EQU H'3FFD'
_HS_OSC EQU H'3FFE'
_RC_OSC EQU H'3FFF'

LIST

48
APPENDIX B. THE PIC16F84 INSTRUCTION SET
LITERAL AND CONTROL INSTRUCTIONS:
MNEMONIC DESCRIPTION FUNCTION
ADDLW K ADD LITERAL TO W K+W W
ANDLW K AND LITERAL AND W K .AND. W  W
CALL K CALL SUBROUTINE PC + 1  TOS, K  PC
CLRWDT CLEAR WATCHDOG TIMER 0  WDT (AND PRESCALER IF ASSIGNED)
GOTO K GOTO ADDRESS K  PC
IORLW K INCL. OR LITERAL AND W K .OR. W  W
MOVLW K MOVE LITERAL TO W K W
OPTION LOAD OPTION REGISTER W  OPTION REGISTER
RETFIE RETURN FROM INTERRUPT TOS  PC, 1  GIE
RETLW K RETURN WITH LITERAL IN W K  W, TOS  PC
RETURN RETURN FROM SUBROUTINE TOS  PC
SLEEP GO INTO STANDBY MODE 0  WDT, STOP OSCILLATOR
SUBLW K SUBTRACT W FROM LITERAL K - W  W
TRIS F CONFIGURE PORT F W  I/0 CONTROL REG F
(DOWNWARD COMPAT. INSTR.)
XORLW K EXCLUSIVE OR LITERAL AND W K .XOR. W  W

BYTE-ORIENTED INSTRUCTIONS:
MNEMONIC DESCRIPTION FUNCTION
ADDWF F,D ADD W AND F W+F  D
ANDWF F,D AND W AND F W .AND. F  D
CLRF F CLEAR F 0  F
CLRW CLEAR W 0  W
COMF F,D COMPLEMENT F .NOT. F  D
DECF F,D DECREMENT F F -  D
DECFSZ F,D DECREMENT F, SKIP IF ZERO F - 1  D, SKIP IF 0
INCF F,D INCREMENT F F + 1  D
INCFSZ F,D INCREMENT F, SKIP IF ZERO F + 1  D, SKIP IF 0
IORWF F,D INCLUSIVE OR W AND F W .OR. F  D
MOVF F,D MOVE F F  D
MOVWF F MOVE W TO F W  F
NOP NO OPERATION
REGISTER F
RLF F,D ROTATE LEFT F  C  7 0 
 
REGISTER F
RRF F,D ROTATE RIGHT F  C  7 0 
 
SUBWF F,D SUBTRACT W FROM F F -W  D
SWAPF F,D SWAP HALVES F F(0:3)  F(4:7)  D
XORWF F,D EXCLUSIVE OR W AND F W .XOR. F  D

BIT-ORIENTED INSTRUCTIONS:
MNEMONIC DESCRIPTION FUNCTION
BCF F,B BIT CLEAR F 0  F(B)
BSF F,B BIT SET F 1  F(B)
BTFSC F,B BIT TEST, SKIP NEXT INSTRUCTION IF SKIP IF F(B) = 0
CLEAR
BTFSS F,B BIT TEST, SKIP NEXT INSTRUCTION IF SET SKIP IF F(B) = 1

KEY:
FIELD DESCRIPTION
B BIT ADDRESS WITHIN AN 8-BIT FILE REGISTER
D DESTINATION SELECT; D=0 STORE RESULT IN W
D=1 STORE RESULT IN FILE REGISTER F.
DEFAULT IS D = 1.
F REGISTER FILE ADDRESS (0X00 TO 0XFF)
K LITERAL FIELD, CONSTANT DATA OR LABEL
W WORKING REGISTER

49

You might also like