Professional Documents
Culture Documents
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.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:
13 1101
+ 9 + 1001
10 Carried digits 10010
22 Result 10110
Base-10 Base-2
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
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
1630 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
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
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
Q2 Q1 Q0
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.
9
B3 B2 B1 B0 A3 A2 A1 A0
CIN
S2
S1 74F382
S0
F3 F2 F1 F0 COUT
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
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
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.
8
Working
regis ter
CLK
8 8
D
Q
A B A B
8 8
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 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
Carry
output
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.
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.
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 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.
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
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.
Arithmetic/Logic Unit (ALU). This processing unit performs arithmetic operations such as addition
and subtraction, and, logic operations such as AND, IOR and XOR.
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.
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.
2. What does the MOVLW instruction do? (You will need to find the PIC assembler instruction set and
check the description.
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
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.
22
B4. MICROCONTROLLERS AND EMBEDDED SYSTEMS
B4.1 Microcontrollers and Embedded 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:
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.
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).
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.
0x3FF
25
B6.4 Data Memory: Registers
Registers are memory locations used to store data temporarily during the execution of a program.
(BANK 0)
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.
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.
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 take1s.
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 1s 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).
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
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.
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.
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.
So with a 4MHz oscillator, 195,075 clock cycles = 195,075s = 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.
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.
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:
Normally, the interrupt service routine would need to save/restore state (context)
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.
35
B10. PIC ADDRESSING MODES
immediate
direct
relative
indirect
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.)
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
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.
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.
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:
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.
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