Documente Academic
Documente Profesional
Documente Cultură
PIC16F877A
Assembly Language
MPLAB
PICKIT2
Lana Michele
F2010
22 Table of Contents
Table of Contents
PIC Programming Workbook ......................................................................................... 1
Table of Contents ................................................................................................................ 3
Chapter 1 – What is a Microcontroller? ............................................................................ 5
Chapter 2 – Flowcharting.................................................................................................. 11
Assignment 1 – Flowcharting ................................................................................... 27
Assignment 2—Flowcharting ................................................................................... 29
Chapter 3 Troubleshooting ............................................................................................. 31
Assignment 3 -- Troubleshooting ............................................................................. 35
Chapter 4 – Basic Number Systems................................................................................. 43
Numbering Systems ...................................................................................................... 43
Converting from Binary to Decimal ............................................................................. 46
Converting from Decimal to Binary ............................................................................. 48
Converting from Hexidecimal to Binary ...................................................................... 50
Converting from Decimal to Hexadecimal ................................................................... 52
Converting binary to ASCII Code ................................................................................ 53
1‘s and 2‘s complements ............................................................................................... 54
Chapter 5 -- The PIC16F877A .......................................................................................... 61
Byte-oriented file register operations ........................................................................ 70
Bit-oriented file register operations .......................................................................... 70
Literal and Control Operations ................................................................................. 71
Assembler Directives ................................................................................................ 74
Lab 1 -- MPLAB software Simulation Lab .................................................................. 84
Chapter 6 – On to Real Circuits ........................................................................................ 87
Lab 2 – Blinking LED................................................................................................... 87
Lab 2a – Blinking LED Hardware ................................................................................ 90
Lab 2b – Blinking LED Software ................................................................................. 99
File Addition Modes ............................................................................................... 105
Lab 3 – Blinking LED with a Pushbutton ................................................................... 120
Lab 4 – Relays ............................................................................................................ 122
The Electro-Mechanical Relay ............................................................................... 122
The Solid State Relay.............................................................................................. 125
Difference between EMRs and SSRs ..................................................................... 125
Lab 5 – Relays 12 Volt Control .................................................................................. 129
Lab 6 -- Flashing Binary Counter with Labels and Equates ...................................... 130
Chapter 7 Logic in Action/Indexed Addressing .......................................................... 141
The AND gate ............................................................................................................. 143
The OR gate ................................................................................................................ 145
The NOT gate ............................................................................................................. 147
The XOR (Exclusive OR) Gate ................................................................................. 149
The NAND and NOR gates ........................................................................................ 151
Lab 7 – Logic in Action .............................................................................................. 152
Table of Contents
Chapter 1 – What is a
Microcontroller?
A microcontroller is often defined in terms of its comparison to a microprocessor, so lets
look at the microprocessor first
A microcontroller on the other hand, has RAM, ROM and peripherals internal to the
chip. One of the main differences between the two is that unlike the microprocessor, the
microcontroller is designed to perform only one task. Nestled in the heart of their circuit,
these microcontroller circuits are referred to as embedded circuits, meaning the
microcontroller is embedded in the circuit. Microcontrollers are portable, cheap and very
useful in small applications. Some examples of common applications for the
microcontroller are remote controls, microwaves, photocopying machines, telephones
printers, etc. The included peripherals may be as simple as I/O ports but commonly
include ADC converters, LCD drivers, PWM control, etc. Microcontrollers do not
usually utilize monitors, keyboards, mice or printers. We will get to some of these in this
course, and more in your fourth semester course, Interfacing.
6 Chapter 1 – What is a Microcontroller
Microcontrollers are perfect for small portable applications such as robotics and mobile
circuitry. I hope you have lots of fun learning about them.
In Chapter 5 I will go over our particular PIC chip, the 16F877A in more detail.
Chapter 1 What is a Microcontroller? 7
Of special interest is the ALU. The ALU is the Arithmetic and Logic Unit. It can receive
inputs from the working register, a literal value or a file register. Everything is
processed by the ALU.
As we work through the course, we will be covering all the sections shown in the diagram
above. Suffice it to say for now that the PIC allows you to do everything a computer can
do but on a smaller scale.
Chapter 1 What is a Microcontroller? 9
Kit List. As soon as you receive your kit, go through it and make sure all the parts are
there. If you are missing parts, we can replace them at this point. But after two weeks if
you have not gone through it and you are missing parts, you will have to replace them
yourself. So GO THROUGH YOUR KIT!
10 Chapter 1 – What is a Microcontroller
There are two components that we will not be using directly but which I have included
for you to make it easier. The LM7805 is a 5 volt voltage regulator. You can even hook
it up to a 9 volt battery. With this you can do your labs at home. All you need is a couple
of capacitors. (The labs must still be demonstrated in class for a sign off.)
The other is the MAX232 chip so that you can do some in line serial programming. We
won‘t get into that in this course but it is definitely something worth exploring and it will
help you next semester in Interfacing. You can find schematics involving the MAX232
online.
Chapter 2 Flowcharting 11
Chapter 2 – Flowcharting
Flowcharting is an important and necessary skill for you to develop if you are to become
a good technician or programmer. A good flowchart can make a process clearer in your
mind, and that is the number 1 priority for programmers of any kind. Understand the
problem. If the purpose of a process or project is not clear in your mind, how can you
expect to program it properly? A flowchart will help you do this.
You will notice that all of the instructions are in plain English. No programming code is
used. A flowchart should be universal so that you can take the description and apply it to
any code that you want. It should not be tied to any particular code like assembly or C.
Later on when you get to pseudocode you will be using C type instructions but not in a
basic flowchart.
Chapter 2 Flowcharting 13
Lets look at the flowchart from a slightly different angle. Does it look a little bit familiar
when viewed this way? Its just like a rung on a ladder diagram. (Think Motor Controls
and Pneumatics) Start and Stop are like power and ground. There is your straight line of
flow right across and in this case with a parallel rung thrown in to add some variety.
Keep this in mind when you are designing your flowchart. The main body of the flow
chart should be a clear vertical line, with some parallel choices added in. You never
create parallels by abandoning the centre line.
14 Chapter 2 -- Flowcharting
The first thing that we do when we start a flowchart is to give it a title which clearly
defines the process it must perform. This in itself defines what you are doing.
Having said that, building a flowchart is really quite easy. You are working with a
limited number of basic shapes. They will pretty much be the same wherever you go,
which is great because so few things have a standard these days. The most basic shapes
are the terminator or terminal box, the operations or process box, the decision box,
connector lines and connectors. We will add some other fancy boxes later on, but these
will get us started.
Microsoft Visio is available on the computers in the lab. You can choose to use another
flowchart building software if you like. There are many available online as trials etc., or
if you really want, you can use Autocad or Paint. I do expect it to look like a flowchart
and not to be hand drawn. If you are using Visio, make sure you choose flowcharting in
the Template Categories
Chapter 2 Flowcharting 15
Also choose Basic Flowchart and make sure that US units is selected.
If you pick metric, you will not see a decision box in your shape selection.
16 Chapter 2 -- Flowcharting
Chapter 2 Flowcharting 17
After you have chosen from this screen, the following screen should come up. This
shows you all of the shapes you can work with. If you don‘t see this, play around until
you get to the right screen.
18 Chapter 2 -- Flowcharting
Terminator
Every program will begin and end with a terminator sometimes called a terminal block.
Terminators are used to identify your start and stop or beginning and end points. You
write the name of your program or process in the Start block. This should briefly but
clearly describe the purpose of your process. The Stop on the other hand identifies that
the process has been completed. It might sound simple, but using a start and stop point
help you to identify your limits. The program should end when the process described in
the Start Terminator has been completed. As you can see in the illustration below, the
start has only one line coming from it and the end has only one line going to it.
Terminators do not appear anywhere in the flowchart except at the beginning and the
end.
We are going to build a little program as we go along and explain each of the blocks.
Our program is called Get Cheese and will go through the process of getting cheese. If
you have any questions about how to put arrows on your connector lines, go down to the
connector lines section.
Chapter 2 Flowcharting 19
Every program will have a series of operations or processes. Either name is fine. These
are the things that will occur as the program progresses. They do not require a decision
on your part, they are simply telling you what is being done or received or what you need
to do at that point. The operation box is a square or rectangle shape as shown below.
There is usually one line coming in and one line going out in a vertical path.
There is an exception to this however. If you have a loop in your program, it is possible
that there could be a third line coming in on one of the sides that originates further down
in the program. We will look at some of these later. For now don‘t worry about it.
Quite often, an operation or process block appears after the Start Terminator to begin the
program. In this case you can see that the process will start once we receive a request for
cheese. In this program we are going to pretend that your mom/dad/spouse/sibling asks
you to go out to the store and get some cheese so they can make grilled cheese
sandwiches for lunch. We all know how important cheese is on a grilled cheese
sandwich, so ‗not going‘ is not an option.
20 Chapter 2 -- Flowcharting
Decision Boxes
Many programs will have a decision that must be made. These are considered to be the
most important boxes in a flowchart. Did you get that?? These are the most important
boxes in a flowchart. This is where a process chooses one path or another. The decision
box has a diamond shape and always asks a yes or no question.
The decision box has one line coming in from the top and two lines coming out. One of
the lines must go down and follow a vertical path.
So you have received a request for cheese and you know that you have to go. What is the
first thing that you ask yourself?? Assume the store is two blocks away but it‘s really
raining. Your first decision might be whether to walk or drive. To express this using a
decision box you would do the following:
Chapter 2 Flowcharting 21
Connector Lines
Every program will have connector lines which indicate the direction of flow by way of
an arrow.
In Visio, to put arrows on your connector lines, click on the Line Ends drop down menu
and pick which arrow you want.
To make a line, select the line connector tool and away you go.
Chapter 2 Flowcharting 23
Connectors
Last of all we need connectors for when flowcharts are too big for one page.
There are two types, the on-page connector and the off-page connector :
The on-page connector is simply a circle. We would use this when we come to the
bottom of the page but there is room to continue the program at a different location on the
same page. We always put the same number or reference ID in both on-page connectors.
Notice here that they both have the number 2.
24 Chapter 2 -- Flowcharting
And the off-page connector. This looks like homeplate on a baseball diamond and is
used when we come to the bottom of the page and must continue on a new page. As with
the on-page connector, we use the same reference ID in both connector boxes.
Let‘s think of a simple problem we can put into a flowchart. You own a company and are
calculating the raises for the year. The employees receive commission as well as salary.
If their commission and salary combined add up to more than $100,000 (yeah that would
be cool) then they get a 10% increase in their salary. If it is less than $100,000 then they
only receive a 5% increase. There are 30 employees and you are required to calculate
each one. Once they are all completed you are to send the new salary information to the
payroll clerk.
We‘ll call the program Calculate new salary. What are your first and last operations?
Our first operation will be to receive the request for new salaries and our last operation
will be to send this new salary information to payroll. So we have a beginning and an
ending…… excellent!!!!!!!! What is going to happen in between?
Chapter 2 Flowcharting 25
Even if that is all you start with at first, that‘s great, we have a start and a stop point.
So now onto our operations. In this case once we have received our end of year request,
we need to retrieve some employee information in order to perform this process.
Our first operation is that we receive a request for new salaries. This is also the trigger
that starts the program.
If the total is less than 100,000 (no) we continue down and add 5% to the total
If the total is more than 100,000 (yes) we branch to the left and add 10% to the total
We loop through the program until all 30 employees are processed then forward the
information file to payroll.
As you can see here, we have added a loop at the point of the Decision box Employees
Complete?. This allows us to follow the same previous steps over and over until all 30
employees have been recorded. It‘s a great tool.
You may also notice that the loop up is on the right while the loop down is on the left.
Whenever possible, put loops up on one side and loops down on the other. It will give
more consistency to your flowchart and make it easier for you to follow later.
We could have added more into this flowchart, for instance depending on where the
employee data is we may have divided this into several operations. The great thing
about flowcharting is that you don‘t have to be concerned with the code at this point, you
Chapter 2 Flowcharting 27
are just understanding what is going on. Once you completely understand it, the code is
just an insertion process more than anything else.
Assignment 1 – Flowcharting
Let‘s modify our previous process a little. Instead of just the $100,000 amount as a
marker, you have decided to grade the salary increases a little. Greater than $100,000 is
still going to mean a 10% increase. But greater than $80,000 < $100,000 is going to be
a 7.5% increase and greater than $60,000 < $80,000 is going to be a 5% increase and
less than $60,000 is no increase and the employee is put on probation.
Draw it up on the computer. We have VISIO in the lab under Microsoft Office. If you
use VISIO remember that it won‘t print directly to our printer. Finish your flowchart,
press print screen and then paste it into a Word document.. Hand drawn is not
acceptable. Submit it as Assignment 1 -- Flowcharting. This flowchart must be
handed in in hard copy form.
This flowchart is to be handed in before you write test 1. Failure to do so will result in a
25 % deduction from your test.
28 Chapter 2 -- Flowcharting
Now let‘s talk about another handy tool, the subroutine box.
Subroutine boxes
We didn‘t go over these before but they will come in handy. Subroutine or predefined
process boxes are great for subroutines where you want to show what is happening but
on the side. Suppose for a moment that the Record New Amount operation box involved
a several step process all on its own but you don‘t want to put it all down there. You
would use the subroutine box to indicate there is a mini-process that will happen at that
point. On the side you would create a flowchart with terminal blocks. The start would be
the name of the subroutine and the stop would be Return, which would return you to the
same point in the program you left.
In this case we would not need to use the online connector, the predefined process box
will do it for us.
Chapter 2 Flowcharting 29
Assignment 2—Flowcharting
Think of a process that you encounter or a problem like the one above. It must have at
least 3 separate decision boxes and at least 1 connector or subroutine box. Draw it up on
the computer. We have VISIO in the lab under Microsoft Office. If you use VISIO
remember that it won‘t print directly to our printer. Finish your flowchart, press print
screen and then paste it into a Word document.. Hand drawn is not acceptable. Submit
it as Assignment 2 -- Flowcharting. This flowchart must be handed in in
hard copy form.
This flowchart is to be handed in before you write test 1. Failure to do so will result in a
25 % deduction from your test
Chapter 3 Troubleshooting 31
Chapter 3 Troubleshooting
You hear the word all the time in this program. But what does it really mean and how do
you go about it?
You have them already. Believe me, you wouldn‘t be alive on this planet if you didn‘t.
You run into problems every day that you need to solve.
You get up in the morning and go to make toast. The lever won‘t stay down on the
toaster. What do you do? You check to see if it‘s plugged in. You‘re checking for
power and ground.
So we‘re going to go through a little checklist to help you with your troubleshooting. If
you ask me to help you with a circuit I am going to ask you what steps you have followed
on this checklist. If you haven‘t followed anything, I‘ll come back when you have.
a) When you first walk up to the machine, having lost your money before, let‘s
say you are going to look and see if the lights are on the machine. If there are
32 Chapter 3 – Troubleshooting
b) Is there an ―Out of Order‖ sign on it? If the Out of Order sign is there, go find
another machine. If there is no sign, keep going.
c) Put your money in and press the selection. If your drink comes out you are at
the end of the program. If not, keep going.
d) Did you put enough money in? Maybe the price has gone up. If yes, go find
the maintenance man. If not, go back to the operation where you put money
in and press the selection.
e) If this solves the problem, drink your drink, your troubleshooting program is
over. If not, go find the maintenance guy, get your money back, find another
machine and go back to the start of the program
You can even see this whole troubleshooting process in a flowchart (below)
Chapter 3 Troubleshooting 33
Notice that the loop up going up on the right is kind of confusing and seems to interrupt
the process.. In this case an on page connector box would definitely help
34 Chapter 3 – Troubleshooting
If you don‘t understand the situation, find out. You can‘t troubleshoot anything if you
don‘t understand what is supposed to happen. Be prepared to explain what is supposed to
happen and why. The best way to find out?? READ. If you‘ve read it over a gazillion
times and you just don‘t get it, come see me. Don‘t stay stuck. But attempt to
understand it on your own first.
Chapter 3 Troubleshooting 35
Assignment 3 -- Troubleshooting
Think of a problem you are trying to solve right now or have solved recently. Write out
the steps to how you are going to solve it and create a flowchart. Hand it in. This
Assignment must be handed in before you write Test 1. Failure to do so will result in a
25% hit on your test.
36 Chapter 3 – Troubleshooting
Now that we‘ve done that, let‘s apply some troubleshooting techniques for solving circuit
problems.
Below you will see the chip we will be working with in this course, the PIC16F877A.
Label your pinout numbers for any pins that you are using on your chip. It makes it so
much easier to troubleshoot a problem later when you can verify pinouts just by looking
at them. Notice here below that the pinouts are all labeled both by number and function
on the PIC16F877A chip.
Divide the Circuit right from the beginning. Decide you are going to do the hardware
setup and troubleshooting before you even attempt any software. This will give you
more control over the circuit.
Wire Your Circuit to Accommodate easy troubleshooting. If you look at the circuit
below, you will see that all grounds are black, all power connections are red and that
Chapter 3 Troubleshooting 37
everything else is tight and close to the board to prevent confusion. The connections to
the Resistor Network are easy to see as are the connections to the LED bar. No wires are
crossing each other. Troubleshooting misplaced wires is relatively easy and painless
when you take care when wiring your initial circuit.
Test your hardware for errors. Make sure that all of your powers and grounds are
properly connected by testing the main rail, the side rails and the power and ground pins
on the chip.
Test any external inputs. This includes any pushbuttons (make sure that the input to the
chip change states when you push the button); clocks (make sure that you are getting a
clocking input with your oscilloscope and that it is within the proper range that you
should be seeing)
Test any external outputs. If there are any LEDs or motors, etc apply 5 volts or ground
to that output pin (whichever makes it active) and see if the light, motor, etc is actuated.
Some outputs you cannot test as in your piezoelectric transducer, because it needs a
crystal oscillation to actuate.
Doublecheck that all chips are in properly and are powered and grounded as to
their specs on their data sheets. Make sure your chip is not in backwards. The dot is
38 Chapter 3 – Troubleshooting
pin 1. Wherever the chip requires a power or a ground, double double check that you
have applied it. Ninety percent of the time, a circuit that is not working is due to a power
or ground issue.
Doublecheck any diodes, transistors and electrolytic caps If your circuit is using any
of these, make sure that they are in the right way, look up the data sheets to confirm.
Don‘t assume they are in the right way.
Once you are satisfied that you have tested all that you can in terms of hardware, move
on to the software portion of your circuit.
Ask a fellow student if you can try your chip on their working board.
If your chip works on their board, its hardware. Anything from an interface cable to the
wiring on your protoboard. If your chip does not work, check you chip for errors.
Remember these are troubleshooting tools. You must get your program working on your
board with your chip for a sign off.
Whatever you do, don‘t let yourself get overwhelmed. If you are confused and really
don‘t get it, come to me. I will help you if you are feeling lost.
Apart from that, ask yourself if it is likely hardware or software. If you really don‘t
know, start at the beginning of the last scenario by testing the hardware one section at a
time, moving on to the software portion once you are done. After a while it will be much
easier for you to discern if it is software or hardware.
40 Chapter 3 – Troubleshooting
On the next page you will see a Lab Documentation and Troubleshooting Table. You
will be required to show one for every lab that you do as well as a flowchart. You will
find the blank under Course Documents
Chapter 3 Troubleshooting 41
Program : ____________________________
Fill in the table, adding extra lines where you have dealt with errors. Give clear, detailed
explanations about how you fixed them. Put a check mark in the right hand column once you
have completed one step and are ready to move on to the next.
** must be done before I will even look at your circuit
In your own words, explain the purpose of the lab and what you should be seeing when it is
completed. (This requires you to read the entire lab before attempting ANYTHING)
Hardware Section
Wiring must be done in such a way as to be conducive to easy troubleshooting
(grounds are black, power is red). Red and black wires are not used anywhere else
and all other wires and components are tight to the board, colour differentiated and not
crossing)**
Power and ground have been tested on the main rail and all side rails and are reading
properly
External inputs (pushbuttons have been tested with a voltmeter and are sending the
proper inputs into the chip when activated. Note any errors and how they were solved.
External clocks have been tested and measured with the oscilloscope and input signal
is clocking and at desired frequency. Note any errors and how they were solved
External outputs have been tested by applying voltage or ground to actuate, to confirm
output paths are accurate (your LEDs aren‘t in backwards, etc.)
.
Transistors, Diodes, electrolytic caps have been confirmed via data sheets for proper
connection in the circuit. Note any errors and how they were solved.
42 Chapter 3 – Troubleshooting
Double check your chips that they are not in backwards and that all necessary power
and grounds have been applied. Note any errors and how they were solved.
Software Section
Write and compile your program, taking care to comment every line and put a clear
explanation of the program as well as your name in the title. Note any errors or
problems encountered and how they were solved
Transfer the program to the chip or board. Note any problems and how they were
solved
Run the program. Note any problems and how they were solved
Note any hardware changes and if they were implemented successfully or if not, what
was the problem and how did you solve it
Note any software changes here and if they were implemented successfully or if not
what was the problem and how did you solve it
Chapter 4 Basic Number Systems 43
Numbering Systems
Before we really get into PIC programming, we need to look at the following numbering
systems; binary, decimal, hexadecimal and ASCII. Pay attention, you will be using these
numbering systems for your entire career. You might as well memorize them all now.
1. Binary
Binary is the language of computers. A binary number as a base of 2 and can be
identified with that subscript. For example 10112. This means that its range of
numbers is 2. In this case those two numbers are 0 and 1. So the count is 0, 1, and then
there is a carry. You usually don‘t see it as just one digit however. Usually in groups of
2, 4, 8, 16 etc. In the table on the next page, the binary number is written in groups of
fours. When we are specifying a binary value in our program we would begin the
number with the letter B, like so B‘0010 1100‘
2. Decimal
Decimal is the numbering system we are most familiar with, Decimal numbers have a
base of 10, but don‘t usually carry a subscript in everyday life. However, when we are
dealing with a lot of different numbering systems we identify a decimal number by using
that subscript. So 96 in decimal would be 9610. In decimal we have the numbers from
0 – 9 before there is a carry. Then we start all over again. When we are specifying a
decimal value in our program we would begin the number with the letter D, like so
D‘124‘
3. Hexadecimal
Hexadecimal is also a language of computers. And it is less cumbersome than binary.
Hexadecimal has a base of 16 and can be identified with that subscript. Another way to
easily identify a Hex number is if you see that there is a letter in the number (from A –
44 Chapter 4 – Basic Number Systems
F). Having a base of 16 leaves you nowhere to go after you pass 9, so the letters A – F
are also incorporated into the Hex count. So the number C2 would appear as C216.
When we are specifying a hex value in our program we would begin the number with the
letter H, like so H ‗2C‘.
4. ASCII Code
And of course we must include the ASCII code which is the code we use to represent
numbers, letters and special characters. When we are specifying an ASCII code in our
program we will begin with the letter A, such as A‘@‘.
Chapter 4 Basic Number Systems 45
I have highlighted the first point of carry for each of the numbering systems below.
0000 0 0
+ 1 = 0001 1 1
+ 1 = 0010 2 2
+ 1 = 0011 3 3
+ 1 = 0100 4 4
+ 1 = 0101 5 5
+ 1 = 0110 6 6
+ 1 = 0111 7 7
+ 1 = 1000 8 8
+ 1 = 1001 9 9
+ 1 = 1010 10 A
+ 1 = 1011 11 B
+ 1 = 1100 12 C
+ 1 = 1101 13 D
+ 1 = 1110 14 E
+ 1 = 1111 15 F
+ 1 = 1 0000 16 10
When we are dealing with different number systems on a regular basis, we must be able to
convert between them quickly and easily.
46 Chapter 4 – Basic Number Systems
For this section we are going to focus on how to convert between numbering systems
Bit 27 26 25 24 23 22 21 20
To convert binary to decimal we simply spread the binary number out, look at the value
associated with each 1 and add the numbers together.
Bit 27 26 25 24 23 22 21 20
Bit 27 26 25 24 23 22 21 20
Binary Number to 1 1 1 0 1 1 1 0
convert
Numbers to add 128 64 32 8 4 2
together
Chapter 4 Basic Number Systems 47
Bit 27 26 25 24 23 22 21 20
Binary Number to
convert
Numbers to add
together
Using the above table, convert the following binary numbers to decimal.
a) 00112
b) 1010 01012
c) 1111 11112
d) 11002
e) 1011 11012
f) 10 11012
48 Chapter 4 – Basic Number Systems
Converting back is a little bit different. To convert from decimal to binary we have to
repeatedly divide by 2. We record a 0 when there is no remainder and a 1 when there is.
Our first number will be the LSB and our last the MSB. Let‘s take the number 56.
56 ÷ 2 = 28 no remainder so we record a 0 0
28 ÷ 2 = 14 no remainder so we record a 0 0
14 ÷ 2 = 7 no remainder so we record a 0 0
7 ÷ 2 = 3 with 1 R so we record a 1 1
3 ÷ 2 = 1 with 1 R so we record a 1 1
1 ÷ 2 = 0 (less than 1) with 1 R so we record a 1 1
The binary equivalent to 5610 is 1110002. If you want to prove it, just convert it back again using
the table we used earlier.
1 1 1 0 0 0
32 + 16 + 8 + 0 + 0 + 0 = 56
Convert the following decimal numbers to binary using the method shown above:
a) 12410
b) 8910
c) 4210
d) 9110
e) 24410
f) 18910
Chapter 4 Basic Number Systems 49
Converting from Binary to Hex is fairly easy. You divide your binary numbers into groups of 4
and just read the value. For instance 11110011 would be divided into:
1111 and 0011
Now you can either convert the value to decimal and then hex, or you can look it up in the table
below. After a while you will know all of the conversions and you will not have to look them
up.
0000 0 0
0001 1 1
0010 2 2
0011 3 3
0100 4 4
0101 5 5
0110 6 6
0111 7 7
1000 8 8
1001 9 9
1010 A 10
1011 B 11
1100 C 12
1101 D 13
1110 E 14
1111 F 15
Looking at the table, we know that the value of 1111 is 15 or F in hex and that the value 0011 is
3. Therefore the hex value is F3.
a) 1000 11012
b) 1011 00112
c) 10112
d) 1111 0011 11012
e) 0011 01012
f) 1010 10102
50 Chapter 4 – Basic Number Systems
From the table shown above we know that E = 1110 and that 2 = 0010. Therefore our binary
equivalent to E216 is 1110 00102. Familiarize yourself with this table you should know it by
heart in case its on a test or something.
a) C116
b) D316
c) 2416
d) 1516
e) AA16
f) 5516
Chapter 4 Basic Number Systems 51
a) F616
b) 3416
c) 2816
d) C216
e) 4D16
f) AA16
52 Chapter 4 – Basic Number Systems
Now this one does get a little tricky. You can do this conversion 1 of 2 ways. You can covert
to binary and then to hex from there or you can do straight conversion from decimal to
hexadecimal. You already know how to convert from decimal to binary and from binary to hex.
So we‘ll deal with the other possibility. We‘re back to division again, and very similar to the
decimal to binary conversion. Remember again that our first number will be our LSB (least
significant bit)
So our answer is 2D4. If we want to prove it, just convert back like we did before
2 x 256 + D x 16 + 4 x 1 = 512 + 208 + 4 = 72410
a) 42310
b) 6110
c) 9110
d) 21810
e) 102810
f) 506210
Chapter 4 Basic Number Systems 53
The columns are the MSBs (most significant bits) and the rows are the LSBs (least significant
bits)
LSBs MSBs
Converting from ASCII to binary is very simple if we have this table. Suppose we wanted to
type the letter g (small case). In this case we would look at the column where the g sits, which is
0110 and then at the row where g sits 0111 and put them together to get 0110 0111 or 6716.
What is the binary code and the hex code for the following:
a) 9
b) (
c) K
d) <
e) @
54 Chapter 4 – Basic Number Systems
Something you will need to understand when working with microprocessors or microcontrollers is
the concept of the complement.
The 2’s complement simply follows a basic math principle. That is, you can perform subtraction by
adding the inverse + 1 of the number to be subtracted instead.
Okay, now that I have you totally confused let’s look at it in a way this is more familiar to you.
The 1’s complement is what you would add to a number to reach the maximum value possible for
that number. of bits. It works the same for all of our numbering systems. Here is a simple table so
that you can refer to it in case you are not proficient in converting the basic numbering systems.
9910
-4410
5510
5510 is the one’s complement of 4410. When we add them together, we get the maximum
number for that number of bits. (9910)
Chapter 4 Basic Number Systems 55
a) 1 decimal place
b) 2 decimal places
c) 3 decimal places
d) 4 decimal places
2. Now that we understand that, what is the 1’s complement of the following decimal numbers?
a) 210
b) 3310
c) 65110
d) 324810
e) 796510
It works exactly the same in binary. We tell you to simply switch the 1’s for 0’s and 0’s for 1’s for
every bit. And that works because you are only dealing with a 1 or a 0, not 0 – 9 as in the decimal
numbering system. 1 IS the complement of 0 and 0 IS the complement of 1 in the binary system
But to perform the same action, we could take a number with 4 binary places (bits), use the
maximum number for that many bits and subtract from there.
Suppose we want the 1’s complement for 01102. By simply switching all the 1’s for 0’s and 0’s for
1’s we get 10012. What we are really doing is this:
In the answer key at the back of the book, I have shown the answers calculated through subtraction
of the max no. for that number of bits minus the number. But feel free to simply switch the 1’s for 0’s
and 0’s for 1’s when figuring out the 1’s complement for binary. It is much faster.
b) 0102
c) 01012
d) 101010102
e) 011110002
You can do the same thing with octal and hex, but I recommend you convert them to binary first,
perform the operation and then convert back. It is hard for us to perform mathematical
calculations in our heads in terms of base 8 or base 16.
I will show you with hex, octal you can work out on your own or see me if you want to learn it.
You wont be applying 1’s complements to octal in this course.
FF
-C2
3D
But when you are first starting, its hard to think in hex, so we’ll convert it to binary and work from
there.
1111 11112 (FF16)
a) C16
b) A216
c) 1F616
d) AA5516
Chapter 4 Basic Number Systems 57
The 2s complement is simply the 1’s complement + 1. This means that instead of adding up to the
maximum no. for that number of places, we are going to add one more number so that we can roll
over to the next number of places. Let’s go back to the decimal numbering system for a moment. We
already know that the 1’s complement of 4410 is 5510. The 2’s complement would be what we have
to add to 44 to rollover to the next number of decimal places, in this case to roll over to 100. So the
2s complement of 44 would be 56, because 56 would roll us over to 100. Or we can say that it is the
1’s complement + 1. 55 + 1 = 56.
5. What is the 2’s complement of the following decimal numbers? What do they roll over to?
a) 410
b) 1210
c) 26310
d) 762410
6. What is the 2’s complement for the following binary numbers? What do they roll over to?
a) 02
b) 102
c) 1102
d) 11012
7. What is the 2’s complement for the following hex numbers? What do they roll over to?
a) C16
b) DB16
c) 02 3D16
d) F6 7816
58 Chapter 4 – Basic Number Systems
Okay, so now you know what the 2’s complement is. It is simply the 1’s complement +1 OR the
number you need to add to a given number to make it roll over to the next number of places.
Okay big woopy doo. What does this mean and how do we relate it to subtraction??
Lets try the same problem but this time we will ADD the 2’s complement of the number we want to
subtract and then ignore the leading carried 1.
332 10
+ 879 10 2’s complement of 12110 = 99910 -12110 = 87810 + 1 = 879 10
1 211 10 We then drop the leading 1 and holy moly we have the same answer that
we got using direct subtraction.
66710
-44210
22510
66710
+ 55810
1 225 10 Drop the leading 1 and there we go again, the same answer as we got
using straight subtraction.
Chapter 4 Basic Number Systems 59
I know what you’re thinking. Couldn’t I just take a shortcut and subtract 44210 from 100010 to
get the 2’s complement. Absolutely!!!!
a) 410 –210
b) 3310 – 1110
c) 32810 – 66610
d) 153210 – 127410
a) 12–12
b) 102–012
c) 110 2– 0112
d) 10102 -00012
10. And finally, get your teeth into the hex problems:
a) A16 –616
b) BB16 – AA16
c) CD16 – 1216
d) 6416 -3D16
You have to admit this is pretty cool. But what possible use can it have in Micros??? Branching
!!!!!!!!!!!! Well I’ll let you in on a little secret. The Microprocessor doesn’t know how to subtract, it
can only add. So here’s what it does. Do you remember we told you that any 8 bit number with a
leading 1 is seen as negative? That negative bit tells the computer to ignore any 1 that is being
carried. So any number below 0111 1111 will be added as usual, but any number greater than or
equal to 1000 0000 will be added, but then the leading 1 ignored. That is how it differentiates
between a forward and a backward branch. I know that’s way toooo exciting, go sit down for awhile.
Let me know if you still are having trouble understanding the 2’s complement Answer Sheet:
Chapter 5 The PIC16F877A 61
Now I know this looks crazy, but we aren‘t going to be playing with all parts of the chip this
semester, You will get into much more detail next semester with this chip and C programming.
We‘ll start with the basics. What is the first thing you do with this chip? Every chip needs
power and ground and most of the time if something isn‘t working that is where you will find
your error, so powers and grounds have to be connected first. Let‘s look at those.
VSS is your ground. (Think source in a transistor) VSS is located at pins 12 and 31 so make
sure you tie those two pins to ground first.
VDD is power (Think drain in a transistor) VDD is located at pins 11 and 32, put both of those
at + 5 volts.
!MCLR or is the master clear or reset button and is located at pin 1. The bar over the top
or the exclamation point in front of the word means that it is active low. Active low means that
putting a ground on this pin turns it on. When this input is turned on (momentarily given a
ground), it resets the chip. But we don‘t want it turned on all the time or the chip will be
constantly held in a reset state and will not function. And we don‘t want any random grounds to
hit the input, making it reset arbitrarily. To take control of this input, we tie it to 5 volts. Most
of the time you will see hooked up to power through a resistor in parallel with a
pushbutton hooked up to ground (shown below). This keeps the pin tied high and yet allows us
to give it a ground (reset the chip) whenever we need to by pressing pushbutton. We will look
at that later.
Clock/Oscillator Inputs
These pins are important to understand because we will be using them right away. You can put
a few different things on these pins. Refer to the Oscillator Configurations section of your
16F877A data sheet under Course Documents as we go through the next part.
RC RC Network (Resistor/Capacitor)
XT Crystal Resonator
You will need to know these when we program as you have to specify which you are using in a
section called Configuration bits (we will go into more detail of this later)
This chip actually has 5 ports available to use with I/O. I/O refers to input output. This is where
we connect peripheral devices to either start a process (pushbutton) or to output to (a light,
motor). Any of the I/O ports can be set for input or output. We designate how we want it to be
set up when we initialize the chip through an instruction called TRIS. TRIS refers to the data
direction register for each port.
MOVLW b‘00001111‘
TRIS 06
The movlw/TRIS instruction combination moves the given value into the data direction register
for the specified port. In this case, we are moving the binary value 00001111 into the data
direction register for Port B (address 06 as shown below). Any 0‘s we include set a bit for
output. Any 1‘s we include set a bit for input. In this case we are setting the 8 bit register half
for output, half for input. Bits 7 – 4 are output, bits 3 – 0 are input. We don‘t have to use
binary either. We could have said:
In this case, without a letter designation in front, the default is hex. Whenever we use hex we
must put a 0 in front, especially if it was a value with a letter in front. That is if we wanted to
specify CF, we would have to use 0CF or it would give us an error.
It would just be silly. Using binary allows us to immediately visualize which bits are being set.
Once you get proficient as hex, you can use that just as quickly.
Examine the following problems and specify the bits for input, the bits for output and which port
we are trying to initialize.
1. MOVLW b‘10101111‘
TRIS 05
Input bits:
Output bits:
Chapter 5 The PIC16F877A 65
Port:
2. MOVLW 024
TRIS 07
Input bits:
Output bits:
Port:
3. MOVLW b‘10101010
TRIS 08
Input bits:
Output bits:
Port:
All I/O defaults to input on start up. This is a safety feature. Its better to have a random event
coming into the chip then one going out and actuating something like a motor or spot welder.
Port A can be found at address 05, has 6 bits and occupies pins 2 – 7
Port B can be found at address 06, has 8 bits and occupies pins 33 – 40
Port C can be found at address 07, has 8 bits and occupies pins 15 - 18 and 23 – 26
Port D can be found at address 08, has 4 bits and occupies pins 19 – 22
Port E can be found at address 09, has 3 bits and occupies pins 8 – 10
I have circled them in the illustration below. The address references can be found in the register
set table further down.
66 Chapter 5 – The PIC16F877A
When you are choosing which inputs and outputs you want to use, you can pick any that you
want. But pick ones that you won‘t want to use for another application.
For example, RB7 and RB6 (pins 39 and 40) are also used for inline serial programming. We
will get to that later, you don‘t have to worry about it now.
RB0 (pin 33) is the pin you use when you want to utilize an external interrupt.
RC1 and RC2 (pins 16 and 17) will be used when we utilize the internal PWM of our chip.
Chapter 5 The PIC16F877A 67
Register Set
The register set lists all of the different address registers that are available to your chip. What is
an address register? It is just a group of 8 bits basically, in some cases 16 that are set up to hold
information. You will also find a detailed description of each of these registers, whether they are
68 Chapter 5 – The PIC16F877A
read or write, how many bits they are and what instructions can be used to access them in your
chip data sheet. Take a moment and look over this part of the data sheet.
The register set can be divided into two types. They are SFRs or special function registers and
GPRs or General Purpose Registers.
Special Function Registers are registers that are already assigned a specific purpose. So any
register with an allocation in the previous table such as TMRO, PCL, STATUS, etc. would be
considered a special function register.
General Purpose Registers are yours to play with. You create your own registers here, your own
storage spaces. You can call them whatever you want and use them for whatever you want. You
can use any of the addresses assigned to the GPRs for this purpose. For example in Bank 0 you
can use addresses 20 – 7F for general purpose registers.
The registers are addressed with a hex value (hence the ‗h‘ after the address in the table)
Banks
You‘ll also notice in the table that each column is given a bank value shown at the bottom of the
table. The first column is bank 0, the second bank 1, etc. Bank 0 is the default, but if you need
to access a register in another bank, you will have to switch the bank you are in, in order to do
so. We will get to that in a little bit.
Chapter 5 The PIC16F877A 69
First lets examne the four register operation classifications listed on the instruction sheet.
Remember that our chip uses a 14 bit instruction opcode. Bits 15 and 14 are always set to zero.
That‘s why in the illustration above on the left all opcodes start at bit 13.
This category deals with bytes, (groups of 8 bits) at a given address. It looks at the entire
number in that address. With this group we must specify an address (indicated by the f variable)
as well as a destination (indicated by the d variable) or where to store a result of the operation.
This category deals with bits, these are individual bits within the given byte address. With this
group you must specify both an address (represented by the variable F in the table) and a bit
within that address (represented by b variable in the table)
Chapter 5 The PIC16F877A 71
This category deals with an actual literal value, not an address. With this group you specify the
actual value that you want to use.
CALL and GOTO are special instructions within the Literal and Control Operations category
that are treated slightly differently.
In order to really understand this table, let‘s take an instruction and follow it all the way across
the table.
Let‘s use the first instruction, ADDWF and try to understand what this table is telling us.
What does ADDWF represent? ADDWF is the mneumonic form of a machine code. We use
mneumonics to make programming easier. The basic machine code for any mneumonic
instruction, will be the fixed values in the 14-bit opcode column. So in this case, the 00 0111 is
the basic machine code for ADD. What are we told in the description of the ADDWF
instruction? We know that it takes the contents of W and f and adds them together. W is the
working register and f is a register that we specify. Let‘s use PortA as the file register address.
This has an address value of 05. This is a random address that I chose for this demonstration.
The letters after each instruction in the mneumonic, operand column represent the information
we need to put in the operand part of that instruction. These will be represented by the variables
in the 14-bit opcode instruction column. In this case we are looking at f and d. These values
will get plugged into the 14 bit opcode in the fourth column. To understand what f and d mean,
we will have to look at the specs for the classification that the ADDWF falls under. We see it is
a byte-orieneted file register operation, so lets look at how that is expressed.
ADDWF f,d
Our opcodes are all 14 bits, but since addresses are all 8 bits, our two most significant bits
(highest numbers) are useless. These are bits 15 and 14.
Bits 15 and 14 are always set to zero, so the first bit we look at is bit 13.
Bits 13 – 8 are fixed for ADDWF at 00 0111
Plugged into our 16 bit address that means our highest 8 bits are
0000 0111 which has a hex value of 07. Refer to the binary to hex conversion chart if you need
to or the illustration below if that is helpful.
Bit 7 will choose our destination. We can choose to send the sum back to the working register
with a 0 or to the address for PortA (05) if we enter a 1 We will choose to send it to the working
register. Which means we enter a value of 0 for bit 7
Bits 6 – 0 will be the 7 bits of our file register address. This will translate to 000 0101 this. I
know that Port A is 05 which is 0000 0101 but we are going to ignore the MSB in this case as it
is reserved for the destination bit designation.
That is the MACHINE CODE for ANDWF. The CPU converts all of our programming
mneumonics into machine code in order to execute it. And this would be the machine code
instruction if we wanted to add the contents of the working register with the contents of PortA
and store the sum back into the working register.
Chapter 5 The PIC16F877A 73
Working Register
We‘ve made references to a working register but havent really explained what it is, so I‘ll do that
right now. The Working Register is where everything goes before it can go anywhere. The
working register is like a boat. You have to get on the boat if you want to go to any other port.
(We‘ll assume you can‘t swim here of course) If you want to load anything into any address
you must first load that value into the working register and then transfer it to the file register you
want to go to.
The MOVLW instruction provides a great illustration here. It is quite often the first line of a
program. This instruction tells us to moves a literal or actual value (L) into the working register.
(W)
The MOVLW instruction is most often followed by a MOVWF instruction, which directs us to
move the contents of the working register (W) into an address. (F)
There is no MOVLF. You cannot move a literal value directly into a file register and there is no
MOVFF,, you cannot move the contents of a file register directly into another file register. You
MUST go through the working register first.
For those of you from a microprocessor background, the working register would be equivalent to
the accumulator.
Cycles
Now for the cycles column. This refers to how many instruction cycles are required to execute
the instruction. In the majority of cases it is just 1. But there are exceptions as you can see, most
commonly the CALL and GOTO commands.
Instruction cycles should not be confused with clock cycles Our chip is a divide by 4 so there
are 4 clock cycles for every 1 instruction cycle. Most instructions have 4 clock cycles except for
CALL and GOTO which of course would have 8.
Back to our ADDWF instruction, we see that there is 1 instruction cycle and so if we multiply
that by 4 to get the clock cycles, we end up with 4 clock cycles.
Status Affected
This column refers to what bits of the status register can be affected by that particular instruction.
The Status Register itself tells you what is going on at any given time in terms of the working
register. The Status Register can be found at address 03 for Bank 0 and its bits are as follows:
The Status Register reflects the present state of the ALU (Arithmetic Logic Unit) which
processes everything. The Status bits that can be affected for this particular instruction are bits 2,
1, and 0. These are the Zero bit (which sets if the result of an operation is zero), the DC bit
(which sets if there has been a carry from the 4th low order bit), and the C bit (which sets if there
has been a carry from the MSB)
We will get more into the Status Register later on, but enough to say that this register basically
gives us an overview of what is going on at the moment in the ALU.
Assembler Directives
Assembler Directives are instructions not found in the general instruction set. They do not need
to be decoded, they are read as they are.
Chapter 5 The PIC16F877A 75
END
This is the most common assembler directive and must be found at the end of every program.
EQU
This is the second most common assembler directive. We will get to this later, but basically
EQU stands for equate and allows you to give an address or bit number a name so that you can
use that name throughout your program instead of a number. It makes programming so much
easier to understand
Include
You might want to use this when you want to add a header or linker file in our program. The
header file in our program basically lists all of the special function registers and equates them
with their address, so you can refer to them by name instead of address.
Processor
You can use this directive to specify the processor you are using. For example P16F877A
ORG
Org is for origin an specifies the starting point of your program. You might not use it much, the
default origin is 0000. So unless you wish to start your program at a different address, there is
no need to use it.
__Config
You probably will use this in your programming. It specifies the configuration bits you will be
using. We will get to those later.
Macro…Endm
The Macro directive basically lets you set up your own subroutine which is treated as a self-
contained instruction when you refer to it.
List
Allows you to list certain properties of your program such as number of columns, lines per page,
processor type, that sort of thing
Page
76 Chapter 5 – The PIC16F877A
and
Title
Gives your program a title
Chapter 5 The PIC16F877A 77
We won‘t be writing our programs in machine code, but you will come across them. You will be
using a program called the PICKIT2 to transfer your programs to your chip. When the program
comes up, you will be able to view the machine code. Understanding it takes the mystery and
confusion out of this screen.
I‘ve attached an example below. You see on the top line is the machine code for this particular
program.
We‘ve already looked at a byte oriented instruction in the ADDWF and what the machine code
would be if we performed the operation on the working register and PORTA and then stored the
value in the working register.
78 Chapter 5 – The PIC16F877A
Lets try one from another category, from the Literal and Control Operations classification. Refer
to the tables on pages 53 and 54 if you need to.
MOVLW which we already touched on is most commonly the first instruction in an assembly
program.
In order to figure this out, we must first ask what kind of instruction MOVLW is so that we can
look at the proper 14-bit opcode format. Refer to Table 7.2 of the PIC data sheet on the next
page. Under what heading do you find the MOVLW instruction? We find it under Literal and
Control Operations (General) Format. Now we refer back to Figure 7.1 on the previous page and
we see the breakdown for this instruction. Under the Literal and Control Operations (General)
Format, bits 13-8 are the code for the actual instruction (opcode) and bits 7-0 are the numbers
or address they are referring to (operand).
To be even more specific we can refer to the instruction sheet which looks even more closely at
the instructions, bit by bit. I have included the one for MOVLW below.
So how do we figure out the hex code from this?? Pretending for a moment that we have 16
bits, lets break down the numbers. As we said before, our pic has a 14 bit opcode, so bits 15 and
14 don‘t exist, they are simply read as 0‘s. Bits 13 – 8 are the fixed opcode for the MOV part
of the MOVLW instruction. The two x‘s are don‘t cares and if you look at the table on page 54
you will see that we plug in the value of 0 into don‘t care spots. That gives us an opcode value
of 0011 0000 or 30 for the first 8 bits. The k in the operands part of the mneumonic operand
column says that we need to provide a literal value for bits 7 – 0. Lets just use the value 00 since
this is often the case at this point.
As you can see, that is pretty straightforward for the MOVLW instruction.
Chapter 5 The PIC16F877A 79
There are two variation of the Literal and Control Operations. They are GOTO and CALL. Lets
have a quick look at GOTO.
As you can see, the fixed opcode for the GOTO is 0010 1. The next three bits will be 0s leavin
us with 0010 1000 or 28. Now lets give it an address. Lets give it the address 03 or 0000 0011
(this is the address of the Status Register) I just chose it at random. So if we wanted to GOTO
address 03, our machine code would be 2803.
Lets look at an example of a bit-oriented operation. These are for testing bits mostly. We‘ll look
at the BCF. This instruction clears a bit in a given address.
80 Chapter 5 – The PIC16F877A
The fixed part of the machine code for the BCF are bits 15 -10 which are 0001 00.
Bits 9 – 7 specify the bit in binary and bits 6 – 0 specify the address where the bit can be found.
So if we wanted to clear bit 7 (binary 111) at PortB, (address 06), we would enter the following
information:
Referring to Table 7-2 and Figure 7.1 and assume a machine code of 158C. In the illustration
below, show how the 14 bit opcode is divided up and designated for this instruction. Fill in the
hex code.
Which of the 4 14-bit opcode formats will we be using here?? Referring to Table 7.2 and then
on to Figure 7.1 as with the previous example, we discover that we will be using the byte
oriented format. In this case we divide up a little differently.
Chapter 5 The PIC16F877A 81
The CLRF instruction is telling us to clear everything out of address 06 (portb). As you can see
from the CLRF line from the instruction set, the CLRF opcode has a value of 01 for the first 8
bits. Bit 7 determines whether we are referring to the working register or whether we are
referring to another address (f register) Since we are going to be giving it an address and not the
working register, bit 7 will be set to the value of 1, and we are writing to address 06 which
gives this instruction a machine code of 0186.
Memory Map
The memory map tells you where everything is stored.
You will see a diagram with the physical pinouts listed (shown below) and later a more detailed
chart of the significance of each of the pins. This will help you know exactly what your chip
can do and of course is absolutely essential when it comes to wiring a circuit.
Your first lab will be the simulation lab in the MPLAB Getting Started Guide Chapter 2
(Available under Course Documents on blackboard). I have chosen this lab to give you a
practical application in which to play around with software in a step by step guided way.
There‘s no better way to get familiar with a software than to use. Don‘t worry if you don‘t
understand everything as you go. Look up what you can.
http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1406&dDocNa
me=en019469&part=SW007002
or you can just do a search for MPLAB download and pick the microchip site that comes up and
go to the bottom of that page. Right now we are using version 8.5. It may have changed since
then.
Follow the tutorial in Chapter 2 of the MPLab Getting Started Guide that I have included in
Course Documents. If you cannot file any of the necessary inc or header files files, check under
Course Documents I have put copies there as well. We will only be simulating this tutorial, we
will not be downloading it to the board so you can do this at home although it must be
demonstrated in the lab for a sign-off. Go ahead and follow all of the instructions as given with
the chip they have specified. This SHOULD work if done properly, let me know if you have
any difficulty. The last step should be the stopwatch.
Chapter 6 On to Real Circuits 87
In order to do your flowchart you will have to completely understand what is happening here and
be able to follow the flow all the way through. That means you will have to read through both
parts A and B before you begin. We‘ll work on the first one together, the rest you should be
able to do on your own. Of course let me know if you are experiencing difficulty.
88 Chapter 6 – On to Real Circuits
How are we going to do it? Let‘s look ahead at our program. Remember we are not writing our
program yet, just understanding the problem.
The first two lines in this program you have seen before. We are loading the data direction for
Port b (address 06) with all 0‘s. So we are setting Port B for all outputs. This will allow us to
view our light on RB7. After all RB7 has to be an output for us to send a signal to it. We could
have just set the 7th bit and loaded 80 instead of 00, but we‘ll get to that later.
Then we turn RB7 off (again the length of time is determined by our RC network)
So the flowchart for our first program should look something like this:
You will notice that in our flowchart we use an END terminal block even though this program
will repeat forever. We simply didn‘t attach it to the end of the flowchart.
90 Chapter 6 – On to Real Circuits
Fill in the hardware part of your documentation as you go. Don‘t forget to describe the purpose
of this lab and what you expect to see when it is complete if it is working properly.
Wire up the following circuit on your breadboard. Make sure you follow the rules. Black for
ground, Red for powe. These colours are not to be used anywhere else in the circuit, all wires
and components tight to the board for easy troubleshooting. Mark the chip number on the chip in
the illustration below and mark the pinouts (both number and function) that we are using and
note why they are connected where they are. (They are in this workbook and on the 16F877A
datasheet under Course Documents).
Chapter 6 On to Real Circuits 91
*** Remember that an arc over a line means the two crossing lines are NOT connected***
A straight line with a dot means that the two crossing lines ARE connected
When you are done, your labeled bins should look like this:
As I said earlier, many of the pins have multi-functions. I will only go into the details of the
functions we will be using for now. We will go into more details later on as we use them.
Pin 1 is the Master Clear for the chip. The line above it is a NOT, meaning that this pin becomes
a master clear when it is grounded or low. In order for the chip to function it must be tied high.
It will reset every time it is given a low. To facilitate this, we have tied it to 5 volts via a 10 K
resistor. We have also attached a pushbutton, connected to ground which will provide a ground
and clear or reset the chip each time it is pressed.
92 Chapter 6 – On to Real Circuits
Pins 11 and 32 are + 5 volts and pins 12 and 31 are ground. Every time we hook up a chip, we
connect power and ground pins first. Why? Because they are the easiest to forget. But that‘s
okay if you don‘t believe me now, you will.
Pin 13 is a Clock Input. We are providing a clock input via an RC network made up of a 4.7
KΩ resistor and a 10 µf capacitor. Remember your RC time constant from AC?
Finally pin 40 is our output pin. We are using bit 7 of Port B and an LED to provide our visual
output. This particular chip has 5 different ports available for I/O. (Ports A – E) We will go
into more details about the others later.
Here it is wired up for you below. Note how all grounds are black, powers are red and
everything else is tight to the board and easy to follow. Bring 5 volts to the board, using the
fixed 5 volts on your power supply if it offers one.
.
Before we enter our program, let‘s verify our hardware.
Hook your voltmeter up between the positive and negative side of the main rail and make sure
you have 5 volts.
Chapter 6 On to Real Circuits 93
Now measure all of the vertical rails and make sure you have power coming in there.
With your black lead on ground, check your VDD pins for + 5 volts and your VSS pins for 0
volts.
Next let‘s test our master clear set up. Place your red lead on pin 1 (master clear input) and your
black lead on ground. Look at the voltmeter.
94 Chapter 6 – On to Real Circuits
Now press the button. It should change to zero. This simulates us resetting the chip.
Perfect. If it doesn‘t work check the wiring, you probably have a wire in the wrong hole.
Chapter 6 On to Real Circuits 95
Next we can test is our clock input. Turn on your oscilloscope and hook it up between the clock
input and ground.
Turn on your scope and adjust the settings so that you have a nice clear picture of the wave with
only two or three full waves on the scope screen.
Let‘s back up one minute and look at our RC network here. We have a 10 µf capacitor and a 4.7
KΩ resistor. What are the time and the frequency?
Well if you remember, time is R x C. so our time is 4700 x .00001 or .047 seconds.
And frequency is the inverse of that, so our frequency is 1/ .047 or 21.23 Hz.
Calculate the frequency of the wave on your screen by multiplying the number of squares by the
time/division setting and taking the inverse.
Take the value and calculate the RC constant and frequency you would expect to see.
RC constant _______________
Now substitute the 2.7 KΩ resistor with a 10 KΩ potentiometer. It will hook up as shown
below.
Chapter 6 On to Real Circuits 97
Keeping the scope hooked up, what is the frequency when the pot is all the way counter-
clockwise?
_____________________________
What is the frequency when the pot is turned all the way clockwise?
_____________________________
_____________________________
Remove the 10 KΩ potentiometer and put the 4.7 KΩ resistor back in the circuit. Now that
you‘ve had a little review of the RC time constant let‘s get back to our circuit.
Finally, let‘s test our PB7 line from pin 40. Simply apply 5 volts to pin 40. This will simulate
an output from that pin. The LED should come on. This tells you that the line from RB7 to
ground is good. If your LED turns on, you can be assured that it is not in backwards and that all
of the rest of your wires in that sequence are hooked up in the right places.
98 Chapter 6 – On to Real Circuits
You have just verified that your physical circuit is working and that all of your connections are
good. If they weren‘t I‘m assuming you have fixed them. Or if you haven‘t yet, make sure the
circuit is working as it should before you move on.
This has already removed wiring as one of your issues in case your circuit does not work
properly after programming your chip. And makes troubleshooting a gazillion yes I said a
gazillion times easier.
You can have the hardware portion of this lab signed off by verifying that the is working,
the LED is working and that you do indeed have a clock pulse coming in. Make sure that all
hardware sections are filled in on your documentation sheet and be prepared to explain each pin
and its purpose in this circuit.
Create a folder on your N drive called Single Blinking Light or something like that. You will
need to create a new folder for every program you create. If you drop a bunch in the same
folder it could screw up your programs when you try to run them.
Enter the program as shown below, making sure you enter your own name etc in the information
section.
Save it into the Blinking Light folder you created. Make sure you save as type All Files and that
you put the extension .asm on the file as shown below.
100 Chapter 6 – On to Real Circuits
Now, find the .INC (include) file for our chip and drop it in this folder. Notice the path at the
top of the screen below. It should be on your C drive under Program Files and follow the path
shown in the address window below. We won‘t be using it this time, however we will be using it
a lot later and it‘s a good habit to get into. So always drop a copy of it into your new folder .
If for some reason it isn‘t there I always put a copy of it under Course Documents.
Now onto MPLAB. Find MPLAB through the Start and Programs Menu. It won‘t simply be on
your desktop unless you are doing it from home.
Chapter 6 On to Real Circuits 101
Click on it. When it comes up, go to the Project men and select Project Wizard.
If you don‘t see the above option, you accidentally installed the HI TECH I told you not to
install. Uninstall the program and install it again making sure not to select it this time.
When it first comes up it will have a big letter A beside it. Click on that letter three times until it
turns into a C as shown below. Then select Next.
Chapter 6 On to Real Circuits 105
In case you are wondering what each of these letters that come up mean, the are File Addition
Modes. I have included a brief description of them here.
A stands for Auto mode. It lets the program decide whether the path should be relative or
absolute. Relative means that the file you are referring to is already in your project folder. If it
is not it will choose Absolute mode.
S stands for system. For example if you wanted to refer to the include file in the microchip
directory you could use an S here and simply refer back.
C is for copy. This will copy a project file to your directory. It defaults to relative path. You
can also rename the file name as you include it.
If you double click on the .asm file, it will come up in the window for you. Do that now.
The following screen will come up. When it does, uncheck the little check box at the top that
says Configuration Bits set in code. And OK when the alert screen comes up.
Change the configuration bits as shown below. Make sure you have the value 3F73. Once you
do, recheck the box.
Configuration bits
108 Chapter 6 – On to Real Circuits
If you are familiar with C programming configuration bits are the same as fuses. They are a
series of settings you select to specify how your chip is read, etc. In case you are wondering
where the 3F73 value comes from when looking at this selection, look below. I have highlighted
our desired selections, let me know if you have any questions.
Before we continue, lets go over each of the bits and what they mean in detail.
Bit 13 is your code protect. When it is enabled you cannot retrieve anything from your chip. It
is to protect you from someone trying to steal your program. Unfortunately for us we are
constantly rewriting our programs so that isn‘t very practical. You will want to set this bit to 1
and turn code protect off.
If you want to do in line programming (programming while your chip is in its circuit), you would set this bit to 0. This
would be choosing PGD on pin 40 (instead of RB7) and PGC on pin 39 (instead of RB6). These are the two
communication pins you need to perform in circuit programming. If you want to use this pins as general outputs, set
this bit to 1.
Here are the various categories of write protection. We will turn it off.
We enable this bit if we are going to do in circuit serial programming (ICSP). We are not, so set
it to 0.
The BOREN config bit should be disabled. The BOREN bit resets the chip if the voltage falls below its minimum
value.
110 Chapter 6 – On to Real Circuits
The power up timer allows for a small spike on start up without tripping anything. You will definitely want to enable
this bit.
The watchdog timer resets the chip in case it hangs. For our purposes in these labs, it is little more than an
annoyance although it does have its place. Make sure you disable it. If you find that your chip is resetting or looping
when you didn’t want it to, check this bit.
These bits choose your oscillator type. We will be using either an RC network (11) or a HS 20 MHz crystal (HS 10)
for our labs.
Okay, now that we’ve gone over all the secrets of the universe, here below I have summarized our settings.
Chapter 6 On to Real Circuits 111
Remember, bits 15 and 14 are ALWAYS set to zero as this PIC has a 14 not a 16 bit opcode.
We make our selections as to what we want enabled/disabled in the chart above and then enter it
into a table as shown below. Once we have done that, we divide it in groups of 4 and simply
read it as a series of hex values. We end up with 3 F 7 3.
Let me know if you have any questions about configuration bits. You can find more information
in the data sheet and even more information if you search online for these settings.
112 Chapter 6 – On to Real Circuits
If you are having problems understanding it, it‘s only because you are making it more
complicated than it is.
Once we have the configuration bits set, we want to compile the program. In this software it‘s a
Build All command.
The following Output screen should appear, and should end with BUILD SUCCEEDED. If it
doesn‘t, you will see an error somewhere in there. Click on it and it will take you to the line
where the error exists. Most likely it‘s a typo.
Make sure your PIC Programmer is plugged in and the green light is on. Using your IC Puller,
remove your 16F877A chip from the circuit and put it into the 40 pin zif (zero insertion force)
socket on the programmer. Lock it into place with the little green lever. You must put it in the
programmer in order to send your program to the chip. After it has been programmed you pull it
back out and put it in your circuit.
Locate the PICkit 2 software in the Start Menu Program Tree and click on it.
If you get this error, you forgot to put your PIC chip in, so do that now.
Try again.
Once it is successful, click on the Write button. You should see a Programming Successful
message.
118 Chapter 6 – On to Real Circuits
Then Verify.
Remove the chip from the programmer and put it into your circuits, making sure it is in the right
way. (The dot is always pin 1)
You should see the LED flashing. The rate of on and off time can be calculated by the RC time
constant (remember AC?) The Capacitor is 10 µf , the resistor value is 4.7 KΩ.
If you don‘t see the LED light flashing, the only HARDWARE problem it could be, resides with
the PIC chip itself since we already eliminated everything else:
Chapter 6 On to Real Circuits 119
Hardware Problems
The PIC chip is in the wrong way or not snug enough for contact
The PIC chip has physically malfunctioned and is not sending out the signal
Software possibilities
The output is not receiving a signal from the PIC chip due to an error in the program.
Let‘s assume that the LED is not flashing (even if it is) and continue with the next steps.
Out of all the possibilities we listed above, the quickest and easiest to check is if the PIC chip is
sending a signal to the output. We can measure this on the RB7 pin. Hook up your scope or
voltmeter and see if it is pulsing.
The voltage level should be changing fairly quickly between 0 and 5 volts.
Is it? __________________________
If it is, then apply +5 volts to pin 40 again and see if it is turning on the LED.
We‘ll assume that it isn‘t. Remove power from your circuit. THIS IS IMPORTANT. If you
remove your PIC chip while the circuit is powered it will fry the chip. You don‘t want that.
Before you take your PIC chip out of the circuit, check to see that the dot on the chip is sitting
where Pin 1 is on the chip. (The master clear pin). If not then it is upside down. Using your IC
Puller, pull it out, turn it around and try again. If it doesn‘t work, try pushing the chip further
into the board if it isn‘t snug enough.
Remove your PIC chip from the circuit and put it back in the programmer. Lock it down. Open
PICkit 2 and this time read the chip. Is it able to read? Is that your proper code?
Try loading the hex file and programming it again and try it in the circuit again.
Last but not least, try another PIC chip (and you should always make sure you have at least two
on hand).
Once it is all working, you may have the software portion of this lab signed off. Prepare to
demonstrate any of the above steps used. Don‘t forget your documentation and flowchart.
120 Chapter 6 – On to Real Circuits
If you notice the comments in this program, you will see that every line is fairly easy to follow in
terms of what it means and what is happening. Comments are extremely important as you will
see shortly. Also, the goto line in this program. As you can see we specify a line to go to at
three points in the program. To figure out which line we want to go to, we have to count the
lines of code. Only the lines with instructions on them and starting from 0. This can be a real
pain. Shortly I will show you how to use labels and it will make this process much easier.
You will notice we have introduced the instructions btfsc and btfss, these simply test the given
bit in the given register to see if they are set or cleared. When we push a button, we ground it out
(clear it) So the first instruction on line 29 is checking to see if the button has been pressed.
When we have not pushed a button or have released it, it is set (high) if you look at the circuit
you can see it is tied to 5 volts unless we ground it out by pressing it. So online 32 we are
checking to see if it has been released.
Look up any instructions you don‘t understand in the data sheet for the 16F877A available on
Course Documents. Let me know if you are having any problems understanding anything.
122 Chapter 6 – On to Real Circuits
Lab 4 – Relays
First of all , what is a relay? There are two main types, electro-mechanical and solid state.
A relay consists of a coil and some auxiliary contacts. In the diagram below, you can see that
there are two poles. Pole 1 and Pole 2. Each of these poles has a common (Pin 9 and Pin 12), a
NO contact and a NC contact. Some relays have only one pole, others can have three or four.
When power is applied to the coil and it is energized, the contact that is connected to the
common switches position. Meaning whatever was open is now closed and whatever was closed
is now open.
If we want a closer view of the process, let‘s look at what is happening on the first pole.
Chapter 6 On to Real Circuits 123
So when the coil is energized, anything connected across pins 9 and 5 will turn on, while anything
connected across pins 9 and 1 will turn off.
You may be wondering why we would bother with a relay when we can just directly wire to our
output. Very good question. Apart from adding flexibility to a circuit, which the relay does by
offering a) multiple poles meaning that many different components can be hooked up to one relay
and b) auxiliary contacts in NC and NO conditions, meaning that we can turn things off and on on
the same pole at the same time, the relay also allows us to use different voltages for our outputs.
It is important to remember that all the coil does is switch the contacts. It does not power whatever is
on them. They need an external power supply. If you look at the diagram below, you will see that
our relay requires 24 volts to energize the coil. The two poles however, the motor and the light
require 120 V and 12 V respectively. The poles must be externally energized. They will not be
energized from the coil.
124 Chapter 6 – On to Real Circuits
Chapter 6 On to Real Circuits 125
Now we come to the solid state relay. The solid state relay is a little different.
The Solid State relay only mimics the action taken by the electro-mechanical relay. It does this
through an electronic circuit rather than an actual coil and physical contacts that open and close.
The solid state relay ‗coil‘ is made up of an opto-isolator and a transistor (either a TRIAC an
SCR or a FET).
As you can see in the diagram below, when 3 and 4 become ‗energized‘ the opto-isolator
transmits a signal to the transistors that connect to 1 and 2. This closes that side of the circuit,
energizing whatever is on there. Unlike the electro-mechanical relay, solid state relays usually
have only one contact and it is usually NO although other kinds are available. IN the following
illustration we have four pins. Pin 4 is the input (the output from your PIC circuit or PB7). Pin 3
goes to power through a diode (shown next page). Pin 1 is + voltage, Pin 2 is negative voltage
(power and ground for us). You can put your load on pin 1 or pin 2 depending on whether you
want it to go to power or ground. We will be using a simple LED, so we will be putting it on pin
2. The power applied to pin 1 (+VDC) will be whatever you need to energize your component.
You‘re probably wondering what the difference is between an electro-mechanical relay and a
solid state relay.
Although SSRs are not sensitive to vibration, physical shock or altitude, they are especially
susceptible to heat. This is because as a semiconductive component, they are never truly off just
in a holding state. To combat this, you will almost always find an SSR with a heat sink.
In applications that require little noise or electrical interference, the solid state relay (SSR) is a
better choice such as electronic circuits. However if heavy surge currents or spike voltages are
anticipated or known to occur, such as in many industrial applications, use an EMR.
126 Chapter 6 – On to Real Circuits
Both types of relays have incredibly long lives. When a SSR fails (and they rarely do) it is
usually due to a short in the contacts. When an EMR fails, it is usually due to the coil shorting
out although often contacts can get welded together as a result of arcing.
So what we are going to do for this lab is take the flashing LED light lab (2a/b) and modify it as
shown on the following page. You do not have to change the program in any way.
You will notice that, in addition to the electro-mechanical relay, we have also added a diode and
a resistor. This is to prevent feedback from damaging the relay. Remember with relays that
diodes are your friend. This is especially true when dealing with motors.
Look up the relay that is included in your kit, is it solid state or electro-mechanical? Look up the
pinouts and connections on that data sheet and hook it up accordingly. I have given an example
of each type below.
Chapter 6 On to Real Circuits 127
128 Chapter 6 – On to Real Circuits
Once you have it blinking just like with the last lab, you may have it signed off. Don‘t forget
your documentation. You will need it for troubleshooting purposes.
Chapter 6 On to Real Circuits 129
The purpose of this lab is to illustrate that by using a relay, we create flexibility in terms of the
voltage levels of our outputs.
.
Don‘t forget your documentation and flowchart.
130 Chapter 6 – On to Real Circuits
Build the circuit shown below. Don‘t forget to write the chip number and all of the pinouts on
the circuit schematic below. Test your hardware before moving on to the software portion as we
did last time filling in your program documentation. Don‘t forget your flowchart.
If you‘ll notice in the picture below, I have used a resitor network (SIP) instead of individual
resistors for this circuit. This resistor network has one common pin and 9 220 ohm resistors. If
you are setting up a circuit where one side of the resistors is all going to power or to ground then
you can use this network. It makes things so much easier. But NOT if they are not all going to
power or ground on one side.
Chapter 6 On to Real Circuits 131
SIPS come as isolated resistors, that would mean a common and resistor on every two pins. Or
a bussed resistor which is one common and however many resistors per other pins. We are using
a bussed resistor. Pin 1 is the common and all of the other pins are 220 ohm resistors.
132 Chapter 6 – On to Real Circuits
Okay before we get into the software portion of this lab, let‘s talk a little bit about how your
program should appear. There are four columns in a standard assembly program.
The first column contains labels and equates, don‘t worry we‘re about to get to those.
The second column contains your instruction mneumonics as you have seen. These are
instructions like MOVLW, TRISB, MOVWF, etc
The third column contains your operands which you have also seen. This can be a literal value
or an address. If the instruction before it contained an L for literal, the value will be a literal
value. If the instruction before it contained an F, the value will be an address.
The fourth column contains your comments, always marked by a semicolon. The semicolon tells
the processor to ignore whatever appears next on that line. These are notes you make to yourself
explaining the program. The clearer your comments are, the easier it will be for you to come
back to this program later or for someone else to help you troubleshoot it.
If you put something in the wrong column, you will get a warning when your program is
building. Not an error, just a warning. You should pay attention to warnings, but only errors
will result in a Build Failed message.
Here is the main body of the flashing binary counter program with equates. Make sure that when
you do your program you include a title and description of what the program is supposed to be
doing.
Chapter 6 On to Real Circuits 133
Equates
An equate lets you specify a value or an address for a specific term so that whenever you use that
term, the CPU will go to whatever value or address you specified.
PORTB EQU 06 which means that every time we read PORTB we will be telling the
CPU to go to address 06
Labels
As for labels, if we give a line a label, we can go back to it with a goto command. It‘s great for
looping.
Instead of goto and a line number (03) which we used in our last program, we can use goto
Repeat and put that label on the line we want to go back to. The advantage of this is that if you
end up adding more lines to your program, you don‘t have to recalculate which line to go back to
every time, it will simply find the line that is labeled Repeat on it.
134 Chapter 6 – On to Real Circuits
Open up a new folder on your N drive and call it Lab 3 Flashing Binary Counter something to
define what it is. Type this program into notepad and save with an .asm extension, then drop it
in the folder.
Open MPLAB, project wizard, la la la la and set the config bits for 3F73 just like last time.
Perform a Build All on the program.
Well if you entered it exactly the way I had it, you got a Build Failed error. The message
Symbol not previously defined is referring to a simple typo. If you click on that line it will bring
you to the error as shown by the little blue mark below.
Chapter 6 On to Real Circuits 135
If you notice, PORTB is all in caps on the equate line, and in lower case where the blue arrow
appears Typos and case differences like this will drive you nuts but they are the most common
error. Errors that are caught during the build by the assembler are called syntax errors. Usually
typos, punctuation, or things not being where they are supposed to be (include and header files)
etc. The other type of error is a logic error. With a logic error, the program will probably build
fine but when you run it, it does not do what you expected due to a mistake in your program.
So fix the error, you can make them both lower case or capital so long as they are the same and
build again.
And this time it was just perfect. Or if not, click on the line where the error is and try and figure
out what it is.
But finally it will run perfect. Before we move over to the PIC Programmer, let‘s use MPLABs
simulation to see just how this program performs.
To open up the Simulator go to the Debugger on the Menu bar and select MPLAB SIM.
136 Chapter 6 – On to Real Circuits
Once you do, you will notice that MPLAB SIM appears on the bottom left hand side of your
window and another toolbar pops up.
They are in order, run, stop, fast forward, step through, step over, step out of, reset and break.
You already played around with some of these in the simulation lab.
Now that we have the simulation software open, let‘s target some registers to watch as we step
through the program.
Chapter 6 On to Real Circuits 137
Select PORTB and then click on the Add SFR button. It will appear as shown below.
Okay
Click on Step Into to start advancing through the program step by stepl
Each time you press it, it will advance to the next step. Keep an eye on the Watch window to see
when the value of PORTB changes. TRISB should remain the same as 00 since that is what you
set it as. Once it hits the Repeat, it should just keep repeating those two lines forever and your
PORTB should keep accumulating.
Chapter 6 On to Real Circuits 139
Let‘s talk a little bit about TRIS. We touched on it in the last chapter, but let‘s go into a little
more detail now. TRIS is not a regular instruction in the instruction set for your chip. TRIS is
the data direction register for your ports. There is a TRIS for every I/O register, that adds 80 to
the original address of the PORT as shown below.
TRIS has a little routine. This instruction says, take the value that is in the working register and
put it in the data direction register for the following port.
MOVLW 00
TRIS 06
We are telling the CPU to take the literal value of 00 and put it into the data direction register for
PORTB, which is address 86h.
140 Chapter 6 – On to Real Circuits
Setting a value of 00 (0000 0000) sets PORTB for all outputs. If we set it for FF (1111 1111) we
would be setting it for all inputs. We could also set a combination. If we set it at A5 (1010
0101) we would be setting bits 0,2,4, and 6 for inputs and bits 1,3,5,7 for outputs. Remember a
0 is like an O for output and a 1 is like an I for input. And of course all ports default to all inputs
on start up for safety reasons.
After going through the simulation, are you confident that your program will work on the chip?
You should have already tested your hardware and now your software, what could go wrong?
Export the hex file from MPLAB, import it into PICKit2, program the chip and place it in your
circuit. Once it is running you may have this lab signed off. Make sure you have filled in all
of the documentation and created your flowchart for this lab and that you can explain every part
of the program..
Chapter 7 Logic In Action/ Indexed Addressing 141
Below you will see your three basic logic gates. As you may or may not know, logic gates are
binary in nature. That is any inputs to the gate will either be a 1 or 0. And any outputs will also
be a 1 or a 0. The logic is expressed in terms of an algebraic equation using Boolean Algebra.
You will learn this in detail in your digital course. Boolean equations use letters to denote inputs
and outputs. The AND, OR and NOT gates are your basic gates. Everything else is just a
combination of them.
AND
142 Chapter 7 –Logic In Action/ Indexed Addressing
OR
NOT
Chapter 7 Logic In Action/ Indexed Addressing 143
The AND gate performs an arithmetic function. That is, the two inputs are multiplied together.
The Boolean equation is X = AB , equivalent to X = A x B. If either input is a 0, the output is
a 0 because anything multiplied by 0 is 0. The only way we can get a 1 output is if both inputs
are 1. In this case we can say that for an AND gate, 0 has control. If a 0 appears on either input,
the output will be a 0 (because anything multiplied by 0 = 0)
Now if we were to us this logic instruction in a PIC program, we would use one of two possible
instructions. They are ANDLW and ANDWF
ANDLW tells us to logically AND the contents of our working register which is where we store
whatever we are working on at the present time, with some other number which we will provide.
Two lines of code are needed. The first for the ANDLW instruction and the second for the
value to be worked on. ANDWF tells us to logically AND the contents of the working register
with the contents of another register. Our second line in this case provides the name of the other
register.
So if our working register contains C2 and the number we provide is AA, these are the two
numbers that we will logically and. Of course we must convert them to binary because as I said
earlier logic gates are binary in nature.
144 Chapter 7 –Logic In Action/ Indexed Addressing
C2 1 1 0 0 0 0 1 0
AA 1 0 1 0 1 0 1 0
When we logically AND, it is a vertical operation, bit by bit. We do not carry, only vertically
AND each bit in turn as shown below.
C2 1 1 0 0 0 0 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
AA 1 0 1 0 1 0 1 0
82 1 0 0 0 0 0 1 0
We know from our AND truth table that the only time we will see a 1 is when both inputs are 1.
This only happens at bit 7 and bit 1. All of the other bit pairs contain a 0 in one or both.
So if we look at our result of the logical AND operation between C2 and AA, we come up with
8216
Given the following values, what will be the binary equivalent and the binary and hex result?
32
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
55
Chapter 7 Logic In Action/ Indexed Addressing 145
The OR gate
The OR gate performs an addition function. That is, the two inputs are added together. The
Boolean equation is X = A + B. If either input is a 1, the output is a 1. The only way we can
get a 0 output is if both inputs are 0. In terms of the OR gate we can say that Logic 1 has control
because if either input is a 1, the output will be a 1.
Now if we were to us this logic instruction in a PIC program, we would use one of two possible
instructions. They are IORLW and IORWF. These instructions are very similar to that
explained for the ANDLW / ANDWF instructions.
So lets take the same two values we used in the AND instruction. If our working register
contains C2 and the number we provide is AA, these are the two numbers that we will logically
OR. We already know what they look like in binary so lets jump to the solution table.
When we logically OR, it is a vertical operation, bit by bit. Once again, we do not carry, only
vertically OR each bit in turn as shown below.
C2 1 1 0 0 0 0 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
AA 1 0 1 0 1 0 1 0
EA 1 1 1 0 1 0 1 0
146 Chapter 7 –Logic In Action/ Indexed Addressing
We know from our OR truth table that the only time we will see a 0 is when both inputs are 0.
This only happens at bits 4, 2, and 0. All of the other bit pairs contain a 1 in one or both inputs.
So if we look at our result of the logical OR operation between C2 and AA, we come up with
EA16
Given the following values, what is the binary equivalent and what will be binary and hex
result?
A6
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
DD
Chapter 7 Logic In Action/ Indexed Addressing 147
The NOT gate performs an inversion function. That is, it takes the input and inverts it for the
output. So if the input is a 1, the output is a 0. The Boolean equation is X =
Input Output X
0 1
1 0
Now we don‘t actually have a NOT instruction, but we do have a complement instruction which
is the same thing. It will invert the input, bit for bit. The instruction is called. The instruction is
called COMF and it will complement or invert the contents of a named register. This is a two
line instruction and the second line is the name of the register to complement.
When we logically NOT, it is a vertical operation, bit by bit. Once again, we do not carry, only
vertically NOT each bit in turn as shown below. A 1 becomes a 0 and a 0 becomes a 1.
C2 1 1 0 0 0 0 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
3D 0 0 1 1 1 1 0 1
148 Chapter 7 –Logic In Action/ Indexed Addressing
So if we look at our result of the logical COMF operation, an input of C2 gives an output of
3D16
Given the following values, what is the binary equivalent and the binary and hex result?
F1
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
Chapter 7 Logic In Action/ Indexed Addressing 149
The XOR gate performs an interesting function. For the exclusive OR to be true, the inputs
must be different. That is, they can be 0,1 or the can be 1,0. IF they are the same, either 0,0 or
1,1 the output is zero. The Boolean equation is .
0 0 0
0 1 1
1 0 1
1 1 0
Now if we were to us this logic instruction in a PIC program, we would use one of two possible
instructions. They are XORLW and XORWF. These instructions are very similar to that
explained for the ANDLW / ANDWF instructions.
So lets take the same two values we used in the OR and the AND instructions. If our working
register contains C2 and the number we provide is AA, these are the two numbers that we will
logically OR. We already know what they look like in binary so lets jump to the solution table.
When we logically XOR, it is a vertical operation, bit by bit. Once again, we do not carry, only
vertically XOR each bit in turn as shown below.
C2 1 1 0 0 0 0 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
AA 1 0 1 0 1 0 1 0
150 Chapter 7 –Logic In Action/ Indexed Addressing
68 0 1 1 0 1 0 0 0
We know from our XOR truth table that the only time we will see a 1 is when the inputs are
different. This only happens at bits 6, 5, and 3. All of the other bit pairs have the same binary
value for both inputs.
So if we look at our result of the logical OR operation between C2 and AA, we come up with
6816
Given the following values, fill in the binary equivalent and the binary and hex results.
C8
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
8C
Chapter 7 Logic In Action/ Indexed Addressing 151
Now we don‘t actually have logic instructions for this PIC programmer that include NAND and
NOR gates. Basically the NAND gate is simply an inversion of the AND gate, hence the bubble
on the output. (Bubble means invert on an output, active low on an input).
SO if we look at the AND truthtable and invert all of the outputs, we will have the truth table for
the NAND gate as shown below.
And of course the same goes for the NOR being an inversion of the outputs for an OR. Fill the
last column in.
Build it.
When you built it, if you entered it exactly as I had shown, you should have received an error.
154 Chapter 7 –Logic In Action/ Indexed Addressing
If you click on that line with your cursor, it should bring you to that line in the program with a
little blue arrow.
When you are entering hex values in your program and they begin with a letter, you must put a
zero in front of it. 0AA. Make this change and try to build it again.
Okay now open the watch window under the view menu
Chapter 7 Logic In Action/ Indexed Addressing 155
We are going to add all of the General Purpose Equates and the work register to our watch
window so we can see what happens.
Using the Add Symbol button, add ADD, AND, OR, XOR
156 Chapter 7 –Logic In Action/ Indexed Addressing
Calculate what you think the results will be for each of the registers at the end of the operation
and write those answers in the table below.
Chapter 7 Logic In Action/ Indexed Addressing 157
ANDLW
ORLW
XORLW
Then single step through the program and watch the values change in the
Watch window. Write in the actual answers. Do they match what you had calculated?
Download the chip to the programmer and put it in your circuit. You should see all of the lights
lit up on your display. Keep in mind that PORTB is only 8 bits so only the botto 8 bits will be
displayed.
Once this has been completed, you may have the lab signed off.
158 Chapter 7 –Logic In Action/ Indexed Addressing
ANDWF A5 23
IORWF 22 42
XORWF 63 36
Make sure that you send the results from IORWF to PORTB instead of the XOR instruction.
Once this has been demonstrated you may have it signed off.
Chapter 7 Logic In Action/ Indexed Addressing 159
Create a new folder and call it index or something like that. Create an .asm file, a project in
MPLAB and build it. Don‘t forget your flowchart and program documentation as well as your
.asm file.
160 Chapter 7 –Logic In Action/ Indexed Addressing
Chapter 7 Logic In Action/ Indexed Addressing 161
As soon as you have the program built successfully, open it up. Open the watch window. You
are going to select FSR from the Add SFR column, FSR2 from the Add Symbol column and then
you are simply going to enter the following addresses.
Now, step through the program. Does the program write the dummy data to addresses 040 to
048 and then to addresses 070 to 078?
Too cool!!
162 Chapter 7 –Logic In Action/ Indexed Addressing
This instruction is a 4 bit instruction that will skip the next line when the bit you have specified
turns into a 1. In this case we have specified bit 3. Bit 3 is 1000. So it actually stops on the
transition from 111 to 1000. (7 in decimal) Which is why it only counts to 47 or 77 before it
stops. Because it is a 4 bit instruction, any value above 4 would be invalid. For example, if you
specified a bit value of 5, it would not write to 32 addresses, it would simply stop. Just try it.
Now, study the BTFSS instruction. You are going to modify the program to write the dummy
data 44 instead of 0BB and you are going to write it to 16 addresses instead of only 8. Make
sure that you can view all of them in the watch window.
Chapter 7 Logic In Action/ Indexed Addressing 163
Chapter 8 Timing 165
Chapter 8 Timing
Those labs were kind of cool, but the 16F877A is usually paired with a 20 MHz crystal. In your
kit you have both an oscillator circuit in a flat pack 4 pin TTL package and a two pin crystal.
You can use either onw, but I‘ll show you how to hook up both. First, the two-pin crystal
circuit is shown below.
166 Chapter 8 – Timing
Hook up your scope to the clock input of the chip and ground for both configurations and verify
that you are seeing 20 MHz with both.
What frequency are you seeing for the crystal and two capacitors? ___________
What frequency are you seeing for the TTL package? _______________
168 Chapter 8 – Timing
As far as your circuit goes, you can use either configuration. It‘s up to you.
Make sure you mark all of your pinouts and do all of your hardware testing before you go any
further for your program documentation.
Once you have all of that done and tested, we will move on to the software. Now the next
program is pretty fancy.
Create a new folder on your N drive called Three leds or whatever you like.
Open notepad and create the file remembering to save it in .asm format. Comment as many lines
as you can in order to understand the program. I do want to see comments. Don‘t forget to save
it to that folder and to drop a copy of the include file in the folder as well.
You will notice that we are adding some assembler directives to help define our program and I
am also introducing a subroutine.
Chapter 8 Timing 169
170 Chapter 8 – Timing
Lets go into detail with this program. As you can see, I start the program by giving the program
a name and describe what it is supposed to do. I then give my name and a rough date for easy
reference later.
Our program has three little sections of equates. The first is the SFRs (special function registers)
they are self explanatory. We need to use those addresses and we are simply going to call them
by their SFR name instead of their address number.
Chapter 8 Timing 171
The GPRs (general purpose registers) are the ones that we create in any address between 20h
and 7Fh (in Bank0) We can use more in the other banks, but there‘s lots for us in Bank 0 so lets
stay with them. In this case we have created three banks called part a, b, and c. These three
GPRs are going to create our delay so that we can take that mega 20 MHz signal which is very
very fast and get a 1 second time delay out of it.
Once I had initialized and set PortB as all outputs, I sent you to the main program. The reason I
used the word main is because you will be using that in C and I thought getting used to it now
might save you some confusion later.
The MAIN program itself starts by turning the Green LED off, and turning the red led on, then
calling a 1 second clock delay… it continues through turning the next one on and turning off the
present led and then repeats continuously.
I have a subroutine called CLOCK which I go to twice during my MAIN program and each time
the CLOCK subroutine finishes executing it returns to the next line of the main program with a
172 Chapter 8 – Timing
RETURN. You‘ll notice that I used CALL to go to the subroutine and RETURN to come back
from the subroutine. The structure of this program is pretty standard. We have introduced a
new instruction here called DECFSZ. This instruction is referring to a state in one of the bits of
the STATUS register.
The STATUS register tells us what is going on in the ALU. The ALU controls and monitors
what is going on in the SFRs, GPRs and working register, whatever we are working on at the
moment.. For example, bit 2 of the working register, the most commonly used bit tells us
Chapter 8 Timing 173
You can check the values in the STATUS register when you are simulating your program simply
by checking off the STATUS in the drop down menu of the SFR.
174 Chapter 8 – Timing
We read the content values as a hex code. For example if we were to read the value in the
STATUS register as OC it would tell us the following:
Bi Valu Meaning
t# e
7 0
6, 0
5 0
4 0
3 1
Chapter 8 Timing 175
2 1
1 0
0 0
We read the binary value in the vertical column as 0000 1100 which is OC.
Bit 2 is the Z bit. That is the bit that is referred to in the DECFSZ instruction in our program.
This is the most commonly referred to bit in the STATUS register and basically serves as a
trigger for many of our timers and counters. If we are decrementing or incrementing a value, we
can simply poll this bit to see when it reaches 0. As soon as it does we can move on to the next
instruction. This is a great bit and very valuable.
The carry bits are used also for similar purposes. Once something carrys either from bit 3 to 5
(Bit 1 in the STATUS register) or from bit 7 to 8 (Bit 0 in the STATUS register) we can use
that information to trigger another operation.
176 Chapter 8 – Timing
Given the value 25, fill in the binary value and the information in the following STATUS
register.
0
Chapter 8 Timing 177
Given the following meanings, fill in the binary value and the Hex code for the
following entries
Bi Valu Meaning
t# e
7
0
178 Chapter 8 – Timing
Okay, now back to our program. You will notice that I followed a sequence to my programming
as follows:
This is a good habit to get into as you will be able to keep yourself and your programs organized.
Also, it will make things a lot easier when you get to C programming next semester.
Let‘s look at some other instructions in our program. Of particular note here is the difference
between a CALL and a GOTO. Both of them send you off somewhere else, but with one very
important difference. A CALL sends you on a subroutine which must end with a RETURN, a
RETFIE or an RETLW A GOTO is just a jump that sends you somewhere else. There is no
provision to come back to where you left off with a GOTO.
Subroutines
So how exactly does a subroutine work?
As soon as you use the word CALL, everything stops. Our PIC contains a register called a
STACK. As soon as you execute a call, the Program Counter (PC) address is pushed onto the
top of the stack so that when the CALL is over, the program knows where to return to. As soon
as your subroutine has finished executing and you use your RETURN instruction, (RETURN,
RETFIE or RETLW) the Program Counter address is popped off the top of the stack and back
you are, one instruction down from where you left off.
With the PIC16 series, stacking is entirely automatic. The stack is not readable or writable by
itself. With later models you can actually change the address and size of the stack.
Also it is 8 addresses deep and 13 bits wide. If you store a 9th into the stack, it overwrites the
first one that was in there, a 10th overwrites the second, etc. It is circular in nature.
The RETFIE instruction is used when you are returning from an interrupt rather than a
subroutine.
The RETLW takes a literal value, transfers it into the working register and returns to your main
program all in one instruction. Now that is pretty cool.
Chapter 8 Timing 179
The following table will help you figure it all out the SFR (Special Function Register) equates.
Now that we have finished exploring the wonderful world of subroutines, let‘s get back to the lab
Once you have saved your .asm file, open MPLAB and go to Project Wizard, following all of the
steps as before. Remember to change the A‘s to C‘s on the following screen.
And once your project is up, go to configuration bits and make sure the following is selected.
You will see that we have changed the Oscillator from RC to HS. HS if the proper setting for a
20 MHz crystal, high speed.
Now build it and fix any errors that occur. Once you are receiving no errors, open the simulation
window as you did before and the stopwatch.
Set a break at the CLOCK label by double clicking on it. A red B should show up where your
break is set. It should look like the program on the next page.
Set a second break at the point where the program returns from the call at
Chapter 8 Timing 183
Click on the RUN button (shown below) Your program should stop at the clock and you should
have 3.2 µ seconds in the Time section of your Stopwatch
184 Chapter 8 – Timing
Now Press it again. The program should stop on line 63, right after the return from the call.
Your stopwatch should read 1.000003 seconds, the 1 second delay plus the 3.2 micro seconds we
had accumulated before we went to the clock.
Chapter 8 Timing 185
Now take off your breaks and transfer the program and run it.
186 Chapter 8 – Timing
Of special interest here of course would be the INTCON Register. The INTCON register, shown
below can be found at addresses 0B, 8B, 10B and 18B, 1 in each of the 4 different banks. The
INTCON register is a write register where we specify which bits we want to be set. Generally
wit the INTCON register, we specify particular bits with a BSF (bit set) or BCF (Bit clear)
instruction unlike the OPTION register where we generally specify a binary value for the entire
register. (You will get to that shortly, in the section on timing)
The INTCON Register can be read as a binary and HEX value according the values that are
selected, just like the other registers in the PIC.
Using the values shown above, we would get a binary value of 1011 1100 or BC
188 Chapter 8 – Timing
Given the value D4, fill in the binary values and meaning for each bit in the INTCON
Register below
0
Chapter 8 Timing 189
Given the following preferences, what is the binary and hex code for the following settings in the
INTCON register?
Bi Valu Meaning
t# e
7
0
190 Chapter 8 – Timing
Okay now, enough with the INTCON register. For our purposes our interrupt is going to stop
the flashing three light sequence from our previous lab when we press the interrupt button and
then flash a fourth light until the interrupt subroutine is ended by another pushbutton.
In order to create an interrupt, we need to enable interrupts in the INTCON register, and
specifically the RB0/INT interrupt.
You will notice that we have used ORG twice in this program. The first ORG sets the address to
go to upon pressing the !MCLR button, the second ORG specifies the address to go to upon
pressing the RB0 interrupt button. Don‘t forget this.
You will notice that the Interrupt Service Routine occurs BEFORE the initialization, unlike a
regular subroutine which occurs after.
Modify your program to reflect the one shown down a few pages.
192 Chapter 8 – Timing
Chapter 8 Timing 193
194 Chapter 8 – Timing
Chapter 8 Timing 195
Once you have it all up and running, it should start flashing in sequence as soon as power is
applied. If it doesn‘t, follow your troubleshooting procedures.
You should notice that if your press the button at RB0, the flashing LED sequence stops, the
three turn off and the fourth starts blinking all alone at 1 second intervals. To pick up where you
left off, press the button at RA4. The LED that was flashing when you pressed the interrupt
button will have been stored in the store GPR that we created. If you want to start all over again,
of course you can press the !MCLR button.
I know that‘s just way too cool. You‘re probably wondering how I got that one second delay.
Did I sit there and randomly change the three values of parta, partb, and partc. Well to tell you
the truth I did do a little bit of that, but the value does follow a certain formula.
Let‘s take a step back and look at our crystal for a second. It‘s a 20 MHz crystal. Our PIC
divides our Oscillator value by 4, which gives us 5 MHZ. Then we take the inverse to get our
instruction time. Because T = 1/frequency. Remember? And you thought you would never use
that from AC. Well 1/5 MHz is .2 µs. That will be the default of any program we create using a
20MHz crystal with this chip. Each instruction will take .2 µs to execute.
After we RESET, we should see our green arrow sitting on the MOVLW instruction.
If we take just one step, we should see 1 instruction cycle and .2 µs in the respective windows.
Open the stopwatch window and take one step.
Well what does this tell you? This tells you that you can modify your time by increasing or
decreasing your instruction cycles. In my program I created my 1 second delay by playing
around with the values 6D, 5E and 1A and using cascaded timers.
Each one added more to the instruction length and so increased my time delay until I reached 1
second.
I like to keep a file where I have several different time delays in it and then pull up one as I need
it.
Here is one I like to use for 100 microseconds. You will notice the parta in there. I leave that
there as this is part of a template I like to use. I add partb and partc as I am making longer and
longer delays. You don‘t have to do that.
So now, we have a total of 504 instruction cycles if we add them all up. Since we already know
each instruction cycle is .2 µ seconds, that gives us a delay time of 100.8 microseconds. Let‘s
see if our program agrees.
Take the little 100 microsecond program and put it in your existing program, commenting out the
previous 1 second delay that was in there.
We set breaks at the beginning and end of our time delay and press run.
And take note of our Instruction cycles and clock cycles at the time.
Chapter 8 Timing 199
Then we delete the first break by double clicking on it. IF you don‘t do this, you are going to be
going through this mini delay forever.
Once you have done that, press run again and take note of the values in the Stopwatch.
So 103.6 microseconds minus our 3.2 starting gives us approximately 100 microseconds. Too
cool eh?
Now if you‘re quick on the draw, you probably noticed that we started with 16 instruction cycles
and ended with 518 even though I said there was 504 which should have given us 520. The
reason for that is because we haven‘t executed the two instructions for the RETURN yet.
Instead of calculating it out, you can just set some breaks as we did before and randomly change
the values in your delay, checking each time until you get the desired time length.
200 Chapter 8 – Timing
For this lab, create a .75 (750 millisecond) a 1.25 second or a 1.5 second delay to run your
three LED program. (you choose which one) Submit a screenshot of your stopwatch at the
RETURN line, your timer subroutine and your flowchart and documentation.
Here are some practice exercises for you for calculating total delay time. I strongly
recommend that you do them. You can check your answers at the back of the book.
Delay Exercises
1. Look at the following table. Given the value MOVLW value and a clock frequency of 1
MHz, how many instruction cycles are there and how long will it take to execute this delay?
MOVLW 0C3
MOVWF parta
DECFSZ
GOTO dec
RETURN
TOTAL
Instruction Cycles ___________
/4 frequency ___________
2. Look at the following table. Given the value MOVLW value and a clock frequency of 4
MHz, how many instruction cycles are there and how long will it take to execute this delay?
MOVLW 044
MOVWF parta
DECFSZ
GOTO dec
RETURN
TOTAL
Instruction Cycles ___________
/4 frequency ___________
3. Look at the following table. Given the value MOVLW value and a clock frequency of 20
MHz, how many instruction cycles are there and how long will it take to execute this delay?
MOVLW 0E2
MOVWF parta
DECFSZ
GOTO dec
RETURN
TOTAL
Instruction Cycles ___________
/4 frequency ___________
In addition to our external clocks, the PIC16F877A offers three separate internal timers known
as TMR0, TMR1 and TMR47 well no actually the last one is just TMR2. First we will have a
look at TMR0.
TMR0 can be used as an 8-bit timer or counter. What does that mean? A timer generates a time
while a counter monitors something that is happening external to the chip. Because it is 8 bit, its
maximum count is 1111 1111 or 255 in decimal. It is the most commonly used of the timers.
You can read or write from TMR0 at any time and when it overflows, an interrupt is generated
and the following flag bit is set: TMR0IF (bit 2) in the INTCON register.
That is important, but no discussion of TMR0 would be complete without looking at the
OPTION register, we‘ll have a look at that now.
204 Chapter 8 – Timing
When we are using TMRO, we must pay particular attention to bits 5 – 0 of the OPTION
register.
Chapter 8 Timing 205
For our purposes we want the following settings on the OPTION register.
Bit # Value Meaning
7 0
6 0
5 0
4 0
3 0
2 1
1 0
0 0
If you look at the illustration above, choosing 100 as the last three bits in the OPTION_Reg,
results in a division by 32. For our next lab we are going to be using a 10 µf capacitor and a 10
KΩ resistor, for a frequency of 10 KHz. We already know that to get our instruction cycle time
we divide our incoming frequency by 4 and take the inverse, so that would give us 10,000 ÷ 4
(2500) and after that we take the inverse(1/2500) to get 400 µs (microseconds). So each
instruction cycle is 400 µs long.
What instruction cycle time would you generate by setting the last three bits of the OPTION
register to 110?
_______________
206 Chapter 8 – Timing
1. You are given a hex value of 2B for your OPTION register. Fill in the binary values and their
meanings in the following chart.
0
Chapter 8 Timing 207
2. You are given the following Meanings for your OPTION Register. Fill in the binary value and
write out the hex code in the table below. And if we were to work it backwards like the table
shown below, we would have the following values:
Hex Code:______________
0
208 Chapter 8 – Timing
Read the entire lab and create a flowchart. Build the following circuit, remembering your
documentation and to test all of the hardware before you go on to the software. Don‘t forget to
mark all of your pinouts.
Once you have completed that, create a new folder and create the following program. Then of
course create the project in MPLAB, build it and bring it up.
Chapter 8 Timing 209
210 Chapter 8 – Timing
Below you will see an example of a simple TMRO program. There are a sequence of operations
you must perform in order for it to work.
Once you have that up and running, open up the settings option on the Debugger menu
If you select the StopWatch now, it should come up with a default value of 10 KHz.
212 Chapter 8 – Timing
You should see that indeed, one step does take 400 µs to execute.
So how long does our delay take to execute?
Set a break at the start of the main program and again after it returns from the TMRO delay.
Chapter 8 Timing 213
At the beginning of MAIN you should see that there have been 7 Instruction Cycles and 2.8 ms.
So if we press run again, it will tell us just how long it takes from the time we turn the LED on
(BSF) to the time we turn it off (BCF).
So press it again.
214 Chapter 8 – Timing
So the actual time between BSF and BCF is 3.2836 - .0028 which is 3.2808 seconds.
Our LED is going to stay on for 3.2808 seconds and then go off for 3.2808 seconds.
Lets look at the instruction cycles. 8209. We subtract 7 as it was the value when we started our
little routine and we get 8202. If we divide the 3.208 by the number of instruction cycles we still
get 400 µs. So the delay adds more instruction cycles to create the delay, it does not alter the
instruction cycle time.
Its going to timeout the 8 bit TMRO register (value of 256) 32 times. That‘s how it works. You
can prove it by dividing 8202/32. You should get 256.
Go ahead and put your program on the chip and run it. Are you seeing an on time of
approximately 3 seconds and an off time of approximately 3 seconds?
Chapter 8 Timing 215
Fix any syntax and logical errors in your program if they exist.
Ducky!
Change the value that you are writing to the OPTION_Reg to 111. (256)
Time _______________________
Divide your Instruction Cycles by your max count for the TMRO register (256)
What do you get?
____________________________
And when you divided the 65554 by the max count in the TMRO register (256) you should have
seen a value of 256 which was your setting in the OPTIONS register when you selected 111 as
your value.
Now of course it wasn‘t exactly 256 because there were 7 instruction cycles and 2.8 milli
seconds of time when we started the BSF, but you get the picture.
Next, open up the Debugger Settings window again and change the value back to 20 MHz.
Change your config bit settings in MPLAB and in your program to reflect this change.
Now our on time for our LED will be 13.11 milliseconds and so will our off time. This will be
too fast for us to see on our LED. And we are at the maximum prescaler value setting in the
OPTION register.
The TMRO is great, but not very practical for this purpose using a 20 MHz crystal as the
maximum delay time we can achieve is 13.11 milliseconds. We simply cannot bring the time
down enough. That‘s why we used a delay subroutine of 1 second when we did it last time.
Change your config bits in both your program and your MPLAB config bit settings to reflect the
changes.
Change the OPTION_Reg value to 101 and fill out the following table.
Chapter 8 Timing 219
For the TMRO, this happens on the RA4/TOCKI/C1OUT pin or pin 6 on your chip.
We can look below to see what our settings should be for the OPTION register.
6 0
5 1
4 1
3 0
2 1
1 1
0 1
So our hex value for the OPTIONS register is 0010 0001 or 2116
Chapter 8 Timing 221
Frequency Generator
Set up your frequency generator as shown. Select the 1K resistance button, the square wave and
make sure your output is connected to the TTL output. On this particular frequency generator it
is called Sync Out. What you want is a dedicated 5 volt square wave, designed to be used with
TTL chips. It might be called something else on your generator, even the TTL output.
Whenever you are connecting into circuits with chips, this is a good output to use.
Adjust your main and fine knobs until you see about 90 Hz.
222 Chapter 8 – Timing
Once you get it all up and running, you should notice a count time of about 2.8 seconds. What
you are seeing is a real time display of what is happening in TMR0. That is pretty cool.
This is a simple calculation of our incoming frequency divided by our max count of the timer
(256) which gives us
1
90 ÷ 256
2.844 seconds.
Chapter 8 Timing 225
Adjusting the frequency will of course adjust the time accordingly. Turn the main (sometimes
called course) frequency adjustment knob on your frequency generator. Notice how the time
decreases (LEDs count faster) as frequency increases.
We can adjust what it counts from in this way by adjusting the value here:
Go ahead and make the change to your program and load it up on the chip. When you plug your
power into the board you will notice that the count starts at C2. It will count to FF and then roll
over. So the actual count is FF – C2 or 3D + 1 (for the roll over) Keep that in mind when you
are using the counter. You must take the 2s complement of the number you want to count to.
(Refer to chapter 4 if you need to review 2s complements) So if you only wanted to count to 10,
you would take FF – 0A (10 in hex) and add 1. That would be F5 + 1 or F6. Your count
would start at F6.
.
226 Chapter 8 – Timing
Lab 17 -- TMR1
TMR1 is a 16bit timer/counter used to create longer delays. The maximum count is 65,535 It
consists of two addresses TMR1H and TMR1L. These stand for the high and low bytes of the
register. So if you had an address of C23A (hex), C2 would be the high byte and 3A would be
the low byte. As with the TMR0, an overflow triggers an interrupt. Only the interrupt flag for
the TMR1 is found in the PIR1 Register at bit 0.
In addition to the stuff you can do with TMR0, TMR1 can do other things. The TMR1 has its
very own register and it is called the T1CON (shown below) .
Chapter 8 Timing 227
TMR1 also has a prescaler, but it is entirely separate from TMR0, and can only divide at 1, 2, 4,
or 8.
TMR1 – Oscillator
Using the TMR1 Oscillator requires a second crystal, usually 32.768 KHz
228 Chapter 8 – Timing
Using our same circuit from TMR0 and our 20 MHz clock, enter the following program.
Don‘t forget to drop the INC file into your folder as we will be using it in this program.
Chapter 8 Timing 229
You will notice that we have added the include file this time. Make sure you specify the path to
where YOUR folder and file are located or you will get an ERROR.
The advantage to including this file is that we don‘t have to specify Special Function Register
equates.
They are included in this file. Once you have the program entered and the project built, click on
the P16F877A.INC file.
Scroll down and you will see the list of Register Equates. I am just showing a partial screen
here.
230 Chapter 8 – Timing
Chapter 8 Timing 231
Build it and work out any syntax errors. Start the simulator and set breaks on Main and GOTO
LOAD (lines 59 and 63) so we can see the delay. Don‘t forget the open the Stopwatch (under
the Debugger menu)
Once your stopwatch is up and your breaks are set, press the run button.
So at the start of the main program you have passed through 12 instructions and 2.4 µs. Pretty
minimal. Press the run button again.
232 Chapter 8 – Timing
So the on time for our red LED is going to be 102.5898 ms. Not very viewable. If you look at
line 38 you will see that we loaded the maximum prescaler possible for TMR1.
The problem is, that at 20 MHz, even with a 16 bit counter with a value of 65, 635 our max
prescale of 8 means that the longest time delay we can get is about 103 milliseconds. Better than
the maximum of 13.11 milliseconds with TMR0, but still not viewable.
Build it and send it to the PIC. Run the stopwatch. As you can see, the 16 bit timer is minimal
for a visual delay using a 20 MHz oscillator. But the timer does have other uses. We will look at
those later. And the TMR1 is not just a timer, but a counter as well.
It runs much the same as the TMR0 counter, but with 16 bits.
236 Chapter 8 – Timing
Lab 18 -- TMR2
Timer 2 consists of 2 8-bit registers. The first register TMR2 sets an initial value to start
counting from. The second register PR2 sets the value to count to. It basically works like a
comparator. It takes the value in TMR2 and compares it ti PR2. Once they are equal, an
interrupt is flagged. The interrupt flag for TMR2 is found at bit 1 of the PIR1 (Peripheral
Interrupt Flag Register) .
The T2CON register is where we set pre and postscale values as well as turn TMR2 off or on.
Timer2 does not have an external clock source possibility like TMR0 and TMR1, so it cannot be
used as a counter, only a timer.
Chapter 8 Timing 237
There is a specific sequence we need to follow in order to set this up. I have taken an excerpt
from my program below. This is where and how we set up TMR2.
238 Chapter 8 – Timing
Chapter 8 Timing 239
240 Chapter 8 – Timing
Once you get this up and running, you should see your red LED flashing at a little more than one
second intervals.
Every time the timer reaches the preset value of EE, the light changes states.
Chapter 8 Timing 241
Here is your circuit, build it and test it. Don‘t forget your program documentation.
The two leads you see connected are from your oscilloscope. The pin that the red lead is
connected to is RC2/CCP1. We are using it as CCP1. It is an output especially designed for
PWM generation.
In order to set up the chip to generate a PWM signal there is a very specific sequence we have to
follow. It can be found in the PIC16F877A data sheet, but I‘ve reproduced it here below for you.
242 Chapter 8 – Timing
If you follow through on the following program, you will see how we have fulfilled each of the
steps.
Step 1 is to write our desired PWM value to the PR2 register (set our desired period). We do
this by first setting the RP0 bit in the STATUS register (changing banks). We then move the
calculated value 249 (Decimal) into the working register and then transfer that to the PR2
register. then we clear the RP0 bit in the STATUS register, resetting the bank.
You are probably wondering where I came up with the number 249. To calculate the value we
need to enter in the PR2 register we need to know the period of our oscillator, our desired period
(at 5000 KHz) and our prescaler value.
We start with our crystal value which is 20 MHz (20 000 000). We already know we are in a /4
so that gives us 5 MHz. we take the inverse which gives us .2 µs. That as you know is our
instruction time or the period of our /4 oscillator.
We want to create a 5,000 KHz square wave. The inverse of that is .2 ms. (.0002) That would
be our desired period.
Step 2 is to set out duty cycle for the PWM. Now the PWM duty cycle is 10 bits long and each
address we use only has 8. We will set our duty cycle by using the two addresses designed for
this purpose, CCPR1L and CCP1Con. CCPR1L holds the upper eight bits, while CCP1Con
holds the lowest two bits at bit addresses 5 and 4.
So if we wanted a 50% duty cycle on a 5 KHz wave and assuming we are using a 20 MHz
oscillator, our formula is
PWM duty cycle = 50% of desired period / oscillator period
= .000 1 / .000 000 2
= 500
We convert that number to binary and get
0111110100
Step 4 sets the prescale value that we had decided upon (4)
We simply put it all together to get the program that will give us our desired PWM duty cycle.
Chapter 8 Timing 245
Create this project and build and run it on MPLAB. You should see the following on your scope
when you connect your scope to ground and pin RC2/CCP1.
246 Chapter 8 – Timing
Chapter 8 Timing 247
Modify your program to give a 2500 Hz signal and use a prescaler of 8. Change the duty cycle
to 25%.
Chapter 9 Motors 249
Chapter 9 – Motors
Before we continue, let‘s take a look at our programmer. We are using a PICKit2 compatible
programmer. You may be using a different one or have built your own. There are certainly
plenty of resources and schematics online for you to be able to put one together.
I chose this one because of the price, the zif sockets, the sturdiness, versatility and finally and
most importantly, the pretty green and red colour combination. (yours is probably blue and
green but I bought mine first)
250 Chapter 9 – Motors
We‘re going to play around with four different types of motors. DC, DC with a PWM circuit,
servo and stepper. This will let you see all of the different sides to these motors and maybe
understand a little about why we use the ones we do in different applications.
Chapter 9 Motors 251
Okay, first let‘s take our regular little 5 volt DC motor from your kit.
Now as cute as this motor is, there are a few let‘s say ‗frailties‘ with it.
These little tabs tend to tear off. But don‘t let that worry you. You are a technician and you can
fix it. Just get a small screwdriver and pop the tabs open on the side.
As soon as you do that, the white part will slide off and you‘ll see the inside.
252 Chapter 9 – Motors
You can take out that little screw and that plastic part comes off, then just solder two pieces of
wire inside to replace the tabs that stick out. Be very careful not to remove these little dudes
These are your brushes and you need them for the motor to work.
Okay now that you‘ve looked at that side, lets pull out the inside of the motor.
So what to you see? A shaft with three coils and three metal plates wrapped around it. And the
motor casing has two magnets on opposite sides, one marked with a red arc and one marked
with a green arc. The red arc marks the north pole, while the green arc marks the south pole.
Six parts actually: axle, armature, stator, commutator, field magnet(s), and brushes.
Chapter 9 Motors 253
The brushes are basically two springy metal pieces that provide contact to the commutator. If
you notice when you put the motor back together, they brush along the side of the commutator
when it is moving, bringing power to the motor. This power energizes the coils which then
creates a field in the plates. The plates (rotors) begin to move as they are repelled and attracted
by the field magnets. Actually, only one is fully energized at a time as it rotates. It becomes
fully energized when it is moving between the magnets, not when it is directly over one This in
turn spins the axle, and the axle drives whatever we put on it. I know what you‘re thinking.
You‘re thinking wow, I didn‘t realize how incomplete my life was before I learned this. So hang
on to your hats, there are actually some animations, some really good animations online that
show how the DC motor works. Look some up.
Okay so now lets put this motor on a board and do some speed control with a straight DC 5 volt
input. Hook up the motor as shown below. It‘s pretty complicated so take your time. Connect
your DC power supply into the jacks and your voltmeter and scope across the power and
ground for the motor. Turn the voltage down to 0 before you turn the power on.
***Remember to test your power supply with a voltmeter*** Always test and never assume.
You don‘t want to assume you have 5 volts on your IC chip when in fact you have 12. You do
that and you are going to start burning something.
254 Chapter 9 – Motors
Okay now turn the power supply and the scope on. Make sure your scope is on the right
channel. Set your volts/division to 2. Select ground first and line it up in the middle. It‘s
always good to know where ground sits. Now switch to DC. With your power supply turned all
the way down, you should be reading 0 volts so the line should not have moved. The motor
should be off.
Now slowly turn the power supply up until your voltmeter reaches 5 volts.
You should see and hear a change in the speed of the motor. The speed of the motor should
increase as you increase the voltage. The output on the scope should now look like this:
And that‘s really all there is to a DC motor powered simply by a DC power supply. The pot
creates an analog input and the speed of the motor increases in proportion to the voltage applied.
This is fine for some applications. But using a straight DC power supply and a pot means that if
you want to interface to anything else say like a PIC, you would have to add the additional
circuitry of an analog to digital converter (ADC).
Chapter 9 Motors 255
This was a very simple lab, you do not require program documentation for this lab.
Demonstrate the change in voltage on your scope as it relates to the change in voltage setting.
256 Chapter 9 – Motors
Now we‘ll have to pull out our PIC for this one.
For robotic applications, ones that deal mostly with digital signals, using variable voltage speed
control are not very practical. Remember that to change your speed you were using a POT. A
POT is analog control. If we were to add this to our circuitry it makes a much more
complicated circuit than if we deal with strictly digital signals.
With a PWM circuit, we are not just playing directly with the amplitude of the input voltage. We
are manipulating the duty cycle or ratio of on to off time of a waveform. The length of the
waveform can be shown below. It is simply picking a point in the waveform and then moving to
the next time it is at exactly the same point. We will be applying 5 volts to the circuit and the
duty cycle will determine just how much of that 5 volts is being delivered.
The circuit we will be building will have a default duty cycle of 50% and every time you press
the reset button it will return to this value. Below you will see an example of a 50% duty cycle.
It means that the pulse is on for the same amount of time that it is off.
Chapter 9 Motors 257
What is a duty cycle?? A duty cycle is the ratio of on time to total length of a waveform. Of
course on time is the length of time that the wave is at its maximum voltage. In the illustration
above, the on time is two squares, the entire length of the waveform is 4 squares. Therefore the
duty cycle is 2 ÷ 4 = .5 or 50%.
To increase the speed we will increase the duty cycle by increasing the ratio of on time to the
entire wave form. In the following example the pulse is on for 3 squares and there is a total of 4
squares in the waveform. We would calculate the duty cycle by using the formula 3 ÷ 4 = .75
The new waveform has a duty cycle of 75%.
To decrease the speed we will decrease the duty cycle. In the next example the pulse is on for 1
square with a total of 4 squares in the waveform. To calculate we simply say 1 ÷ 4 = .25. The
new waveform has a duty cycle of 25%.
258 Chapter 9 – Motors
Let‘s have a look at this circuit for a minute. You will notice that we are using a transistor to
deliver the PWM to the motor. The transistor is an excellent choice as it provides isolation.
What kind of transistor are we using, do you remember?
It‘s an NPN, BJT. If you are trying to remember how to hook it up, look up your datasheets.
Remember that the arrow is always on the emitter on a transistor and that if it is pointing in to the
base it is a PNP (points in permanently) and if it is pointing out it is an NPN (never points in). In
this case of course it is an NPN.
Chapter 9 Motors 259
Your next question for review, is it a sinking or sourcing transistor? Remember that the sinking
or sourcing designation always refers to where the emitter is connected. If it is connected to
ground it is sinking (sinks into the ground) If it is connected to power it is sourcing. (Sourcing
power)
So in our case, we are using a sinking transistor as the emitter is connected to ground.
What is the diode doing in the circuit? Whenever you deal with motors you want to throw in a
diode. Diodes prevent back EMF from frying your circuit. It must be properly biased, that is
that the cathode should be facing power. Also, it should be parallel with the motor.
Load up your PWM circuit from the TMR2 lab. As noted before this entire program is basically
an initialization process.
260 Chapter 9 – Motors
Chapter 9 Motors 261
Once you have the project up, build it again and put it on the chip and into your circuit. The
motor should be spinning. If it isn‘t, double check your output again to make sure you are still
getting your 5 KHz square wave from before.
So what we are going to do is write a program that loads different PWM periods onto the chip
and we can watch them on the scope as they change.
262 Chapter 9 – Motors
Chapter 9 Motors 263
264 Chapter 9 – Motors
Chapter 9 Motors 265
A stepper motor is brushless (inductive) and synchronous (moves with a clock). moves in steps,
measured in degrees and is open loop.. Wow, but what does that mean???
First of all the stepper motor is inductive, it can induce a voltage it does not need to make
physical contact to deliver the voltage. So it is brushless. Remember the little brushes in your
DC motor that transferred the voltage?
Secondly, synchronous, it is controlled by a digital clock pulse and reacts to that pulse. We can
alter the time of that pulse as you will see.
Finally, stepper motors employ open loop positioning. Basically this means that they don‘t
require encoders for feedback. If they did they would us closed loop positioning but we will
leave that for the servo motors.
You will find stepper motors in scanners, printers, car door windows all kinds of small
applications that need a precise movement
.
266 Chapter 9 – Motors
There are three basic types of stepper motors: permanent magnet, variable reluctance and
hybrid.
If you are not sure what type you have, try spinning it without applying any power. A permanent
magnet or hybrid stepper motor will not move, it will be locked, while a variable reluctance
stepper motor will turn fairly easily.
The hybrid stepper motor uses a combination of iron and a permanent magnet.
Chapter 9 Motors 269
When it comes to ways of advancing the motor, all three types of motors permanent magnet and
hybrid, share the following methods: Wave stepping, Full stepping and Half stepping.
Wave stepping takes the least amount of programming and uses the lowest amount of power
consumption but does not provide a reasonable amount of stability or torque. The stepping
consists of simply actuating each line at a time in sequence. The sequence is as follows:
Full Stepping actuates two lines at a time, giving more holding power and less chance of
slippage.
Half Stepping (shown below) combines the two. It provides the most torque and stability and
also increases the resolution of the rated increment by two. That is, if the motor is 7.5°, half
stepping reduces each step increment to 3.75°.
Okie dokie now, enough with the theory, it‘s time to start playing with stuff.
270 Chapter 9 – Motors
Open up your DC Stepper Motor box (little white box) in your kit. You should see the
following: A Stepper Motor and a white sheet showing you the following wiring.
..
First things first, let‘s look up the data sheet for this stepper motor.
You can usually just look up the code found right on the stepper motor. In the case of the
stepper motor I am looking at, the code is J835L. When I do a search for this product number, it
comes up right away. If you can‘t find it I have also posted it under Course Documents.
The five wire means that our centre taps are tied together.
The 7.5 degrees refers to how far it moves with each step. At 7.5 degrees it will take 48 steps to
move an entire 360°.
Chapter 9 Motors 271
If the proper sequence is not used, the shaft will just go back and forth, back and forth and not
turn all the way around. So if you are finding that your motor is doing that during the lab, that
would be why. You do not have the proper sequence.
Wire up the following circuit. Remember your program documentation and to test the hardware
as far as you can.
For those of you who can‘t quite make it out, all emitters are indeed connected to ground before
going to the diode.
Take note of the type of transistor used, whether it is sinking or sourcing and the direction of the
diode as you put your circuit together.
272 Chapter 9 – Motors
Should look something like this, remember tight to the board and no wires looping in the air and
hanging all over the place.
Once you‘ve done that, create a new folder and a new file and enter the following program.
Chapter 9 Motors 273
274 Chapter 9 – Motors
Chapter 9 Motors 275
Okay, now load the program onto the pic chip and lets see it run. You should see the stepper
motor stepping through in sequence, one step at a time, on its way towards a complete
revolution.
If nothing is happening at all, double check your data sheet for your transistors, and check that
they are all 3904s and that none are 3906s or something else. If absolutely nothing is happening,
99% of the time, your transistors are in backwards.
Is it giving you grief? Maybe going back and forth, back and forth.
This is telling you that your sequence is off. The little diagram you got in your kit does not show
the correct sequence. So now what shall we do??
It‘s okay, don‘t panic. We are technicians and we can figure this out.
There is an easy way to find the right sequence, I mean after all there are only four wires, right?
Now try switching 3 and 4 from the original so the sequence is 1, 2, 4, 3 is it going now?
Hmmm. Curiouser and curiouser
Okay once more, let‘s try switching the middle two wires so that the sequence is 1, 4, 2, 3. How
about now? Too cool It should be working fine.
Now of course it would be a really good idea to make changes in your program to reflect this
alternate wiring. It will make it is easier for you to remember that the lines had to be switched
around when you come back to the program later.
Okie dokie
Once this is complete you can have this lab signed off. Remember your documentation.
278 Chapter 9 – Motors
This will be an addition to your program documentation for the stepper motor lab, you do not
need to fill out a whole new set of sheets for this lab.
Chapter 9 Motors 279
A servo motor can be AC or DC (ours is DC) which runs on pulse width modulation (PWM) and
closed loop feed back. Unlike the stepper motor the servo requires and encoder for feedback so
it knows where it is.
All of our robots employ servo motors. DC brushless in the CRS and SCORBOT and AC servos
in the XYZ. Years ago most robots used steppers, but now with servos and the encoder
feedback, the movement is much more fluid and precise.
Most hobby servos operate in a standard manner. They run at 50 or 100 KHz ( 2 or 1 ms) with a
period of 20 ms. . The 1 ms pulse moves the servo clockwise, the 2 ms pulse moves the servo
counter clockwise. A 1.5 ms pulse holds it in position.
280 Chapter 9 – Motors
It is not recommded that we use the PWM mode on TMR2 on our chip to control a servo motor.
We will have to program it differently.
Manually turn the servo motor pinwheel all the way clockwise. Using your protoboard, hook the
red line to power, the black to ground and on the yellow, bring in your frequency generator and
set it for about 50 Hz.
Turn the power on. It should turn until it reaches its CCW limit. Too cool, eh?
Chapter 9 Motors 281
You see, servos are not designed to turn 360 degrees continuously but most can turn 180 in
either direction from centre. When you get to the robots and their User Manuals you will see
that none of them have a 360 degree continuous rotation. That would be silly with a robot, it
would just end up twisting its cables around itself and wrecking things. Back and forth with a
180 degree reach is usually sufficient.
The wonderful thing about servos is the feedback of course. We won‘t be getting in measuring
the feedback in this course, there just isn‘t enough time. However, take note that feedback is
what allows us to keep precision in controlling a robot. For our purposes here, we are simply
writing a little program to sweep it back and forth ninety degrees.
Wire up your circuit shown below. Put in a 4 MHz crystal. If you don‘t have one, come see me.
282 Chapter 9 – Motors
Chapter 9 Motors 283
Before we start our program, lets talk about what we are about to do.
Our program is just going to turn our servo motor 90 degrees clockwise and then 90 degrees
back.
In order to do that we have to create a program with a 20ms period and duty cycles that allow
for 1 and 2ms pulses within that 20 ms period.
I want to show you how to do this using TMR0 because it makes it so much easier. We simply
set the OPTION register to /128 and the TMR0 value to 102 and ta da! We have a 20 ms period.
In slow motion, that is we take our 4 MHz clock and divide by 4 to get 1 MHz (because our
chips is a /4 oscillator, remember)
Then we take that 1 MHz and take the reciprocal (.000 001 or 1 µs)
We multiply that by our 128 setting in the option register (.000 128)
We know that we want to get 20 ms so we divide that by what we have so far to get what we still
need
.02 (20 ms) ÷ 128 µs .(000 128) = 156.25
The max count we can get with TMRO – 256 so we subtract 156 from 256 to get 100. But
remember we need the 2‘s complements so then we add 1 and 1 more for good luck (not really
Timer) loses one at load) Our final anser is 100 + 2. So the value we need to load into TMR0
with an OPTION register prescale rate of 128 in order to get a 20 ms period out of a 4 MHz
crystal input is 102
Or
20 ms ÷ _____________1_____________
4/4 ÷ 128
20 ms ÷ _____________1_____________
.0078125
= 156
The 1ms and 2 ms delays I created using a standard delay as I did with the 1 second delay when
we were playing around with timing.
Remember that the 4 MHz crystal is an XT, not a HS crystal, change your config bits
accordingly.
Chapter 9 Motors 285
286 Chapter 9 – Motors
Chapter 9 Motors 287
288 Chapter 9 – Motors
Since we could not use the TMR0 to set the 20 ms period, you will see that I actually set delays
for the on time and off time off both the CW and CCW modes, each adding up to 20 ms.
We are using a MAN74. This is a common cathode type display which means that it is active
with a 1 on the input segments and the commons are all tied to ground. Logic 1 = light is on.
Now for your Digital course you are using a MAN72. This is a common anode type display
which means that it is active with a 0 on the input segments and the commons are all tied to + 5
volts. Logic 1 = light is off. I‘ve shown them below, side by side. The MAN74 is on the right.
As you can see, each display has different pins ‗missing‘. The MAN72 has no pins at positions
4, 5, and 12. For Micros we are using the MAN74 which has no pins at positions 3, 5, 10 and
11. Remember we are using the MAN74. Don‘t mix them up. They won‘t work properly.
If you look at the above illustration to the left you can see that each light segment has a label of
A – G. If you look at the table on the right you can see which pin number that segment is
associated with. Pins 3, 5, 10, 11 are Not Connected. Pins 4 and 12, the common cathode pins
294 Chapter 10 – Frequency, Sound and Displays
are tied to ground. And Pin 9 is tied to 5 volts through a 220 ohm resistor, it is your power
indicator light.
When we program a 7- segment display we use an 8 bit address and simply connect it to the
corresponding pins. For our example we are going to use Port B for our outputs because all the
pins are together and its easy to visualize.
Now when we write our program, we treat the segments as binary bits in any address with Bit 7
as the MSB and Bit 0 as the LSB.
We would need to put 1s on segments A, F, E, and D which translates to bits 1, 6,5, and 4 if we
refer to the table above.
BIT 7 6 5 4 3 2 1 0
Value 0 1 1 1 0 0 1 0
And of course this translates right into a hex code. We divide the table up into groups of 4 bits
and away we go.
Chapter10 Frequency, Sound and Displays 295
Using the chart on the previous page and the letter and number outlines shown above, fill in the
table below for each of the bit values and subsequent hex codes for 0 – F. I have filled in C for
you.
TO Segment/ Hex
Display PortB bit F E D C B A Code
G Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Bit 7
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
A 0
B 0
C 0 1 1 1 0 0 1 0 72
D 0
E 0
F 0
Now on to our lab. Read the lab over and create your flowchart.
Build the following circuit, don‘t forget your program documentation, and label all of the pinouts
on your diagram.
296 Chapter 10 – Frequency, Sound and Displays
Remember to keep your wiring nice and neat and flat to the board for easy troubleshooting.
Once you have completely tested your hardware, move on to the software portion shown below.
Chapter10 Frequency, Sound and Displays 297
298 Chapter 10 – Frequency, Sound and Displays
Chapter10 Frequency, Sound and Displays 299
The SvenSeg subroutine is a string that gives us our BCD values. You will probably notice that
the values are entered in reverse order (they are backwards) This is important.
The RETLW command is a neat little instruction that loads a value into the work register and
returns to the next line all in one instruction.
The way it works is we specify the length of the subroutine. This is measured from the start of
the subroutine. Our subroutine starts on line 48 and ends on line 80. That‘s 32 decimal
addresses. We convert this to hex and we get 20. When we call the subroutine its going to count
20 hex addresses from the beginning of the subroutine and start there, working backwards.
The end result is that you should see the display counting from 0 – 9 and restarting at about 1
second intervals. There is a little more than that before the 0.
300 Chapter 10 – Frequency, Sound and Displays
Modify your program to count in hex from 0 – F. Don‘t forget to modify your subroutine length.
You can add this part to the bottom of your documentation.
Chapter10 Frequency, Sound and Displays 301
It‘s sort of like a speaker. It won‘t make any noise if you just hook it up power and ground. It
needs a crystal to resonate properly. This is not to be confused with a piezoelectric buzzer which
operates from a DC power supply directly and will sound if it is hooked up to power and ground.
So throw it on your board and hook it up to power and ground and see. Does it make any noise?
The other difference between the buzzer and the transducer is that with the buzzer, varying the
frequency will not vary the notes whereas with the transducer it will.
We are going to start with a very simple program and circuit just to turn the buzzer on for two
seconds then off for two seconds.
302 Chapter 10 – Frequency, Sound and Displays
As you know already from your other labs, our incoming frequency is automatically divided by
4.. So our 20 MHz crystal is brought down to 5 MHz. To get our instruction cycle time, we
take the inverse of that to give us .2 µs per instruction.
Okay now that we‘ve covered that, lets talk a bit about sound.
When it comes to making music, each note has its own frequency. I‘ve shown it in the chart
below. To make the desired note and in the desired octave, we must use the dividers shown in
the chart on the next page. But Woah! Hold your horses, those numbers are huge and we only
have 8 bits to work with.
So what we are going to do is to find an octave that we can use, and then use a little subroutine
which divides each note in half and then go to it for as many times as we need to get to the
desired octave.
To get a range of divider numbers that would all fit into the 0 – 255 range we would have to go
up to Octave 10. Say we want to be at Octave 5. We would use that little subroutine which
divides by 2, five times to come from Octave 10 to 5. Each time the frequency would be
divided by 2 until we reached the frequency for Octave 5.
Let‘s take the note A for example. At Octave 10, the divider is 177.56 and the Frequency is
28160.
Our first division would bring the Frequency to 14080 (9th Octave)
Our second to 7040 (8th Octave)
Our third to 3520 (7th Octave)
Our fourth to 1760 (6th Octave)
And our fifth to 880 (5th Octave)
Chapter10 Frequency, Sound and Displays 305
The delay line starts the delay. We load the frequency for the specific note and the rest of the
subroutine basically divides in it half and decrements the value in the Divider until it has been
divided by 2 five times. Of course 25 = 32, and 28160 ÷ 32 = 880 which is exactly where we
want to end up.
Then later on, we will call the delay as many times as we need to.
306 Chapter 10 – Frequency, Sound and Displays
Chapter10 Frequency, Sound and Displays 307
308 Chapter 10 – Frequency, Sound and Displays
Chapter10 Frequency, Sound and Displays 309
Yeah I know it wasn‘t perfect. But you can still make it out.
310 Chapter 10 – Frequency, Sound and Displays
You will notice that instead of calling the delay 5 times, I put a counter in at the beginning of the
actual delay to count if down 5 times for us. I can change this value at any time and bring the
song up or bring the song down an octave.
Chapter10 Frequency, Sound and Displays 319
Along with your program documentation and flowchart, you will also hand in:
Take the ICP cable out of your kit. You cant miss it, it‘s the only cable in there. 6 pin. Plug it
into your programmer on one end and into your board on the other end.
Make a connection for these wires on your board. You can try putting similar coloured wires into
the end of the connector or you can just cut the end off and put it straight into your board as I
have done. I have done this in order to illustrate it better.
We are going to be using the flashing LED circuit that you have done already. We will have to
change our output pin because PB7 and PB6 are needed for the ICP cable connection. We will
move it to PB1. PB3 we will tie to ground through a resistor.
Chapter10 Frequency, Sound and Displays 321
322 Chapter 10 – Frequency, Sound and Displays
So the only four wires we are hooking up are VPP (into the MCLR pin), PGD (RB7), PGC
(RB6) and Ground.
Load and make changes to the Flashing LED lab. Leave the PIC in the circuit, don‘t put it into
the programmer and program it using the PICKit2 software. It should transfer properly and your
LED should be flashing. If it is not, make sure you have good connections between all of the
wires.
Chapter10 Frequency, Sound and Displays 323
Appendix A – Answers to Lab Book Questions 325
a) 310
b) 17010
c) 25510
d) 1210
e) 18910
f) 4510
a) 11111002
b) 10110012
c) 1010102
d) 10110112
e) 111101002
f) 101111012
a) 8D16
b) B316
c) B16
d) F3D16
e) 3516
f) AA16
a) 1100 00012
b) 1101 00112
c) 0010 01002
d) 0001 01012
e) 1010 10102
f) 0101 01012
326 Appendix A -- Answers to Lab Book Questions
a) 24610
b) 5210
c) 4010
d) 19410
e) 7710
f) 17010
a) 1A716
b) 3D16
c) 5B16
d) DA16
e) 40416
f) 13C616
5. a) 610 ( 910 – 410 = 5 10 (1’s comp) +110 = 610) Rolls over to 1010
b) 7810 (9910 – 1210 = 7710 (1’s comp) +110 = 7810 Rolls over to 10010
c) 737 10 (999 10– 26310 = 73610 (1’s comp) + 110 = 73710 Rolls over to 100010
d) 2376 10 (999910 – 762410 = 237510 (1’ comp) + 110 = 237610 Rolls over to 1000010
7. a) 416 (F16 – C16 =1112 – 11002 (converting to binary) = 112 (1’s comp) + 12 = 01002= 416
b) 25 16 (FF16 – DB16 = 1111 11112 – 1101 10112 = 0010 01002 (1’s comp) + 12 0010 01012
= 2516
c)FDD016 (FFFF16 – 023016 = 1111 1111 1111 11112 – 0000 0010 0011 00002 = 1111 1101
1100 11112 (1’s comp) + 12 = 1111 1101 1101 00002 = FD D016
d) 0988 16 (FFFF16 – F67816 = 1111 1111 1111 11112 – 1111 0110 0111 10002 = 0000 1001
1000 01112 (1’s comp) + 12 = 0000 1001 1000 10002 = 09 8816
b) 2210 3310 – 1110 = 2210 (straight subtraction) Or add 2’s comp (9910 – 1110 = 8810 (1’s
comp) + 110 = 8910 (2’s comp) 3310 + 8910 = 12210 drop the carried 1 and you get 2210
c) 33810 66610 – 32810 = 33810 (straight subtraction) Or add 2’s comp (99910 – 32810 = 67110
(1’s comp) + 110 = 67210 (2’s) 66610 + 67210 = 133810 drop the carried 1 and you get
33810
d) 25810 153210 – 127410 = 25810 (straight subtraction) Or add 2’s comp (999910 – 127410 =
872105 (1’s comp) + 110=872610 153210 + 872610 = 10258 10 drop the carried 1 and
you get 25810
328 Appendix A -- Answers to Lab Book Questions
9. a) 02 12 – 12 = 02 (straight subtraction)
Or add 2’s comp (12 – 12 = 02 (1’s comp) + 12 = 12 (2’s comp) 12 + 12 = 102
drop the carried 1 and you get 02
b) 012 102 – 012 = 012 (straight subtraction) Or add 2’s comp (112 – 012 = 102 (1’s comp) +
12 = 112 (2’s comp) 102 + 112 = 1012 drop the carried 1 and you get 012
c) 0112 1102 – 0112 = 0112 (straight subtraction) Or add 2’s comp (1112 – 0112 = 1002 (1’s
comp) + 12 = 1012 (2’s cmp) 1102 + 1012 = 10112 drop the carried 1 and you get 0112
d)10012 10102 – 00012 = 10012 (straight subtraction) Or add 2’s comp (11112 – 00012 = 11102
1’s comp) + 12 = 11112 (2’s) 10102 + 11112 + 1 10012 drop the carried 1 and you get 1
0012
Converting to binary 10102 – 01102 = 01002 (straight subtraction Or add 2’s comp (
11112 – 01102 = 10012 (1’s comp) + 12 = 10102 (2’s) 10102 + 10102 = 1 01002 drop the
leading 1 and you get 01002 or 416
b) 1116 BB16 – AA16 = 1116 (straight subtraction) Or add 2’s comp (FF16 – AA16 = 5516 (1’s
comp) + 116 = 5616 (2’s comp) BB16 + 5616 = 11116 drop the leading 1 and you get
1116
Converting to binary 1011 10112 – 1010 1010 2= 0001 00012 (straight subtraction) Or
add 2’s comp (1111 11112 – 1010 10102 = 0101 01012 (1’s comp)
+ 12 = 0101 01102 (2’s comp) 1011 10112 + 0101 01102 = 1 0001 00012 drop the
leading 1 and you get 0001 00012 or 11
c) BB16 CD16 – 1216 = BB16 (straight subtraction) OR add 2’s comp (FF16 – 1216 = ED16 (1’s
comp) + 1 16= EE16 (2’s cmp) CD16 + EE16 = 1BB16 drop the leading 1 and you get
BB16
Converting to binary 1100 1101 – 0001 00102 = 1101 11012 (straight subtraction) OR
add 2’s comp (1111 11112 – 0001 00102 = 1110 11012 (1’s cmp)
+ 12 = 1110 11102 (2’s cmp) 1100 11012 + 1110 11102 = 1 1101 11012 drop the
leading 1 and you get 1101 11012 or BB16
d) 2716 6416 – 3D16 = 2716 (straight subtraction) OR add 2’s comp (FF16 – 3D16 = C216 (1’s
comp) + 116 = C316 (2’s cmp) 6416 + C316 = 1 2716 drop the leading 1 and you get 2716
Converting to binary 0110 01002 – 0011 11012 = 0010 01112 (straight subtraction)
OR add 2’s comp (1111 11112 – 0011 11012 = 1100 00102 (1’s comp) + 12 = 1100
00112 (2’s comp)
Appendix A – Answers to Lab Book Questions 329
0110 01002 + 1100 00112 = 1 0010 01112 drop the leading 1 and you get 0010
01112 0r 2716
Chapter 5
1. MOVLW b‘10101111‘
TRIS 05
Input bits: 7,5,3,2,1,0
Output bits: 6, 4
Port: A
2. MOVLW 024
TRIS 07
Input bits: 5,2
Output bits: 7,6,4,3,1,0
Port: C
3. MOVLW b‘10101010
TRIS 08
Input bits: 7,5,3,1
Output bits: 6,4,2,0
Port: D
Chapter 7
AND Gate
32 0 0 1 1 0 0 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
55 0 1 0 1 0 1 0 1
330 Appendix A -- Answers to Lab Book Questions
10 0 0 0 1 0 0 0 0
OR Gate
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
A6 1 0 1 0 0 1 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
DD 1 1 0 1 1 1 0 1
FF 1 1 1 1 1 1 1 1
NOT Gate
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
F1 1 1 1 1 0 0 0 1
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
0E 0 0 0 0 1 1 1 0
XOR Gate
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
C8 1 1 0 0 1 0 0 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
8C 1 0 0 0 1 1 0 0
44 0 1 0 0 0 1 0 0
Appendix A – Answers to Lab Book Questions 331
Chapter 8 – Timing
Delay Exercises
1. Look at the following table. Given the MOVLW value and a clock frequency of 1
MHz, how many instruction cycles are there and how long will it take to execute this
delay?
TOTAL
Instruction Cycles ___________ 588
2. Look at the following table. Given the value MOVLW value and a clock frequency of 4
MHz, how many instruction cycles are there and how long will it take to execute this
delay?
TOTAL
Instruction Cycles ___________ 207
3. Look at the following table. Given the value MOVLW value and a clock frequency of
20 MHz, how many instruction cycles are there and how long will it take to execute this
delay?
TOTAL
Instruction Cycles ___________ 701
6 0
5 1
4 0
3 0
2 1
1 0
0 1
Hex Answer 25
Appendix A – Answers to Lab Book Questions 335
6 1
5 1
4 0
3 0
2 0
1 1
0 1
Given the value D4, fill in the values for each bit in the INTCON Register below
6 1
5 0
4 1
3 0
2 1
1 0
0 0
Appendix A – Answers to Lab Book Questions 337
And if we were to work it backwards like the table shown below, we would have the following
values:
Bi Valu Meaning
t# e
7 1
6 1
5 1
4 0
3 0
2 0
1 0
0 1
338 Appendix A -- Answers to Lab Book Questions
Hex Value: 2B
Binary Value 0010 1011
6 1
5 0
4 0
3 1
2 0
1 1
0 1
Appendix A – Answers to Lab Book Questions 339
And if we were to work it backwards like the table shown below, we would have the following
values:
6 0
5 0
4 1
3 0
2 0
1 1
0 0
340 Appendix A -- Answers to Lab Book Questions
TO Segment Hex
Display g f e d c b a Bit 0 Code
0 0 1 1 1 1 1 1 0 7E
1 0 0 0 0 1 1 0 0 0C
2 1 0 1 1 0 1 1 0 B6
3 1 0 0 1 1 1 1 0 9E
4 1 1 0 0 1 1 0 0 CC
5 1 1 0 1 1 0 1 0 DA
6 1 1 1 1 1 0 0 0 F8
7 0 0 0 0 1 1 1 0 0E
8 1 1 1 1 1 1 1 0 FE
9 1 1 0 1 1 1 1 0 DE
A 1 1 1 0 1 1 1 0 EE
B 1 1 1 1 1 0 0 0 F8
C 0 1 1 1 0 0 1 0 72
D 1 0 1 1 1 1 0 0 BC
E 1 1 1 1 0 0 1 0 F2
F 1 1 1 0 0 0 1 0 E2
References 341
References
Bates, Martin PIC Microcontrollers: An Introduction to Microelectronics 2nd Edition Elsevier
Burlington MA 2005
Mazidi, MyhamadAli, McKinlay, Rolin D, Causey, Danny PIC Microcontrollers and Embedded
Systems Pearson New Jersey, 2008
Online Resources
DC motors
http://www.electronics-tutorials.ws/io/io_7.html
http://zone.ni.com/devzone/cda/ph/p/id/287
Servos
http://www.ermicro.com/blog/?p=771
http://www.best-microcontroller-projects.com/servo-motor.html#Software
http://www.instructables.com/id/Use-a-PIC-Microcontroller-to-Control-a-Hobby-Servo/
http://www.instructables.com/id/Use-a-PIC-Microcontroller-to-Control-a-Hobby-Servo/
http://www.leang.com/robotics/info/articles/servo/drvservo.html
PWM control
http://www.pages.drexel.edu/~kws23/tutorials/PICTutorial/PICTutorial.html#Construction
http://www.best-microcontroller-projects.com/pwm-pic.html
http://www.pages.drexel.edu/~kws23/tutorials/PWM/PWM.html#Parts
http://www.winpicprog.co.uk/pic_tutorial8.htm
http://www.winpicprog.co.uk/pic_tutorial.htm
General tutorials
http://www.winpicprog.co.uk/
Stepper Motor
http://www.imagesco.com/articles/picstepper/02.html
http://www.sapiens.itgo.com/documents/doc37.htm
http://www.solarbotics.net/library/pieces/parts_mech_steppers.html
http://zone.ni.com/devzone/cda/ph/p/id/247
http://www.stepperworld.com/Tutorials/pgUnipolarTutorial.htm
TMR1
http://www.edaboard.com/ftopic275280.html
342 References
http://www.imagesco.com/articles/picservo/02.html
excellent dc motor
http://www.solarbotics.net/starting/200111_dcmotor/200111_dcmotor2.html
TMR2 Explanation
http://www.microcontrollerboard.com/pic-timer2-tutorial.html
INDEX