You are on page 1of 21

Pick A PIC Project

Home

PIC Programmer MkV

Instruction Set for PIC16F628


PIC16F628 data (pdf)
BlankF628.asm
BlankF628.txt

PIC16F628A.inc

See more projects using micros:


Elektor,EPE,Silicon Chip

Notepad2.zip     Notepad2.exe 


Library of Sub-routines "Cut and Paste"
Library of routines:   A-E   E-P    P-Z 

P2(100 Helpful Hints)


P3 The XOR Trick
 
 

If you want to get into the next generation of "project-design," you need to look into
the magic world of a MICRO.
A micro can simplify your project, reduce its size, increase its capability and reduce the cost.
But best of all, it can be centered around a software program that can be hidden from prying eye and this will
make your project unable to be copied.   
Talking Electronics has produced a range of projects using a MICRO and this article will get you into
designing your own project at the lowest cost.
There are a number of microcontrollers on the market and various paths you can follow to produce a
microcontroller project - at least 3 different manufacturers and more than 3 paths are available.
Ours is just one of these options and in our opinion it is the cheapest and simplest way to get into
microcontroller programming.
We have chosen the PIC micro, by MicroChip as it has a huge following on the web with a large range of
projects and support groups.
In addition we have chosen hand-programming using a template to get you started. Our method produces
lines of code where each line is an instruction. This is the simplest way a PIC program is produced and you
produce it by hand.
The instructions are fairly easy to understand as they consist of the first letter of words of a sentence, such as
btfss (bit test file and skip if set) and these are called mnemonics.
There are only (about) 35 instructions and these cover the entire capability of the microcontroller.
This is the simplest and easiest way to write a program and is aligned to the early days of programming
where it was called "Machine Code."
This is the "Lowest Level Language" as the instructions are directly understood by the micro. Any other
language is a "higher level language" as each instruction is usually more powerful but much harder to add to
the program. You need to learn these languages and how to write them in a program (how to structure each
line) as they use symbols such as: "{, }, [, ], <<, >>"  to produce code such as:

1
void waitsync(void)
{
re: while (RX)
{
};
TMR0=0;
if(errorbyte > MAXERR) { errmark=1; return;};

Our approach avoids a lot of complexity and frustration. It only involves 35 instructions.
We have made programming even easier by providing a number of complete projects as well as "sub-
routines" that can be copied and pasted into your program.
On top of this we have provided a LIBRARY OF TERMS to help you understand all the terms. And to simplify
things we have concentrated on two PIC chips. An 8 pin and an 18 pin chip. The 8 pin chip can be either
PIC12F629 or PIC12F675 and the 18 pin chip is PIC16F628 or PIC16F675.
Even though these chips are the simplest in the range, do not under-estimate their capability.
The PIC16F628 can easily replace 20 individual logic chips and produce a project with amazing capability.
We have produced a Tic Tac Toe game that always wins (or draws) and a Dialing Alarm-2 that produces
DTMF tones, a Hee Haw sound and a feature that opens up a microphone to let you listen to the target zone.
By using our suggestions, you can use the chip to its fullest and create a more-complex program than any
other method. You don't have to learn any other "language" or get involved with any "developmental tools"
(some of these are very frustrating to use).
We have also used very simple "programming techniques" in that our "lines of code" are very easy to follow
and clearly explained. Some developers use "very clever" instructions that take "hours to understand" and
this leaves you in a state of frustration. We do it "the simple way" and you feel bolstered after every project
you complete. 
Of course you cannot produce an "all talking, all dancing" project with these tiny micros but our aim is to get
you started.
If you can visualise the capabilities of a 5 chip project; multiply this by 10 and you have the possibilities of
what you are about to encounter. This may seem surprising but as your program gets larger, you can use
some of your pre-written sub-routines and this makes it more-powerful and the last-few lines of code can
achieve enormous capabilities.
Producing a microcontroller design is often cheaper than using lots of discrete chips; plus the board is
smaller. But most important, the program can be "locked away" from prying eyes and can be marketed.
Now is the time to think of some ideas. In most cases they will be "do-able." And we will show you the way.

Below is a list of projects we have developed for the two chips as well as PIC Programmer MkV, for those
with a desk-top computer or tower and PICkit-2 Burner for those with a lap-top computer.
First you have to decide on the programmer. It will depend on the "port" you have on your computer.
 
Look at your computer or "tower" or lap-top. Does it have a serial port:

You need to buy PIC Programmer MkV kit

a USB port:

You need to buy PICkit-2 Burner kit.

Once you have decided on a programmer, you will need to buy the kit and assemble it.
Connect it to your computer and go to the projects below. Start with: World's Simplest Program. It uses a
PIC12F629 and has only 4 instructions to blink a LED. It shows how the Watch-Dog Timer resets the chip

2
every 150mS.  It's not a normal type of program but it tests the micro, the programmer and the circuit you
have constructed.
Then alter one or two of the instructions and see what happens. If you can do this, you are ready to start.
The projects are divided into two groups: PIC12F629 (8 pin) or PIC16F628 (18 pin).
Both micros use the same instruction-set (only some small differences) and both are identical when it comes
to learning how they operate. The only difference is the 8 pin micro has 5 in/out lines and 1 input-only line.
The 18 pin micro has 15 outputs (plus one input-only line).

WE START AT "GROUND ZERO"


The following list of data sheets, projects and "help" articles is like a course. It covers everything you need to
know about producing a PIC microcontroller project.
Everything can be accessed via links on Talking Electronics website (http://www.talkingelectronics.com) and
is also available on CD from Talking Electronics for $10.00 posted to anywhere in the world.
This is the lowest-cost course ANYWHERE on the web and it starts at less than $50.00 for a PIC
programmer and project. You also get a CD containing all the necessary information including instructions for
all the kits. 
Even though our approach is the simplest way to get into PIC programming, you may have a question and it
can be answered by contacting Colin Mitchell or going to a forum, where microcontroller questions will be
answered 24 hours a day! One of the forums is: http://www.electro-tech-online.com/

USING OTHER MICROS


There are a number of other micros on the market and many of them offer a similar range, price and set of
features as the PIC.
We have chosen the PIC because of the enormous amount of help and number of projects on the web.
At this point in time, no-one has written an article to say any other processor is markedly better than a PIC
and so you are not being steered down a "dead end."
One of the other manufacturers ceased to produce their smallest micro and that's why their "attiny" range was
not chosen.  We were just about to promote the attiny12 series when it ceased to be manufactured.  Luckily,
the equivalent PIC chip is cheaper.

START HERE WITH PIC PROGRAMMING


A set of experiments using the LED Fx PC board. The course contains a folder with the file for writing your
program (NotePad2), converting your .asm to .hex (MPASM) and for burning a PIC micro (ICPROG).
You will need a fully built LED Fx, and Pic Programmer MkV
If you have a USB port, you will need PIC-2 USB Burner  and PICkit2 software.

Here are the data sheets, projects and "help" articles:

PINOUTS

Blank template for PIC12F629 or select a PIC12F629 project and remove unwanted code.
Blank template for PIC16F628 or select a PIC16F628 project and remove unwanted code.
To work on (or produce) a template you will need: Notepad2.zip   or  Notepad2.exe 

3
Data sheet for PIC12F629 (5MB .pdf)
Data sheet for PIC16F628 (2.6MB .pdf)
Library of terms  A-E
Library of terms  E-P
Library of terms  P-Z
List of Instructions for PIC12F629    then go to: Explaining the Instructions  &  more details
List of Instructions for PIC16F628   then go to: Explaining the Instructions   &   more details
PIC12F629 Pinout   PIC16F628 Pinout  Files in PIC12F629 and PIC16F628
Software for PIC Programmer MkV - Icprog105c
Surface Mount Pin-outs
The XOR Trick - learning about the power of the XOR function
2 Things at Once - tutorial - using interrupt and isr to do 2 things at the same time.
100 Helpful Hints - things you need to know, to be able to produce a program

PROJECTS:
Pic Programmer MkV  Simple PIC programmer - uses just 12 Parts - for serial port
PIC-2 USB Burner for lap-top USB port
World's Simplest Program for a PIC12F629. It uses only 8 instructions and blinks a LED. It shows how the
Watch-Dog Timer resets the chip every 18mS to 2400mS if not cleared.
Kit contains PC board, 6 pin to 5 pin adapter, 8pin socket, chip, LED, resistor and pins to create a
development board for burning 8 pin PIC chips. 

PIC12F629:
Alarm Space Gun uses PIC12F629
Capacitance Meter - measure capacitor values from 1p to 100u
Crossing Sound - for your model railway layout
EEPROM Speed - write and read EEPROM to see how fast it gets done.
Happy Birthday - uses a piezo and PIC12F629  to produce Happy Birthday tune
It's A Small World - uses a piezo and PIC12F629  to produce It's A Small World tune 
Joy Stick Controller  - control 2 servo's via a Joy Stick
Lego Chaser - Seven routines on two sets of 10 LEDs - uses a PIC12F629
LED Fx - 12 different effects on a set of 3 ultra bright white LEDs.
Lift Counter Uses a PIC12F629 with LED display and up/down buttons.
Music Box  Uses PIC12F629 and plays 11 melodies
Sky Writer  Uses a PIC12F629 to put messages "in the air."
Servo Motor Controller - control 2 servo's via a Joy Stick
Solar Tracker-1  Uses a PIC12F629 with H-bridge to allow a solar panel to track the sun.
Touch Switch - use a PIC to create on/off via a touch pad
Whistle Uses a PIC12F629 to detect a whistle - similar to Whistle Key Finder.
2 Digit Counter using a PIC12F629
2 Digit Up/Down Counter  5 different designs. Uses PIC12F629 or PIC16F628 chips.
12 Digit Running Sign - uses a 12 digit calculator display to produce running messages
40 LED Badge  - uses a PIC12F629 to show effects on 40 LEDs

PIC12F675:
Audio CRO uses PIC12F675 to produce a simple audio CRO via a spinning PCB on the shaft of a motor. A
good mechanical as well as electronic project.

PIC16F628:
Dial Alarm-2 Dials 2 phone numbers via DTMF and produces a Hee Haw Sound. Has a in-built microphone to
listen to the target zone. Uses a PIC16F628
PIC Lick-1  A development board for the PIC16F628
Simon 4 buttons are used to repeat a sequence of Lights and sounds. Uses a PIC16F628
Stroop Game A very interesting Psychological game named after the doctor who introduced the test. Uses a
PIC16F628
Tic Tac Toe  A challenging game where the computer wins or draws. Uses a PIC16F628.
15x7 Display using a PIC16F628

4
2 Digit Up/Down Counter  5 different designs. Uses PIC12F629 or PIC16F628 chips.
12 Digit Display A 12 Digit calculator display is used to produce a running sign and other effects. Uses a
PIC16F628

HELPFUL FACTS
Here is some helpful facts on the PIC12F629 and PIC16F628 micros:
The PIC12F629 has 1024 locations for your program. This is 4 pages and is commonly called 1k of memory.
A page has 256 locations (0FFh locations). Page0 consists of locations 00h to 0FFh. Page1 consists of
locations 100h to 1FFh. Page2 consists of locations 200h to 2FFh. Page3 300h to 3FFh.
The PIC16F628 has 2048 locations for your program. This is 8 pages. This is 2k of memory for your program.
Goto and Call instructions access the whole of memory.
A table can only be 0FFh locations long and it must not go over a border. For instance it can be from location
006h to 0FFh  or 100h to 1FFh or 300h to 3FEh (for the PIC12F629) - the last location stores the oscillator
calibration-bit and cannot be used for your program. 
The microcontroller has different areas for storing different pieces of data. There are 4 main areas that
contain files or registers to store these values.
The first and largest area is 1k or 2k and stores your program. This is called the CODE AREA  or
PROGRAMMING AREA  or CODE SPACE and is in the CORE AREA of the chip. This area is also in "BANK
0" of the micro but is normally referred to as the CORE AREA.
The second and third areas contain Special Function Registers or Files and these are used by the CPU
(Central Processing Unit - the heart of the microcontroller) to control the operation of the chip. These files
have names such as STATUS register, File Select Register, Timer1 HIGH, Timer1 LOW and the in/out port
called GPIO or PORTA, PORTB. These files (or Registers) along with others, are in BANK0 - the core area of
the chip, while other Registers such as OPTION register, Oscillator Calibration register, EEDATA register,
TRIS (the files that determines if a pin will  be input or output) and others are in BANK1.
To place data into these registers or read data from them, you must "switch banks." This is called BANK
SWITCHING and is done by adding an instruction to your program thus:
To change from the core area (Bank0) to Bank1, the instructions is:
bsf status, rp0 ;to get to Bank 1
To change from Bank1, back to the core area (your programming area), the instruction is:
bcf status, rp0 ;to get to bank 0
The STATUS file is located in both areas and that is why it can be used to switch from one bank to the other.
You must switch to Bank0 after accessing files in Bank1, to execute further instructions in your program 
The fourth area is EEPROM area. This area contains 128 bytes of data that can be altered at any time during
the running of a program and data will be retailed when power is removed.
EPROM memory is not CODE area (your program area) or General Purpose Register memory. They are all
separate.
EPROM memory is very slow in writing but fast in reading. It can be written to a million times and needs no
power to hold its memory.
Code space memory (flash memory) has about 100,000 write-cycle capability and cannot retain data without
power.
General Purpose Register memory is STATIC RAM. These are the files from 20h to 5Fh (and more) that you
use to store temporary data during the running of your program. It does not retain data without power.
The "w Register" is the "working Register" and transfers data from one file (or routine) to another.  

READ THE INSTRUCTIONS


All our projects come with a discussion and an explanation of "How the Circuit Works."
Almost all the projects can be constructed using the circuit diagram and photos, but if it doesn't work, you
need to read the documentation.
Electronics engineers don't like reading. That's why we have made it easy to build our projects. All the PC
boards have an overlay and nothing else is needed to put the project together.
But if you want to know how the circuit works or how the project was designed, you need to READ THE
ARTICLE.

Going Further
No-one has produced projects as complex as our Dial Alarm-2 or Tic Tac Toe, using simple hand-
assembly techniques and we have shown the capability of tiny micros.
5
But If you want to design something more complex, you will have to go to the next step by learning
a "Programming Language." This may be "BASIC," or "C" or "JAL" or one of a number of other
languages. These are all fully covered on the web - via a Google search. And, of course, these will
open up a whole new field of expansion.
At least we can say: "we got you started."
 

Chapter 2
100 Helpful Hints

Home 

Instruction Set for PIC12F629


PIC12F629 data (pdf)
BlankF629.asm

PIC12F629.inc

See more projects using micros:


Pic A PIC Project

Notepad2.zip     Notepad2.exe 


Library of Sub-routines "Cut and Paste"
Library of routines:   A-E   E-P    P-Z 

PIC Programmer MkV


P1(list of projects)
P3 The XOR Trick
 
 

Here are lots of helpful hints to get you started in programming. Programming is easy if you follow our
suggestion of taking a program from the list of projects and modifying it slightly by changing one or two
instructions at a time.
It's a lot more tricky writing a program from the start. And we don't advise this AT ALL.
But if you want to find out about some of the "tricky things" in a program, here is a list of 100 Helpful Hints.
Don't forget to see our Library of routines:   A-E   E-P    P-Z   It covers lots of things.

BINARY, DECIMAL AND HEX


The numbers in your program can be written in binary, decimal or hex.
Here is how to write them:
;Binary numbers are shown as b'00000000' or b'11110001'
;Decimal number are shown as: .10 .255 or d'10' - note the decimal point.
;Hex numbers are shown as: 0Ch, 0ffh, 0x2F, 0x20, 0x0ff  - "0" must be placed before any letter as 0xff will
not be read correctly.

You can use a mixture of all three providing you keep to the correct formatting.

6
Or you can specify the way numbers are to be interpreted by the compiler by adding:
radix binary
radix dec    (a number such as 20 will be treated as a decimal).
radix hex

cblock
A simpler way to list all the names for the files is to use cblock.   A program inside the compiler takes each
name and allocates a file, starting at 20h:

           cblock    0x20 (block of constants)


delA     
loops   
display  
jump  
tLOW
tHIGH
tREC  
          endc

cblock is very easy to use. You can add or remove names without having to allocate file numbers.

CALL AND GOTO


The  CALL instruction for a PIC12F629 accesses ALL MEMORY.
Using the:
     call  sub-routine
instruction will send the micro to another address such as a sub-routine and if the sub-routine contains the
instruction:
    retlw   00
the micro will go to the next instruction after the call instruction.
If you use
    goto   sub-routine
the micro will go to the sub-routine but when it sees the
  retlw   00
instruction, it will go to a previous call.

DEFINING THINGS
When writing a program, the layout must be in columns so that the assembler will know how to interpret each
item. This layout is called a TEMPLATE and the program is saved as .asm  (assembly program)
The first column contains Labels.
The second column contains Directives (such as equ, end) and Mnemonics (instructions)
The third column contains Operands, and
The fourth column contains Comments (such as ;output HIGH  ;test zero bit)

Pink – Labels     Blue – Directives        Black – Mnemonics 


Red – Operands         Green - Comments

del1     equ     0x20     ;store del1 in file 20 hex

           movlw   0x34    ;load w with 34  hex


loop    movwf   del1
           addwf   del1,w
           goto      loop

7
           sleep

           end

During the running of a program you may want to decrement a file to create a delay.
The file is called a temporary storage and a set of files from 20h to 5Fh is available in the PIC chips we are
promoting.
At the beginning of a program, each file that you want to decrement, or store a number of loops, or hold a
value for displaying later, or hold the jump value for a table, is given a name such as: delA, loops, display,
jump. These files are sometimes called Variables.
Each name is then allocated a  file, starting at 20h, 21h, 22h, etc.
delA       equ   20h
loops      equ   21h
display    equ   22h
jump      equ   23h
 

goto  $+1     goto  $-1       goto  $


The instruction:
     goto   $+1
sends the micro to the next instruction but takes 2uS.  (A nop instruction takes 1uS)

The instruction:
     goto   $-1  
sends the micro to the previous instruction.  This can create an endless loop!

The instruction:
     goto   $  
creates a halt as $ represents the current address.

You can also use this terminology to go to an instruction before a sub-routine, such as:
     goto   delay-1
This sends the micro to the line before the delay sub-routine. This allows you to use the delay sub-routine for
different timings. The line before the label: "delay" has a load-value of 3Fh and this can be used in the sub-
routine. Or you can preload a value into w and go to the sub-routine at the actual label: delay.
This is how the delay sub-routine is structured:

            movlw     3Fh


delay    movwf     temp
            decfsz    temp,w      ;the decremented value of temp is placed in w
            goto       delay
            retlw       00

Normally we use the instruction decfsz temp,f   where the temp file holds the decremented value. But to
create a multiple input delay sub-routine we need to use: decfsz temp,w and the previous instruction:
movwf     temp  to put the decremented value into temp.  
To use the load value 3Fh, use the instruction: call    delay-1
To load temp with any other value, use the instructions:
         movlw      xxh
         call          delay

DsPIC
Some of the latest PIC chips have part numbers such as  dsPIC30F1010. These are classified as Digital
Signal Controller chips as they have the capability of  processing digital signals and contain a fully
implemented digital signal processor (DSP). 

8
IN/OUT PORT
The IN/OUT port on a PIC12F629 is file 05h. This port corresponds to pins 7, 6, 5, 4, 3, and 2 for GP0, GP1,
GP2, GP3 GP4 and GP5.
Remember: GPIO,3 (GP3) (pin 4) is an INPUT-ONLY pin.
When writing a program, use GPIO,0 GPIO,1 GPIO,2 GPIO,3 GPIO,4 GPIO,5 in your program and the
compiler will do the rest. (GPIO = General Purpose Input/Output).
For instance, If you want to SET (make HIGH) pin 7, you must do two things:
1. Make sure GPIO,0 is an OUTPUT bit by making the corresponding bit in the TRISIO register "0."  This is
done via the following instructions: Remember: "0" = output,  "1" = input

    bsf         status, rp0      ;bank 1


    movlw     b'xxxxxxx0'    ;(x= don't care = does not matter)
    movwf    TRISIO           ;the lowest bit will be an OUTPUT
    bcf         status, rp0     ;bank 0

2. Make the lowest bit of the output port = 1 (HIGH). This is done via the following instruction:

    bsf      GPIO,0

SETTING MORE THAN ONE BIT AT A TIME


Do not set more than one bit at a time in the GPIO (in/out) port. The actual setting of a bit is very complex.
The micro reads the value of the bit, modifies it, then writes the new value and the pin may be connected to a
capacitor that take time to charge or allow the voltage on the pin to change and somewhere along the line,
the result is not transferred to the result and the state of the pin does not change. To avoid this problem, do
not create two instructions such as:

      bsf      GPIO,0


      bsf      GPIO,2

If you need to clear or set two or more output lines, perform the operation via a single instruction:

    movlw   b'xxxxx1x1'


    movwf   GPIO

or perform:  bsf      GPIO,0        bsf      GPIO,2    with other instructions between.

If you must perform the two operation in quick succession, you need to know the state of all the outputs and
include this in the value you are going to load into GPIO via movlw b'xxxxxxxx' etc. 

As can be seen from the above, the six lower bits of file 05 are connected to 6 pins of the chip and these
connect the microprocessor to the outside world.  This file is like all the other files (from 20h to 5F - 64 files)
as it can be operated-upon (incremented, decremented, shifted left or right, plus other operations). The only
difference is the contents of file 05 can be exported to the outside world and the outside world can influence
the file. When any of the bits of file 05 are configured as "out," the value of the bit will make the corresponding
pin of the chip either HIGH or LOW. When it is "set" (=1), the pin will be HIGH. When it is "clear" (=0), the pin
will be LOW.   
If you only want to change 2 or more bits and do not know the state of the other bits, you can use the
following instructions. Only bits 0 and 4 will be toggled:

      movlw   b'0001 0001    ;only bits 0 and 4 will be toggled


      xorwf    gpio,f

To set 2 or more bits:

      movlw  b'0001 0001    ;only bits 0 and 4 will be set


      iorwf    gpio,f

9
MACRO'S
A MACRO is a piece of code that "gets inserted" into your program, by a program called an assembler, during
the time when the program is ASSEMBLED. You only have to write a particular macro once, and it may be
inserted 6 times into your program. Each macro must have an specific name (called a LABEL), so the
assembler can find it.

I do not use Macros. They involve extra thinking and can take up extra space in your program.
But you will find some programmers use them and you need to know how they work.

A macro is like a sub-routine. It is written once and can be used many times in a program.
A macro has a LABEL just like any sub-routine. When you want to use a macro, the name of the macro is
written on a new line in your program and the assembler adds the instruction(s) in the macro at the location
where you have written the name of the macro.  If the macro consists of 5 lines and it is used 6 times, a total
of 30 instructions will be added to your program.
The macro will be deleted from the assembled program and only the contents of the macro will appear 6
times.
The advantage of a macro is the slightly faster execution of the program as the microcontroller does not have
to execute a call and return. The disadvantage is the extra lines of code. 

The reason for this article is to explain how a MACRO is prepared and the terms used.

The first line of a macro contains three terms:

LABEL       macro       PARAMETERS

LABEL can be any set of letters or numbers (some words cannot be used as they are used by the assembler
and a label cannot begin with a number. Use "_"  or "." if numbers are required.

macro   tells the assembler that a macro is the next item in the program.

PARAMETERS   - a list of the files to be used with a comma between each.

Any number of lines of code can now be written. These will be any of the 33 PIC instructions.

The macro ends with:

endm      ;end of macro 

Example:

count      macro  Switch 


              incf    Switch,1      ;increment the Switch file
              btfss  Switch,6      ;test bit 6 in the switch file and if it is "1," miss next instruction
              goto   $+2            ;go to endm  ($+0 is this instruction, $+1 is next instruction)
              decf   Switch,1      ;decrement the Switch file and leave the result in the file.
              endm                    ;end of macro

MCLR PIN
Pin 4 can be configured as an "Input line" (GP3) OR "Master Clear."
To configure Pin 4 as MCLR   (also written as /MCLR  or /MCLRE ) the configuration bit setting is:
_MCLRE_ON
When this pin is configured as /MCLRE, the pin resets the chip when it is taken LOW. But why waste a pin?
Use the pin as an INPUT!
To configure Pin 4 as GP3, the configuration bit setting is: _MCLRE_OFF
This instruction tells the PIC to use its internal MCLR circuitry (to keep /MCLRE high), and leaves pin 4 free

10
as an Input line. Note: MCLR pin (GP3) is INPUT ONLY.

MICROCHIP ICD PROGRAMMER


Microchip ICD programmer is sold in a round plastic case. If you have one of these and use long leads
between the programmer and the chip you are "burning," add a 2k2 resistor to the clock line and 0v rail and a
2k2 to the data line and 0v rail to makes these lines LOW IMPEDANCE. We had enormous trouble
programming a chip due to cross-talk between these two lines.

MPLAB IDE 
IDE stands for Integrated Development Environment and is part of MPLAB. MPLAB has two parts and the
section we use is MPASM. The other section allows you to load your program into a window and look at how
each register (file) is loaded or is currently holding bits (0's and 1's). It also has a single-stepping feature that
increments thorough your program and lets you see what is happening. But this program is very complex and
will cause lots of headaches, to get it up-and-running. We have kept things simple by showing you routines
that work and you simple copy-and-paste.
  

MULTIPLYING AND DIVIDING


Numbers can be multiplied by 2 by shifting the file left with the instruction rlf  total,f  Before this instruction it is
wise to clear the carry bit:  clrc
Numbers can be divided by 2 by shifting the file right with the instruction rrf  total,f  Before this instruction you
must clear the carry bit:  clrc
You can also create a value of 0.75 by using the following instructions.
Suppose you have a file called loops and you want to reduce it to 75%:

                              ;you have a file called loops


    clrc                    ;clear carry before shifting
    rrf         loops,f    ;halve the value of loops
    clrc
    rrf         loops,w   ;halve the value of loops again and put into w
    addwf   loops,w    ;to get 0.75 of original

OSCILLATOR CALIBRATION VALUE


Calibration of the oscillator is only necessary when you need precise timing, as for serial communication. In
most cases you will not have to worry about this.
To use the factory calibration value:

SetUp   org       0x00


            bsf       status, rp0     ;bank 1
            call       0x3FF           ;retrieve factory calibration value
            movwf   OSCCAL       ;update register with factory cal value
            bcf       status, rp0     ;bank 0   

The oscillation calibration value can be changed from the value supplied in the chip by adding the following
instructions to the end of your program, (BEFORE the "end" instruction of the program).

;****************************************************************
;* OSCCAL calibration value                                      
* ;****************************************************************
      org       0x3ff
      retlw   0x20

      END

11
During the  programming of the chip, the above instruction will cause the burner to go to location 3FF and
insert the value 20h as well as the instruction "return with the value 20h in W."
To create the maximum frequency, use: 3fh
Centre frequency = 20h
Minimum frequency = 00h
During the running of the program (when the chip is in the project), this value is put into the OSCCAL
location, to adjust the frequency of the internal oscillator.
To get the micro to do this, the following instructions are added to your program:

;****************************************************************
;* Calibrating the internal oscillator                              
* ;****************************************************************

       bsf       status,rp0     ;bank 1


       call      3ffh               ;get the calibration value
       movwf  OSCCAL       ;calibrate
       bcf       status,rp0     ;bank 0

The location of the oscillator calibration register is 90h. This is in Bank 1 and is identified in your program by
writing: "OSCCAL" It is a 6-bit register, with values from 00h to 3fh.

If none of the above work, or if the calibration value is missing from location 3FF (for a PIC12F629), you can
insert it by hand by carrying out the following:
1. This operation will erase the program in the chip and only install the osccal value, so make sure the
program can be re-installed after this operation.
2. Connect the chip to a programmer and open the software on your desktop: PICkit 2 Programmer.
3. Under Tools  OSCCAL, select "Set Manually" from the drop-down window that appears on the right-hand
side.
4. Scroll down to location 3FF in the Program Memory window and change location 3FF from 0000 or 3FFF
to 3420.
5. Now you can re-install the program to the chip and the oscillator will operate a mid-position of its
frequency-adjustment.
The PICkit 2 Programmer software will not burn any value placed in location 3FF, during a normal burn
operation. You must select: Tools  OSCCAL,  "Set Manually" to burn the osccal value.
 

OTHER PROGRAMMER'S CODE


You will find some of the instructions and code in other people's programs very difficult to understand. You
will need to know "high-level languages" to interpret the meaning of some of them.  We do not intend to teach
any of these "complex sentences" or Pseudo Instructions. We will be showing you how to produce a program
using just the 32 - 35 instructions needed to perform all the functions the microcontrollers are capable of.
Of course you can go one step higher and one step better by including extra complexity in your code but our
intention is to start everyone at "level-zero" to "level-one" where you can produce a program to perform a
reasonably simple task using the mnemonics of the instruction-set. 
Never use any instructions you do not fully understand.
However here is some explanations of instructions you will find in other people's programs:

ARITHMETIC OPERATORS AND  PRECEDENCE:    

 
OPERATOR Example
$ Current address goto $+3 ;goes to 3 locations down the
program

12
goto  $   ;halts the micro
goto  $-4 ;goes to 4 locations up the
program
( Left parenthesis 1 + ( d * 4)
) Right parenthesis (length + 1) * 256
! NOT (logical complement) if !  (a == b)
– Negation (2's complement) – 1 * length
~ Complement flags = ~ flags

* Multiply a=b*c

/ Divide a=b/c

% Modulus entry_len = tot_len % 16

+ Add tot_len  = entry_len * 8 + 1

– Subtract entry_len = (tot – 1) / 8

<< Left Shift flags = flags << 1

>> Right Shift flags = flags >> 1

>= Greater or equal if entry_idx >= num_entries

> Greater than if entry_idx > num_entries

< Less than if entry_idx < num_entries


<= Less or equal if entry_idx <= num_entries
== Equal to if entry_idx == num_entries
!= Not equal to if entry_idx ! = num_entries
& Bitwise AND flags = flags & ERROR_BIT
^ Bitwise EXclusive OR flags = flags ^ ERROR_BIT
| Bitwise Inclusive OR flags = flags | ERROR_BIT
&& Logical AND if (len == 512) && (b == c)
|| Logical OR if (len == 512) | | (b == c)
= Set equal to entry index = 0
+= Add to, set equal entry index += 1
–= Subtract, set equal entry index – = 1
*= Multiply, set equal entry index *= entry_length
/= Divide, set equal entry total  /= entry_length
%= Modulus, set equal entry index %= 8
<<= Left shift, set equal flags <<= 3
>>= Right shift, set equal flags >>= 3
&= AND, set equal flags &= ERROR_FLAG

13
|= Inclusive OR, set equal flags | = ERROR_FLAG
^= EXclusive OR, set equal flags ^= ERROR_FLAG
++ Increment i ++
–– Decrement i  – –

Pseudo Instructions - these are additional Instructions understood by MPASM:

Equivalent
Mnemonic Description Status
Operation(s)
btfsc 3,0
addcf f,d Add Carry to File Z
incf f,d

btfsc 3,1
adddcf f,d Add Digit Carry to File Z
incf f,d

b k Branch goto k -

btfsc 3,0
bc k Branch on Carry -
goto k

btfsc 3,1
bdc k Branch on Digit Carry -
goto k

btfsc 3,0
bnc k Branch on No Carry -
goto k

Branch on No Digit btfsc 3,1


bndc k -
Carry goto k

btfsc 3,2
bnz k Branch on No Zero -
goto k

btfsc 3,2
bz k Branch on Zero -
goto k

clrc   Clear Carry bcf 3,0 -

clrdc   Clear Digit Carry bcf 3,1 -

clrz   Clear Zero bcf 3,2 -

bcf/bsf 0x0A,3
lcall k Long Call bcf/bsf   0x0A,4  
call k

bcf/bsf   0x0A,3
lgoto k Long GOTO bcf/bsf   0x0A,4  
goto k

movfw f Move File to W movf f,0 Z

comf f,1
negf f,d Negate File Z
incf f,d

setc   Set Carry bsf 3,0 -

14
setdc   Set Digit Carry bsf 3,1 -

setz   Set Zero bsf 3,2 -

skpc   Skip on Carry btfss 3,0 -

skpdc   Skip on Digit Carry btfss 3,1 -

skpnc   Skip on No Carry btfsc 3,0 -

skpndc   Skip on No Digit Carry btfsc 3,1 -

skpnz   Skip on Non Zero btfsc 3,2 -

skpz   Skip on Zero btfss 3,2 -

Subtract Carry from btfsc 3,0


subcf f,d Z
File decf f,d

Subtract Digit Carry btfsc 3,1


subdcf f,d Z
from File decf f,d

tstf f Test File movf f,1 Z

PICkit 3 Debug Express


This is the name given to the latest PICkit programmer. When PICkit 3 is used in conjunction with MPLAB
IDE  (Integrated Development Environment) the MPLAB IDE software will show you what is going on and this
will help you in debugging your program.

READING AN INPUT LINE


When any of the bits of file 05 are configured as "input," (this is done via the TRISIO instruction) the HIGH or
LOW on the pin of the chip (this HIGH or LOW will be created by something in the outside world making the
line HIGH or LOW) will be read by the micro as a HIGH or LOW, (when the file is read via an instruction such
as btfss GPIO,1 or btfsc GPIO,1 - test bit1 in file 05h, skip if set or test bit1 file 05h, skip if clear).
This "reading process" can also be done when the contents of file 05 (GPIO) is moved to W.  The instruction
to do this is movf  05h,0 (movf    GPIO,0).  This instruction tells the micro to move the in/out port to the
working register. The working register is called "W" and has the destination "0" - a file has the destination "1."
The contents can also be shifted, incremented, plus other instructions.
Here are some instructions to read the input bit:
In most cases, the first bit (or line) to use in a program is pin 4 as this line is INPUT ONLY. It corresponds to
GPIO,3.
Using the instructions from above, we have GPIO,3 as an INPUT and all other lines are OUTPUT.
We are looking for a HIGH on the input line.
To read the bit, use the following instructions:

    btfsc    GPIO,3    ;This will test the input bit and if it is LOW, the micro goes to movlw xx
    GOTO  PhaseA   ;This instruction takes the micro to a new sub-routine
    movlw  xx

If you don't know the state of some of the bits (or don't want to alter them - by mistake), you can use the XOR
instruction.
For example, to turn ON bits 0, 1 and 2, the instructions can be:
bsf  GPIO,0     b'00000001'
bsf  GPIO,1     b'00000010'   
bsf  GPIO,2     b'00000100'
But this will result in only the third instruction being carried out. We mentioned above, not to use multiple bit-
setting as it will fail to work.

15
The answer is to use the XOR instruction
Combine the 3 instructions to get: b'00000111'
movlw    07h
xorwf    GPIO,1
Only the three lowest outputs will go HIGH.
To turn OFF the three lowest outputs, repeat the same instructions:
movlw    07h
xorwf    GPIO,1
Only the three lowest outputs will go LOW.
Actually, the bits will TOGGLE.

RE-PROGRAMMING:
If you have trouble re-programming a chip, here are some possible solutions:
1. Put a 47k across the power rails to discharge ALL THE CELLS so the programmer can re-program the
chip and prevent "failure to re-program" messages appearing on the screen, or:
2. If a chip is difficult to re-program, remove and replace it. The cells are discharged in this process.
Some chips are just difficult to program and you should buy a number of chips and only use those that are
easy to program, when experimenting.

STACK 
The PIC12F629 has an 8-CALL stack. (8-level stack).
 

SUBTRACT - BE CAREFUL!
Suppose you have a value from a table (it will be in w) and want to subtract (say) 10. The PIC12F629 micro
does not have an instruction for this.
You cannot use: sublw  .10   
because the instruction subtracts w from .10  (decimal ten)
The instruction to use is: addlw   -.10 

TRIS
The TRIS register determines if each line is to be input or output.
It can be accessed by the following two lines of code:
   movlw    b'xx111111'   ;or b'xx000000' or any combination
   tris        gpio              ;
you do not need: bsf  status, rp0 / bcf  status, rp0 to get to bank 1 then back to bank 0.

WEAK PULL-UP FEATURE


When any of the pins of a PIC12F629 or PIC16F628 are configured as inputs, you can turn on the weak pull-
up feature by clearing bit 7 in the option_reg.
Note: GP3 does NOT have this feature. When-ever a pin is configured as an input it will have a weak pull-up
of about 47k. This means you can have a switch connected between an input line and 0v rail and when the
switch is pressed, the input goes LOW.
  

THE XOR TRICK

 P1  Pick A PIC Project


 
  Here is a list of the capabilities of the XOR function:

xorlw 0fh ;EXclusively OR a value with w


xorfw     test   ;EXclusively OR a file with w

16
To toggle a bit or bits:
toggle movlw 10h ;Put 0001 0000 into w to toggle
GP4
xorwf gpio,f ;the only bit that will change is bit4

Match two files (see below)


Exchange two files (see below)
Copy bits from one file to another (see below)
Complement bits in a file (see below)
Create an "In-Line" table (see below)

We have called this article "The XOR Trick" to capture your attention.
The XOR instruction can perform amazing results in a single instruction but it must be fully
understood BEFORE using it.
Most of the 35 instructions for the micros we are studying are easy to understand and it's easy to see
a result, but the XOR function must be checked by "by-hand" to prove what is happening. If you
don't do this, it will be impossible to find a problem, if a problem arises in your program. 
I am not saying a problem will always result from using XOR, but you must check the result "by-
hand" to confirm the result is what you expect. Many of the following examples come from highly
qualified programmers, who like to save a few bytes, but produce extremely "clever" and "complex"
instructions, in the process.
They complain I am "over-stressing" the situation and cannot see the complex nature of this type of
programming, but there has always been the situation of "professors not being able to communicate
with their students."
That's why these highly intellectual individuals are hopeless at teaching. They can't see why you
don't understand advanced programming. And any time the XOR instruction is used, it takes
"concentrated thinking" to see what is occurring.
So, let's look at the capability of the XOR instruction.  It's one of a number of Boolean commands in
the list of instructions and can create a single line of code that can take 10 lines to explain.
The XOR command is spoken as: "Exclusive OR" and is sometimes written EOR or E-OR.
It has the caret symbol "^" when writing assembly code and you will also find some very unusual
symbols for XOR, that cannot be reproduced on the conventional keyboard.
It is exclusively an OR situation, whereas the standard OR function includes the possibility of both
inputs being HIGH for a HIGH output and this is the difference - as you will see below.
The simplest TRUTH TABLE for the XOR function involves two inputs - sometimes called A and
B. These inputs can also be called "arguments."  An input is "true" when it is HIGH and "false"
when it is LOW.
XOR can be described verbally as, "Either A or B, but not both."
The output or RESULT of each possibility is shown in the truth table below. The symbol "^" is the
common symbol (used in C++ programming, etc) for bit-level XOR. In other words, it is used for
manipulation bits in a file and the result is shown in the "output" column:   

XOR Truth Table

Input A Input B A^B

LOW LOW LOW

17
LOW HIGH HIGH

HIGH LOW HIGH

HIGH HIGH LOW

When you look at any truth table, the "item" or "word" or "condition " or "state" you are looking for in the
INPUTS column is: HIGH or T or TRUE. Then look at the state of the OUTPUT. It is only the HIGHs that
concern us. The only two HIGH results are for a single HIGH as an input.

What's the difference between the OR function and the XOR function?
The OR gate produces a result according to: "If A is 1 OR B is 1 (or both are 1), then the output is 1."  Note
that this function produces an output when both inputs are HIGH.  - the XOR removes this result. The OR
function is also called the Inclusive OR as it includes the result when both inputs are HIGH. This
corresponds to the AND function for 2-inputs. Because of the ambiguity of the inputs (we don't know exactly
the state of the inputs), we use the exclusive-OR function for determining the outcome of the INPUTS we are
testing.  The symbol (|) indicates OR.

OR Truth Table  or =(|)

Input A Input B A or B

LOW LOW LOW

LOW HIGH HIGH

HIGH LOW HIGH

HIGH HIGH HIGH

The XOR function also works with multiple inputs and the output is defined to be TRUE if an odd number of
its arguments (inputs) are true, and false otherwise.
In this discussion we will only cover the case of 2 inputs as this corresponds to the capabilities of assembly
programming for the microcontrollers we are covering.

The XOR function is very powerful and will create a result that may take a minute or more for you to work out
"by hand." But you can confirm exactly what is happening, by performing the XOR calculations yourself.

WHAT DOES THE XOR INSTRUCTION DO?


The XOR instruction can be found in the list of instructions as:   xorlw   and xorwf 
These instructions mean:
Example 1:   xorlw     0fh      ;Exclusively OR the number (literal - 0f hex) with w
Example 2:   xorfw     test      ;Exclusively OR the value in file: "test" with w

You can see how complex each of the above instructions can be. For Example1:
Firstly you need to know the value in w. Suppose it is b'0001 0011' 
and the literal is: b'0000 1111.'
Perform a XOR addition:
    0001 0011
    0000 1111

18
    0001 1100    the result is: b'0001 1100' 

For Example2:  You need to know the value in w and the value in "test" file.

MORE THINGS CAN BE DONE WITH THE XOR FUNCTION


One of the simplest things that can be done with the XOR instruction is to change one, two, three . . .  or all of
the outputs (bits) of a port (or any file) from LOW to HIGH or HIGH to LOW or a mixture. 
The instruction changes the sign of each bit and all 8 bits (output lines) of a port will be changed from the
original state to the opposite stage. This means any LEDs (up to 8) on an output, that were illuminated, will
be turned off and any non-illuminated LEDs will be illuminated. The same applies to the bits in a file. Any
number of bits can be changed from "0" to "1" or "1" to "0." We do not have to know the original state of any
of the bits. By creating a "toggling number" any bits with "1" will create a toggle.

TOGGLING
We can write an instruction that selects a particular output bit (LED) and changes the state of only this bit.
This will turn a LED on or turn it off.
If the bit is ON, it will be turned OFF. And if the instruction is processed again, the bit will be turned ON. This
is called TOGGLING. With this instruction we do not have to know the state of the bit. It can be "1" or "0." The
instruction will simply change the state.

Here are the instructions for toggling a bit:  (see more on TOGGLING: Library of terms  P-Z)

toggle movlw 10h ;Put 0001 0000 into w to toggle GP4


xorwf gpio,f ;the only bit that will change is bit4

MATCHING TWO FILES = COMPARISON = COMPARE


We can also use the XOR function to detect a MATCH between two files.
To find out if two numbers are the same, they are XOR-ed together. Since each binary digit (bit)
will be the same, the result will be (0000 0000). For example, if we have two files:
b'0001 0011'    and   b'0001 0011'  bit0 in each file is '1'   bit1 in each file is "1"  bit2 in each file is
"0"  etc etc etc. In fact all bits are the same. When all bits are the same, this will SET the zero flag in
the Status (03) file and by testing bit 2 (the z flag) you can include an instruction in your program to
skip the next instruction when the z bit is set.

Here are the instructions for matching two files:

match movlw 0Ch ; load 0Chex into w


xorwf motor ; see if "motor" file holds 0Chex
btfss status,2 ; test the z flag to see if it is SET
goto notsame ;z flag is not set
goto same ;z flag set = files are both 0Chex

EXCHANGE THE CONTENTS OF A FILE WITH W


This code exchanges the contents of a file with the w register.  It doesn't require the use of another
file to store an intermediate value. file holds: b'0001 1100'   w holds:b'0000 1111'
f_x_w xorwf file,f ;before: file=b'0001 1100' w=b'0000 1111'
;after: file=b'0001 0011' w=b'0000 1111'
xorwf file,w ;after: file=b'0001 0011' w=b'0001 1100'
xorwf file,f ;after: file=b'0000 1111' w=b'0001 1100'

EXCHANGE THE CONTENTS OF TWO FILES


This code exchanges the contents of two files using the w register.  It doesn't require the use of
another file to store an intermediate value.
exch movf file2,w ;file1=b'0001 0011' file2=b'0000 1111'
;w=b'0000 1111' (after execution)

19
xorwf file1,f ;file1=b'0001 1100' w=b'0000 1111'
xorwf file1,w ;file1=b'0001 1100' w=b'0001 0011'
xorwf file1,f ;file1=b'0000 1111' w=b'0001 0011'
movwf file2 ;file2=b'0001 0011'

RANDOM NUMBER GENERATOR


rand     movlw    01Dh         ;any value can be used
           clrc                        ;clear carry
           rlf          random,f    ; rotate random file left
           btfsc     status,c     ;test the carry bit (bit0) in Status file
           xorwf    random,w   ;xor w with random and put result in w
           retlw     00

COPY BITS FROM ONE FILE TO ANOTHER


copy   movf    from_file,w
          xorwf   to_file,w
          andlw  b'xxxxxxxx'  ;replace "x" with "1" to copy the bit or "0" to leave bit as is.
          xorwf   to_file,f

BITWISE OPERATIONS
Operating on the bits of a file (or two files) is called a BITWISE OPERATION. 

COMPLEMENTING BITS
An "XOR mask" complements (reverses) selected bits of a file. This is called a BITWISE ARITHMETIC
OPERATION.   The MASK is loaded into w and XOR'ed with fileA.

reverse  movlw    b'00000011'    ;this is the MASK to reverse the two lowest bits
                                              ;fileA contains b'11111101'  (before)
            xorwf      fileA,f            ; fileA contains  b'11111110'  (after)

HOW THE XOR OPERATOR WORKS:


Here is a summary of how the XOR operator works:
^ is the XOR operator (0^0 = 0, 0^1 = 1, 1^0 = 1, 1^1=0).
Any value XOR'd with itself results in 0 (X^X=0)
XORing with zero has no effect (0^X=X)

INLINE TABLE
An "Inline Table" is a table that does not use a "call and return" feature.
Here is a 5 element table:

addwf pcl,f
xorlw 3^00^(2^01) ;the table-value is 3
xorlw 2^01^(7^02) ;the table-value is 2
xorlw 7^02^(5^03) ;the table-value is 7
xorlw 5^03^(1^04) ;the table-value is 5
xorlw 1^04 ;the table-value is 1
movwf tempA
(the program will use the value in tempA to display a value on
a 7-segement display or something similar then go to an
address above addwf pcl,f to change the value for w to jump to another table-value)
Before entering the above instructions, the program will need to load w with a value from 0 to 4 so that when
the instruction addwf  pcl,f is executed, the micro will jump down the appropriate number of table-values and

20
enter at the correct location. 
If the value for the table is "0," the first table-value will be executed 3^00^(2^01) and then the next line:
2^01^(7^02) and the following three lines will also be executed to produce a value of 3 to be placed in tempA.

This is a very complex way of achieving a table-value but it shows how the XOR operator works. And it is the
only way to produce an "in-line" table.
Each table-value consists of three items. The first item is the actual table-value. The second item is the value
that w will contain when it enters the table and third item is a copy of the  first and second values in the next
table-row.
To work out what is happening, you must remember the two rules for XOR'ing:
Any value XOR'd with itself results in 0 (X^X=0)
XORing with zero has no effect (0^X=X)
If we take the fourth table-value, w will enter with the value 03 and perform an XOR on 5^03^(1^04) then
advance to the next line and perform an XOR on 1^04. W will contain 5.
If we place all the values in a single line they become: 03^5^03^(1^04)^1^04.
The 03^03=0 and (1^04)^1^04=0 leaving 5^0^0=5.
If the micro enters the first line, the five lines of XOR'ing would be:
0^3^00^(2^01)^2^01^(7^02)^7^02^(5^03)^5^03^(1^04)^1^04=3.

Now you can see why it might take a few minutes to work out what is happening in a 10 line "in-line" table!

  5/7/2010

21

You might also like