| Chapter 1
 
		
    
	
         Chapter 2
 In this chapter we talk about the magic of a microcontroller. 
		A single microcontroller can 
		replace many simple IC's and make a project so powerful it appears 
		to have "intelligence."
 There are lots of microcontrollers on the market and lots of new 
		companies and manufacturers coming out with their own devices. It's so 
		complex that you almost don't know which path to travel.
 The competition is so fierce that new products and designs are cheaper 
		and more powerful than the predecessors and this gets your head 
		spinning.
 Obviously you can't spread your talents too thinly and you can't learn 
		to program all the different devices. So, the simple answer is to start 
		with something that has been on the market for a while and has an 
		enormous backing - in the form of programs, projects and discussion 
		groups -  that's 
		why we have chosen the PIC family.
 
 But just before we discuss the PIC chip, here is little diversion.
 Texas Instruments have introduced their own line of micros and a recent 
		email promoted their MSP430xxx series.  These are a 16-bit 
		ultra-low-power devices and the suggested price started at 25 cents.
 Thinking this was a very good entry price, I looked further to find the 
		actual part number and costing. Apart from not finding the part number, 
		the remainder of the website suggested the prices started from 49 cents, 
		not the 25 cents on the frontice page.
 On further investigation I found very little in the way of documentation 
		or projects for any of the chips in this range and finally found a 
		supplier that sold the chip for 69 cents in quantities of 2,000 pieces!  
		Or single units for $2.30. This is a far-cry from the 25cent "bait."  
		I am still waiting for a reply to my email to "TIasia." asking for 
		clarification of the 25 cent device.
 As I have said before, don't spread your resources too thinly.
 Every time you entertain a new style of microcontroller you have to 
		learn a new set of instructions or advance to a higher-level language 
		where a compiler will create the code.
 We have done all the background leg-work and come up with a PIC as the 
		best choice.
 
 That's why the microcontroller we will be discussing is the PIC12F629. 
		It is one of the simplest on the market, as we are starting at the 
		beginning of microcontroller design. This means everyone will be able to 
		pick up this amazing field of electronics.
 There are thousands of pages on Talking Electronics website to help you 
		in all facets of electronics, including the designing of circuits 
		(called interfacing) to a microcontroller.
 Some projects, in various magazines, don't tell you anything about the program in the micro and 
		projects give the chip a name such as "Hand Wand" and don't tell you 
		the type of chip in the circuit. We don't do that. We don't keep you in 
		the dark. We explain everything.
 Everything we design has the full circuit diagram and all the code for 
		the program.
 Our intention is to make you successful as an electronics engineer. The 
		author has been designing projects for over 30 years and sees customers 
		every day who say they have gained an enormous amount from reading 
		Talking Electronics projects and articles.
 It's a lot of work but it is worth it.
 To get into the microcontroller field is a lifetime career. You don't 
		know were it will lead, however I can guarantee you a position in the 
		medical area.
 You only have to concentrate on monitoring and the field is enormous.
 It may be monitoring patients with terminal diseases, life-threatening 
		diseases, constant-monitoring-diseases or one of a thousand situations 
		that need attention.
 Or you can take up hearing-loss, speech-loss, co-ordination-loss. And 
		then there are other areas such as security, shop-signs, automotive, 
		education, toys and lots more . . .
 
 But before you can think about designing anything, you need to be able 
		to program a chip to carry out a task.
 This is what this course is all about, It will give you the confidence 
		to tackle tasks you thought impossible. And produce designs beyond your 
		imagination.
 But before we can work in any of the fields we have mentioned, let's work on some simple projects to gain 
		programming skills.
 Let's walk before we run.
 
 EVERYTHING
IS DESIGNED AROUND A "COMPUTER"
 Almost every new product is designed around a "computer" and to us, this means a "micro."
 Devices such as talking key-chains, whistle detectors to locate your keys, 
remote controls for garage doors, cars, DVDs, cable TV, 
house alarms and toys are all designed around a single "computer" chip.
 The reason is simple. Economics.
 A "computer" chip is a device with many functions. It can 
"remember" codes and inputs from the user and output to one or more 
devices.
 Rather than design a circuit using lots of transistors, chips and components, it 
is much cheaper to use a single chip. It takes less board-space, costs less to 
produce and creates a smaller product.
 Here is a circuit for a 
		DOOR CONTROLLER:
 
		
		 DOOR CONTROLLER
 It is nothing more than a "door striker" 
		(a solenoid to release a door) that operates when a code is entered on 
		the 4x4 keypad. All the processing of the data from the keypad and code 
		remembering is done with a number of chips including a RAM. This can now 
		all be done in a micro and no other chips are required. This is how a 
		micro has changed electronics.  
		Micro's not only simplify designs, they reduce the size of the PC board 
		enormously. New designs are always going for compactness and the trend is to produce something 
smaller than the previous model. And it all revolves around a micro.
 There are two choices. It can be custom-designed or "off the shelf."
 Designing a chip will cost thousands of dollars. But in most cases you can buy one 
		"off the shelf" for only a few dollars and all you need to do is add the 
		"program."
 
 These "universal" chips are called microcontrollers and are equivalent to buying 
an exercise book and writing your own article.
 One of the smallest and cheapest microcontrollers on the market is the
PIC12F629  
(data sheet 4.9MB .pdf)
 It is an 8 pin chip with 5 pins that can be 
connected to external devices such as globes, switches, relays, microphones, 
photo devices, motors, etc 
and 1 pin that is an INPUT only.
 Sometimes you will need a transistor or other component between the chip and the 
device to get them to "talk" to the chip, or get the chip 
to drive the device. This 
is called INTERFACING and will be covered in our discussion.
 Even though the PIC12F629 is very small as far microcontrollers are 
		concerned, it can take the place of 10 or more individual chips, as can 
		be seen above.
 All sorts of projects can be designed around the chip or you can get it to 
perform "intelligent" commands such as playing a game or remember a sequence of 
events.
 It may be small, but it's the place to start.
 Every year, electronics is reducing is size, increasing in performance and 
halving in cost.
 New products are being released all the time using microcontrollers.
 Devices such as auto-dialers for monitoring heart patients or diabetes suffers, 
automatically dial a central station and download data to monitor the patient. 
The computer decides if an alarm is to be raised.
 The  world is crying-out for devices to assist those unable to perform 
certain tasks.
 But to be able to turn an idea into reality, you have to know the capability 
of electronics and be able to carry out the design-work. You will lose-out 
heavily if you pass your idea to another authority.
 This is what this article is all about.
 It shows some of the capabilities of a microcontroller and how to 
get from the concept-stage to the finished product.
 It's all a matter of doing things in small steps and 
when these are combined together, you have something that will perform a task.
 
 
WHY PICK THE PIC12F629?The first thing you will ask yourself is: Why pick the '12F629 for a project?
 The answer is simple. It is an 8-pin chip with 6 pins that can be used as inputs 
or outputs and these can be changed at any time during the running of the 
program. Pin 4 (GP3) can only be used as an input pin. The only smaller PIC 
micro is the PIC10F222. It is 20 to30 cents cheaper but does not have all the 
features of a PIC12F629. See the article on
PIC10F222.
 Each pin of the PIC12F629 will drive up to 25mA and this can be buffered with a transistor 
to deliver higher currents.
 The chip takes only a few micro amps when put into sleep mode and can 
take the place of many other types of chips.
 But best of all, the program you write and burn into the chip, can be protected 
from prying eyes, so the project can be sold for material gain.
 There are thousands of potential uses for this chip.
 You only have to think of the medical field, security field, educational field 
and use it as an interface device between buttons and a motor, lamp or speech 
chip.
 The best place to start is in your own household.
 If you have an elderly person or know of someone that requires attention; study 
the situation and develop something that solves the problem.
 The same requirement will be needed for everyone else in the same predicament and if 
the device you produce is cheap and reliable, you will have a ready-made market.
 The main reason why we suggest a microcontroller is "ease 
of modification."
 By writing a program and having all the operations (such as timing, delays, sequencing 
etc) will be done via a program and the end-result can be modified to an individual's 
requirement, so the chip can be up-graded without having to change any of the circuit 
components.
 Not only that, many of the logic chips in "old-style" designs are becoming obsolete and difficult to 
obtain.
 But best of all, you will have the quodos of knowing the project you have 
designed uses the latest technology.
 Don't worry about the code space of about 1,000 instructions. You will almost 
NEVER fill the memory. The reason is simple. As you produce a larger and larger 
program, you will refer to some of the previously written sub-routines and thus 
you will be able to get a lot of new activity with a few instructions.
 You can think of it this way. If you were to write a program on paper, using 25 
lines per page, the 1,000 line program would require 40 pages. Some of the lines 
of the program would consist of tables and if you allow 250 items of data, the 
remaining space is 750 lines for your code.
 
 
 THE PICAXE AND THE STAMP
 You may have come across very popular microcontroller teaching systems called 
"PICAXE" or "STAMP." These are both concepts that have been designed to teach 
programming of 
microcontroller chips using a higher level of language called BASIC (the 
lowest level is called Machine Code).
 The whole concept of these products is to get a project up and running, using a 
microcontroller, in which all the sub-routines have been pre-programmed into the 
chip and all you have to do is create a list of instructions to call the 
necessary sub-routines to create a result. The simplest module in the PICAXE 
range uses a PIC12F629 and the stamp uses a similar microcontroller.
 This is a wonderful way to get a project "up-and-running" without having to learn how 
to program the chip, but instead of having to learn 33 instructions for the 
chip, you have to learn a language called "BASIC." This is totally different to anything we are doing. 
We are using the 33 instructions that come with the chip and we are capable of 
carrying out 
everything the chip is capable of doing.
 Learning to program the other two "devices" is like getting someone to take your place at 
University for 5 years and then give YOU the Engineering degree at the end of 
the course.
 BASIC language has nothing to do with PIC chips. The chip inside the product could be an ATMEL 
chip and the outcome would be exactly the same.
 If you want to produce a project and just see the end result, you can 
use one of these concepts.
 If you want to produce something that may be converted to an income-producing 
idea, these concepts will cost a lot more as you have to buy the 
pre-programmed chip from special suppliers. Secondly, the chip is already so filled 
with routines (called the BOOTSTRAP program) that it will only accept a few 
instructions (about 30 - 80 BASIC instructions) that are placed in the EEPROM 
section of the chip.  One of the pins of the chip is used for programming, so the chip has one less in/out 
line.
 If you are beginning programming, you can try them and see how exciting it is 
to get something working. If you then want to produce a more-complex project, 
and you run out of space in the chip, you can put the PICAXE chip in a 
conventional programmer and erase the bootstrap program and use the chip in one of our projects. Nothing will be wasted!
 Note: The BOOTSTRAP program can also be called the ROM Monitor program or 
Monitor ROM as it is the operating system for the PICAXE system. Imagine if 
every book you bought had a list of words in the front and how to create 
sentences. What a waste of paper! That's how I feel about the MONitor system. It 
reduces the capability of the chip enormously.
 
 Our concept is to teach PROGRAMMING. When you do everything yourself, you can 
change anything to suit the circumstances. When anything is done at 
"arms-length" or by someone else, you have less control. Both our concept 
and PICAXE or STAMP have 
enormous potential and it's up to you to work out which path you want to take.
 I prefer to be in charge of everything I do. That's why I show how to do 
everything at the lowest level possible.
 That's why our level is called hand-assembled "ASSEMBLY CODE."
 The individual lines of code (instructions) create a program with an extension 
".asm"  and this program is actually made up of sub-routines. Each sub-routine is designed to 
carry out a simple task such as recognizing the push of a button, turning on a LED 
or creating a tone 
in a speaker.
 The place to start writing this code is on a template already laid-out with preliminary details. 
For the chip we are featuring, the template is called 
		blank12F629.asm 
(assembly template).
 
 We have two templates:
 
 BLINK12f629.ASM
 "blink12F629.asm" 
will blink a LED to show that the program, chip and circuit, is working. This is a test program to prove 
the writing, burning and circuit components are correct and functioning.
 
 BLANK12f629.ASM
 "blank12F629.asm" is a starting template.
 To create a program for the chip, use  blank12F629.asm, 
open 
Notepad.exe or Unzip 
Notepad.zip in our Programming 
folder on the left-side of the screen and load it with the blank12F629.asm 
file by sliding it into Notepad. It will then 
show in Notepad. Rename the file immediately to something such as "project1" and 
save it. Work on  "project1" file.
 Don't get blink12F629.asm confused with blank12F629.asm
 
LIBRARY OF 
		SUB-ROUTINESTo 
make programming easy, we have created a number of sub-routines and placed them 
in a Library.
 The library has also been formatted as a text file so you can copy and paste the 
instructions directly into your program. Click 
HERE for the library 
as a text file.
 
 DESIGNING A PROJECT
 We have designed a lot of 
projects using this PIC chip and the best place to start is with one of the 
projects.
 Some of them are surface-mount and some are programmed when the chip is 
already fitted to the board. No matter which project you choose, you will learn 
A LOT.
 If doesn't matter if it is improving your soldering skills or simply identifying 
components, every project will add to your knowledge.
 Eventually you will want to design your own project and this is when your skills 
will be tested.
 The author has just spent 5 hours finishing a simple LED-light strip of over 300 
LEDs for a set of doors in a bottle-shop.
 The final design required 5 modifications and it's important to work of the 
correct modification before going to the next.
 Everything has to be done in the correct order and everything needs a lot of 
thought.
 The modifications were simple but in the finish it took 5 hours.
 To be able to work on a project and make changes, you have to know what you are 
doing. That's why we have produced so many project and presented them on the 
website. Even though many of the projects do not use a microcontroller, they 
offer other design features that will help you. That's why it's important to put 
together as many projects as possible. They will all offer some feature that 
will add to your knowledge.
 If you think a new design will work first-time, you are fooling yourself. They 
all require modifications and improvements.
 So, here's the path: Pick a project and put it together.
 Pick another and put it together
 Try another project and build it.
 Even if you set a goal of one project a week, it will take many months to build 
up a store of "building blocks."
 It takes time, money, patience and commitment to build up a store of knowledge. 
But it will be worth it in the end.
 Every society is promoting the need to have an understanding of technology and 
the only way to get an electronics education is via self-study.
 The range of material we have on the site will get you through to employment in 
almost any field and it's all FREE!   All you have to do is take 
advantage of it and back up what you read with the practical side.
 
 The following article discusses the PIC12F629 and its technical 
		features. You should also refer to the 120 
		page manual for more details on the workings of the chip.
 
		
 
		THE PIC12F629by CHARLES MANNING
 
		The Microchip PIC12F629 microcontroller is one of the smallest 
		chips in the range and is a good starting point for 'dedicated micro' applications. 
		It is low 
		cost and easy to program. 
 Electronic circuits are often used to monitor and control equipment. 
		This may be as simple as a sequencer for a model railway or sprinkler 
		system, or as complex as a real-time industrial controller. Where once 
		relays and logic gates were used, microcontrollers are now finding their 
		way into sophisticated and 'intelligent' control.
 Unfortunately for the private individual this approach is often not 
		feasible since micro-controller development systems can be very 
		expensive. However this article will show you how to use this device and 
		explain most of the features of the chip.
 
 A microcontroller is a 'computer in a chip', which has been designed 
		specially for control purposes. As 
		well as the central processing unit, most microcontrollers include 
		random access data memory (RAM), and read only memory (ROM), timers and 
		input/output lines; all in a single chip. Some also include more 
		complex features such as analog to digital converters, serial 
		communications channels and pulse width modulators. As is the case with 
		all electronic technologies, microcontrollers are becoming smaller and 
		many are now available in 'skinny DIP' or surface mount packages with 
		less than 20 pins.
 A few years back, the use of miniature microcontrollers was only 
		feasible for large manufacturing companies producing tens of thousands 
		of each product. The design process was slow. Firstly, the design 
		engineers would use expensive design and modeling systems to lay out the 
		design of the device. The designs were sent off to the chip 
		manufacturer, who would take a few weeks (and a few thousand dollars) to 
		make a couple of sample parts for testing.
 Hopefully the first design was right, but more likely some bug would be 
		found and this process would have to be repeated. Once the design was 
		tested, the manufacturer would then schedule a
		production run of these parts.
 
 This slow and costly process kept miniature microcontrollers out of 
		reach for a growing sector of the market, such as small engineering firms who 
		could not afford the large costs and long turnaround times. These firms 
		frequently have small budgets and their products are often cost 
		sensitive, have short production runs and need to be delivered quickly.
 A few chip manufacturers realised this, and began producing miniature 
		microcontrollers with development systems that the smaller companies 
		could afford (a few hundred to a few thousand dollars).
 This article is based on the PIC12F629 
		microcontroller, from Microchip Technologies, which has some features 
		which make it ideal for the amateur developer. Microchip's PIC series of 
		microcontrollers has created a lot of interest in the electronics 
		development community. Not a day goes by without exchanges about PICs on 
		international news networks like the Internet.
 Unlike many micro-controllers, which have evolved from general purpose 
		microprocessors, the PIC series were purposefully designed from scratch 
		as small, cheap, feature-packed microcontrollers to suite both small and 
		large scale developers. PICs have a rather novel reduced instruction set 
		(RISC), which makes PIC code very compact and easy to learn. The 
		simplicity of a RISC core allows the PICs to combine low power usage and 
		high performance in small packages.
 The main difference between the 12F629 and most other microcontrollers is 
		that the program is stored in onboard EEPROM, instead of EPROM. EEPROM 
		memory is erased electrically in a few milliseconds; EPROM typically 
		requires a few minutes exposure to ultra-violet light. Microchip 
		probably did this to allow new programs to be downloaded in the field.
 EPROM-based reprogrammable devices are packaged in ceramic, with a 
		quartz window to admit ultra violet light; however the 12F629 comes in 
		the standard plastic packaging, which makes it cheap when compared with 
		other reprogrammable micro-controllers. As a bonus, EEPROM program 
		storage also does away with the need for an EPROM eraser.
 The PIC12F629 is a CMOS device. This means it has a low power 
		consumption, typically 2mA or less at a clock speed of 4MHz and just a 
		few microamps in sleep mode. The 12F629 needs a 4.0 - 6.0V power supply 
		for XT, RC and LP oscillator configurations and a 4.5 - 5.5V supply for 
		the HS configuration.
 
 PIC architecture
 The heart of any computing device is its processing core. The PIC has a 
		Harvard architecture, which uses separate memory access paths for 
		program and data. This improves performance, as program memory access 
		can be performed simultaneously with data memory access. Separate memory 
		access also allows the instruction word width to be different from the 
		data memory word width, a trick which the PIC designers have use to 
		great effect in implementing the RISC core.
 Unlike most microcontrollers, the PIC has an eight-bit wide data word 
		and a 14-bit wide instruction word (earlier members of the family have 
		12-bit wide instruction words), allowing all PIC instructions to fit 
		into a single instruction word. This means that the program code is very 
		compact, the instructions execute faster and the design of the core is 
		simplified dramatically. As an example, Microchip quotes 2.24 times the 
		code density and 1.54 times the execution speed of a Motorola 68HC05 for 
		the same oscillator frequency (4MHz).
 
 The 14-bit PIC core needs only 35 instructions and no 'strange' 
		addressing schemes, which simplifies programming. A PIC instruction 
		cycle takes four oscillator cycles. PIC instructions are decoded and 
		executed in one instruction cycle and in all case we talk about one 
		cycles for each instruction-execution. Fetching an instruction also takes 
		one instruction cycle.
 The PIC has a pre-fetch pipeline, which allows an instruction to be 
		executed while the next instruction is being fetched. This allows most 
		instructions to execute in one instruction cycle; the exception being 
		where executing the instruction causes a change in the program counter.
 The next instruction in the pipeline cannot be used and an extra machine 
		cycle is required to reload the pipeline. Examples of these include the 
		GOTO and RETURN instructions.
 The 
		12F629 has 1024 instruction addresses for your program and this is the 
		space allowed for instructions and any table data.  It also has 64 
		locations for SRAM and 22 for special function 
		registers.
 It also has 128 bytes of EEPROM data, which lie outside the data space and are accessible via special purpose registers. 
		The EEPROM data can be read and modified at run-time and, unlike RAM 
		data, is retained when power is removed from the device.
 The PIC devices based on the new 14-bit core support and in-circuit 
		serial programming mode. This is particularly relevant for the 12F629 because the program is kept in EEPROM. 
		A new program and EEPROM data can 
		be downloaded without having to disassemble the circuit or the 
		enclosure.
 For example, I have designed a 12F629 based circuit which can operate 
		underwater. The 12F629 can be reprogrammed without having to open and 
		reseal the enclosure, and can even be reprogrammed underwater. The 
		serial programming mode means the programming circuit can be kept 
		very simple.
 The PIC core has an eight-deep hardware stack, which is used to store 
		return addresses for subroutine calls and the interrupt service routine.
 
 Oscillator modes
 The PIC12F629 can support eight different clock oscillator modes, which 
		are selected by programming the corresponding configuration fuses. The 
		LP, XT and HS modes cater for various frequency ranges of crystal or 
		ceramic resonator operation, as well as external clock input. Such an 
		oscillator is a must where accurate timing is required.
 
 The RC mode requires only an external resistor and capacitor. The 
		frequency of oscillation is determined by the resistor and capacitor 
		values and, to a lesser extent, by the supply voltage and temperature. 
		This mode cuts down costs at the expense of reduced accuracy. Microchip 
		suggests that the resistor be kept in the range of 3k to 100k, to ensure oscillator stability and a reasonable degree of accuracy. 
		Similarly, a capacitor value of at least 20pF is suggested.
 
 Power-on reset
 The PIC allows various power-on reset (POR) configurations. There are 
		three parts to the POR delay circuitry.
 The power-up timer (PWRT) is a fixed internal RC timer of approximately 
		72 milliseconds. This timer is enabled by setting the PWRTE 
		configuration fuse.
 After the PWRT has elapsed, the oscillator startup timer (OST) counts 
		1024 clock cycles for LP, XT and HS mode oscillators. This allows the 
		oscillator time to settle down to guarantee oscillator stability.
 The MCLR pin allows for an external reset to be applied. It is usually 
		sufficient to hard wire this pin to Vdd and rely on the combination of 
		the PWRT and OST to provide a clean start up. A longer delay can be 
		applied by attaching external circuitry to the 
		MCLR pin.
 A word of caution, though. The MCLR pin may be attached directly to Vdd, 
		but it must always be connected to ground via a resistor of at least 100 
		ohms. This resistor prevents a high current latch-up problem from 
		occurring. Thankfully this problem is not shared by other pins on the 
		device.
 
 Power-down mode
 The PIC devices support a power-down mode which shuts down the 
		oscillator, 'putting the device to sleep'. The PIC enters the power down 
		mode when the SLEEP instruction is executed. The primary purpose of this 
		mode is to conserve power, though it may also be used as a delay.
 The normal power consumption, typically about 2mA, is very low, but this 
		drops to less than 10uA in SLEEP mode, which means that a small battery 
		can keep a PIC in SLEEP mode for a couple of years. This makes the PIC 
		suitable for number of circuits where very low power consumption is a major 
		consideration.
 Of course there isn't much point in having a PIC just sleeping. The 
		wake-up sequence runs the OST sequence for the oscillator to stabilise 
		(1024 oscillator cycles for LP, XT and HS mode oscillators, but 
		immediate for RC mode oscillators) and then resumes execution at the 
		instruction after the SLEEP instruction.
 The PIC can be programmed to wake up on external interrupts and watch 
		dog timer expiry. Unfortunately, since the internal oscillator is turned 
		off, the timer/counter does not function and can't cause an interrupt. 
		This restricts time based wake-ups to the watchdog timer expiry which, 
		as mentioned below, is not entirely accurate. It does however still 
		allow the PIC to be asleep most of the time, waking periodically to 
		check for some condition, then going to sleep again.
 
 Watchdog timer
 Even the best designed circuits can sometimes freeze up or go a bit 
		berserk due to power spikes, the phase of the moon or other glitches.
 When this happens with desktop 
		computers, it seems to be accepted as an annoying part of our high-tech 
		way of life. However if a microcontroller deeply embedded in an 
		appliance goes crazy, you end up with a washing machine stuck on 'spin' 
		or flooding the laundry. A watchdog timer provides a mechanism to help 
		increase the reliability of an embedded microcontroller.
 The watchdog timer consists of a timer circuit which is built into the 
		PIC's reset circuitry. This timer must be periodically cleared by 
		executing a CLRWDT instruction. If the timer is allowed to expire, the 
		watchdog 'bites' and resets the PIC.
 The timer period is approximately 18 milliseconds. The period is set by 
		an internal resistor and capacitor, so it is prone to minor change with 
		temperature, voltage and manufacturing variations. The period can be 
		lengthened up to approximately 2.3 seconds by using the prescaler available in the OPTION register.
 The watchdog timer is enabled by programming the WDTE fuse in the 
		configuration fuses. As mentioned above, the timer may also be used to 
		wake the PIC from power-down mode.
 
 Interrupts
 The idea of an interrupt can be easily explained by an analogy. Consider 
		that you are sitting at your desk performing some task. You have a 
		phone, but it has a tiny indicator lamp instead of a ringer. This means 
		that you need to periodically stop what you are doing and check whether 
		the lamp is lit. If you don't do this often enough, you may miss a call; 
		do it too often and you will never get any of your work done. This is 
		analogous to polling.
 Trying to write a program like this is very difficult, since the code 
		must be peppered with regular checks for external events. This situation 
		gets even more difficult if timing is critical.
 Now replace the telephone's indicator lamp with the more familiar 
		ringer. You can now get on with your work. When the phone rings, you can 
		stop what you are doing, take the call, then get back to your original 
		task. This is analogous to interrupt handling.
 When the microcontroller hardware detects an interrupt condition, it 
		saves the foreground task's current execution context on a stack, then 
		starts executing the interrupt handler code — starting at a special 
		location called the interrupt vector. This is location 04 in program 
		memory. When the interrupt handler 
		completes its task, it executes a 'return from interrupt' instruction 
		which restores the suspended execution context and the foreground task 
		continues as if nothing had happened. Since the hardware checks for the 
		interrupt events, all the software writer needs to do is specify a 
		single interrupt servicing routine and enable the appropriate 
		interrupts.
 Interrupts allow the foreground processing code to be considered 
		separately from the background 'event handling' code. Interrupts really 
		help to reduce the coupling between the fore ground task and the 
		background tasks, 
		making the code more robust and easier to understand. A bonus is that 
		this code becomes more modular, which means that it is easier to build 
		reusable software components.
 
 Instruction set
 Here is the Instruction-set for the 
PIC12F629. The letter "f" indicates a file (also called a register) from 20h to 5Fh. 
The letter "d" is the destination for the result of the operation and when d=0, 
the result will be placed in the W (working) register. If d=1 the result will be 
placed in the file itself.
 The letter "C" = Carry flag in the Status register. "DC" = Digit Carry in the 
Status register. "Z" = Zero flag in the Status register.
 These instructions are described in more detail in the
.pdf file for PIC12F629 and 
		on our Instruction Set page.
 
 The PIC Instruction Set is very simple and can be 
		mastered in a short time.  The table below shows the  PIC12F629  
		Instruction Set in contracted form. For more details on each 
		instruction, see
		 Instruction Set.
 
			
				| 
				
				
				Mnemonic | 
				
				
				Description | 
				Flags |  
				| 
				
				ADDLW     00 to FF | 
				
				Add literal to W | 
				
				C, DC, Z |  
				| 
				
				ADDWF     f,d | 
				
				Add W to f | 
				
				C, DC,Z |  
				| 
				ANDLW    00 to 
				FF | 
				
				AND literal with W | 
				Z |  
				| 
				ANDWF    
				f,d | 
				
				AND W with f | 
				Z |  
				| 
				BCF            f,b | 
				
				Clear bit | 
				  |  
				| 
				
				BSF            f,b | 
				
				Set bit | 
				  |  
				| 
				
				BTFSC       f,b | 
				
				Test bit, skip if clear | 
				  |  
				| 
				BTFSS       f,b | 
				
				Test bit, skip if set | 
				  |  
				| 
				
				CALL         addr | 
				
				Call address | 
				  |  
				| 
				
				CLRF           f | 
				Clear f | 
				Z |  
				| 
				
				CLRW | 
				
				Clear W | 
				Z |  
				| 
				
				CLRWDT | 
				
				Clear watchdog timer | 
				
				TO.PD |  
				| 
				
				COMF    f,d | 
				
				Complement f | 
				Z |  
				| 
				
				DECF           f,d | 
				
				Decrement f | 
				Z |  
				| 
				
				DECFSZ      f,d | 
				
				Decrement f, skip if zero | 
				  |  
				| 
				GOTO         addr | 
				
				Goto address | 
				  |  
				| 
				INCF           f,d | 
				
				Increment f | 
				Z |  
				| 
				INCFSZ      f,d | 
				
				Increment f, skip if zero | 
				  |  
				| 
				IORLW       k | 
				
				OR literal with W | 
				Z |  
				| 
				IORWF       f,d | 
				OR W with f | 
				Z |  
				| 
				MOVF         f,d | 
				
				Move f to destination | 
				Z |  
				| 
				MOVLW     
				00 to FF | 
				
				Move literal to W | 
				  |  
				| 
				
				MOVWF   f | 
				Move W to f | 
				  |  
				| 
				NOP | 
				
				No operation | 
				  |  
				| 
				
				OPTION | 
				
				Load OPTION register | 
				  |  
				| 
				
				RETFIE | 
				
				Return from interrupt | 
				  |  
				| 
				RETLW       
				00 to FF | 
				
				Return with literal in W | 
				  |  
				| 
				
				RETURN | 
				
				Return | 
				  |  
				| 
				RLF              
				f,d | 
				
				Rotate f   left | 
				C |  
				| 
				RRF              
				f,d | 
				
				Rotate f  right | 
				C |  
				| 
				
				SLEEP | 
				
				Enter sleep mode | 
				
				TO,PD |  
				| 
				SUBLW       
				00 to FF | 
				
				Subtract W from k | 
				
				C, DC, Z |  
				| 
				
				SUBWF       f,d | 
				
				Subtact W from f | 
				
				C, DC, Z |  
				| 
				
				SWAPF       f,d | 
				
				Swap nibbles | 
				  |  
				| 
				
				TRISIO      | 
				
				Load tristate register | 
				  |  
				| 
				XORLW       
				00 to FF | 
				
				XOR literal with W | 
				Z |  
				| 
				
				XORWF       f,d | 
				
				XOR W with f | 
				Z |  
		The PIC has one working register, the W register. It has many purposes 
		and one of its simplest uses is a "carrier" file or register.
 If you want to load one of the files (20h to 5F) with a value, the value 
		is initially loaded into W. The value is called a literal and can 
		be from 01 to 0FFh. These values are hex (hexadecimal) values. For the 
		table of hex values from 00 to FF see:
 Library 
		(Decimal to Binary to HEX).
 The value is then moved from W to the required file 
		(this is a total of two instructions). W is also often used as a dummy 
		register where the results of an operation are to be discarded.
 The 
		PIC's files are called data memory or 'data registers'  or 'data 
		files.'
 It is useful to identify the various operand types to understand how 
		the instructions work. The first type are the byte-oriented operations 
		on file registers. This is where all the 8 bits in a file are operated 
		on. A typical instruction is:
 
 DECF   20h,1
 
 These typically have two operands, referred to as f and d, where f is 
		the file number (20h in this case) and d is the destination of the 
		result (1 in this case).
 The f operand is a seven-bit address which selects which file 
		register is being manipulated. The d operand is a single bit which 
		selects the destination of the result; 0 selects the W register and 1 
		selects the file register specified in f.
 Note that the two clear instructions, CLRF and CLRW, really fall into 
		this category although they do not have two operands. CLRF, the clear 
		file instruction, requires only the f operand and the destination is 
		implicitly the file register; CLRW, the clear W instruction, is 
		effectively a CLRF instruction with the destination set to W.
 The second type is the bit-oriented file register operations. These 
		operations have two operands, f and b, a seven-bit file register 
		address and three-bit bit address respectively. These allow any bit in 
		the file registers to be set, cleared or tested.
 The third type of operand requires a single literal byte operand. The 
		mnemonics for all of these operations end in LW, indicating a literal 
		value operation on the W register.
 The last operand type is the 11-bit program address used by the GOTO and 
		CALL operations.
 
 Conditional execution
 Unconditional branching is supported by the GOTO and CALL instructions. 
		Conditional execution is supported by four instructions, DECFSZ, INCFSZ, 
		BTFSC and BTFSS. All these instructions skip 
		the execution of the next instruction if a certain test condition is 
		met. For example:
 
 DECFSZ     test,f
 GOTO        loop2
 GOTO        Siren
 
 Here the DECFSZ instruction is the decrement test, decrementing 
		the "test" register and putting the result in the file itself. 
		The letter ,f indicates the result is placed in the file. The 
		GOTO  loop2
		instruction is skipped if the result of this decrementing was not zero. 
		In other words, the micro will normally go to the instruction below the DECFSZ 
		unless the result of the file is zero. This allows loops to be created 
		(such as for delays):
 
 loop2     DECFSZ     test,f
 GOTO        loop2
 GOTO        Siren
 
 and when the result is zero, the micro advances down the program to 
		the instruction:
		GOTO        Siren
 Do not use
		DECFSZ     test,w 
		if you want to decrement a file to zero (such as in a loop) as the 
		instruction will only put the result of the decrement into w and the 
		file will remain with its original value!
 
 Special instructions
 The PIC supports some special 
		instructions which manipulate special PIC features. These are the CLRWDT, 
		SLEEP, OPTION and TRISIO instructions.
 Part of the reason why the PIC RISC core can be kept so simple is the 
		rich set of Special Function Registers (SFRs). The PIC12F629 supports 16 SFRs, which are used to access special features. All of the SFRs 
		are mapped into the PIC data space, and are accessed as if they were 
		normal RAM data locations.
 IND0 and FSR: This pair allow data memory to be indirectly 
		accessed. The address of the data memory to be accessed is placed in the 
		FSR.   FSR is file 04. The specified data memory can then be accessed as if it were in the 
		IND0 register. The following code fragment may explain this better.
 
 MOVLW        10h            
		; put value '10h'  into FSR
 MOVWF        FSR           
		;
 MOVF           
		IND0,W      ;accessing INDO actually 
		accesses data at address '10'
 
 Indirect memory access is often useful for iterative 
		(pronounced it'-ter-a-tive is an adjective 
		meaning repetitious) operations such as 
		reading or writing to buffers.
 RTCC: The RTCC SFR gives access to the RTCC register mentioned 
		above. This register may be read or modified.
 PCL and PCLATH: These registers allow access to the low 
		and high bytes of the current program counter (PC). The program counter 
		holds the ad dress of the instruction which is currently being 
		executed. Accessing the PC is not done commonly, except as a way to 
		perform table look-ups or implement state machines.
 Note that modifying the program counter invalidates the instruction 
		pipeline. This means that an extra instruction cycle is required to load 
		the next instruction.
 STATUS: The status register holds the current arithmetic status, 
		reset status and page preselector bits.
 C is the carry/borrow bit. This bit is set if a carry out or 
		borrow out occurred in the last arithmetic instruction (ADDWF, ADDLW, 
		SUBWF, SUBLW). This bit is also modified by the rotate instructions (RLF 
		and RRF).
 DC is the digit carry/borrow bit. Its semantics (the way it 
		works) are identical to 
		C for arithmetic operations, except that it reflects a carry out or 
		borrow out from bit 4 of the W register. This bit is not affected by 
		rotate operations.
 Z is the zero bit. This bit is set if the result of an 
		arithmetic, logical or MOVF instruction is zero.
 PD is the power-down bit. This is set to 1 during power-up or by 
		a CLRWDT command. It is set to 0 by a SLEEP command.
 TO is the time out bit. This is set to 1 during power up and by 
		the CRLWDT and SLEEP commands. This bit is set to zero by a watchdog 
		timeout.
 The PD and TO bits may be used in conjunction to determine the cause of 
		the last reset.
 The PIC architecture supports 1024 bytes of data space (that is: 1024 
		lines of code or 1024 "instructions and table values etc").
 RP1 and RP0 are the register page select bits for direct 
		addressing of data space.
 IRP should be maintained at 0.
 The PIC12F629 supports the entire 1024 locations of the data space. This 
		means a GOTO instruction can direct the micro to any part of the 
		program.
 OPTION: The option register controls some of the special 
		functions available on the PIC devices. The OPTION instruction is 
		used to load this register from the W register. By default all the bits 
		are 1. The OPTION register is called OPTION_REG
 PS2, PS1 and PS0 are the prescaler bits. These control the 
		prescaler division rate. PSA is the prescaler assignment bit. This 
		assigns the prescaler to the TIMER (timer0) if PSA=0. If PSA=1 it 
		assigns the prescaler to the watchdog timer (WDT).
 RTE controls the RTCC signal edge. The RTCC will increment on a low to 
		high transition if this bit is zero, otherwise the RTCC will increment 
		on a high to low transition. This is only useful if the RTS bit is set.
 RTS selects the RTCC signal source. The RTCC will increment on internal 
		clock transitions if this bit is zero, other wise the RTCC will 
		increment on transitions of the RTCC pin.
 
 INTEDG selects interrupt edge sensitivity of the INT pin (GPIO2). The 
		interrupt will occur on falling edges (high to low transitions) if this 
		bit is 1, other wise the interrupts will occur on rising edges (low 
		to high transitions).
 GPPU enables the weak pull-ups on 
		GPIO pins when this bit is set to zero, 
		otherwise the pull-ups are disabled. The pull-ups are disabled by 
		default.
 
 INTCON: This register controls which interrupts are enabled and 
		identifies which interrupts have occurred. The interrupt mechanism is 
		very flexible, to allow it to be tuned to react only to specific events.
 GPIF is the GPIO interrupt flag. This is set when any of the GPIO input pins change. This flag must be reset in software.
 INTF is the interrupt flag. This is set when the GP2/INT interrupt 
		occurs. This flag must be reset in software.
 T0IF is the Timer0 overflow interrupt flag. This is set when Timer0  overflows. This flag must be reset in software.
 GIE is the global interrupt enable flag. If this flag is zero then no 
		interrupts are enabled, otherwise the interrupts specified.
 GPIO and TRISIO: These control access to 
		the 12F629's six I/O pins. All of these pins can be used as  
		inputs and all can be used as output except GP3 (pin4) which is input 
		only. The TRISIO register controls whether the pins in GPIO are input or output. The TRISIO 
		register can be set just like any other register, providing you access 
		it in Bank 1. All output have a push-pull output 
		drivers. GPIO2 has a Schmitt trigger input which gives a 
		better noise immunity than the standard TTL level inputs of the other 
		inputs.
 All inputs have 'weak' pull-ups (typically 100uA - 47k). 
		The weak pull-up is only active while the pin is in input mode and only 
		if enabled by the RBPU bit in the OPTION register.
 A word of caution. The actual write to an I/O pin only 
		happens at the end of an instruction cycle, but the input state is 
		latched at the beginning of a read operation. If a read instruction 
		follows a write instruction, it is suggested that at least one 
		instruction be inserted between the write and read, to allow the pin 
		voltage to stabilise for the read operation.
 EEDATA, EEADR, EECON1 and EECON2: These four registers control 
		access to the 128 bytes of EEPROM data on the 12F629. EEDATA and EEADR 
		work in a similar fashion to the IND0 and FSR pair. The address of the 
		byte to be accessed is written into the EEADR register; the data at that 
		address can then be accessed via the EEDATA register. This is relatively 
		straightforward for reading the data, but writing the EEDATA is a bit 
		more complex.
 
 An EEPROM write cycle is a lengthy affair, taking up to 10 milliseconds. 
		The WR bit in the EECON1 register is cleared by the EEPROM programming 
		logic when the write cycle completes. The programming logic may also be 
		configured to generate an interrupt on completion of the write cycle.
 The EECON1 register is used to access the EEPROM control logic. It has 
		the following five bits.
 RD is the read control bit. Setting RD to 1 initiates an EEPROM read. 
		This bit is cleared after a read by hardware and can not be cleared in 
		software. A read takes one clock cycle.
 WR is the write control bit. The EEPROM write cycle is initiated by per 
		forming a fixed sequence of accessing EECON2 then setting WR to 1. WR is 
		cleared by hardware when the write cycle has completed and, like the RD 
		bit, cannot be cleared in software. As mentioned above, the write 
		operation takes about 10 milliseconds.
 
 WREN is the EEPROM write enable bit. All writes to EEPROM are inhibited 
		when this bit is zero, otherwise they are allowed.
 WRERR is the write error flag. This bit is set if a reset occurs and 
		prevents the write operation from completing.
 EEIF is the EEPROM write completion interrupt flag. This is set when a 
		write cycle completes. This will generate an interrupt if enabled by the 
		EEIE bit in the INTCON register.
 EECON2 is not a physical register and is only used for performing part 
		of the write sequence.
 
 Configuration word
 The configuration word controls the PIC's hardware features and is not a 
		register or part of the program instruction space. It is not accessible 
		at runtime, but can be accessed by the programmer. The following 
		functions are supported.
 FOSC2,
		FOSC1  and FOSC0 are used to select the oscillator type. By default, the 
		RC oscillator is configured.
 WDTE enables the watchdog timer feature. This is the only way to control 
		the watchdog timer. In particular, the watchdog timer cannot be disabled 
		by software. The watchdog timer is enabled by default.
 PWRTE is the power-up timer enable fuse. This controls the operation of 
		the power-up reset circuitry. This is enabled by default.
 CP is the code protection fuse.
 If code protection is enabled, reading the PIC will not produce any 
		meaningful output and the program cannot be over written. This prevents 
		unauthorised duplication of the program.
 This fuse also serves two extra purposes in the 12F629. Firstly, it also 
		prevents the EEPROM data from being accessed from the programmer. 
		Secondly, it provides a mechanism for erasing the EEPROM data and 
		program.
 The configuration word is created by placing "CONFIG" in the first or 
		second column and putting a double underbar in front: __CONFIG    
		In the next column is placed a number of features that are required to 
		be implemented by the micro, such as code-protection on or off, watchdog 
		timer on or off etc. Here is a typical __config with 4 features (more are normally required)
 
 __CONFIG   _CP_OFF & _WDT_OFF & _PWRTE_ON & _INTRC_OSC_NOCLKOUT
 
 
 
 
 
 
 
  12/12/07
 |