Getting Started with the PIC Microcontroller

 

 

By

 

Randy Innerarity

Stephen F. Austin State University

Physics 475.001

Summer I, 2003

 


The original Word file and other documents can be found here:

http://observe.phy.sfasu.edu/courses/phy475/Innerarity2003/Phy475/

I. Introduction

Our modern world sometimes seems awash in remarkable new developments and products.  Most of them are interesting but their utility can run the gamut from ridiculous to truly revolutionary.  Occasionally, a product is so significant that it reshapes an entire industry.  The digital electronics field has been experiencing such an event and it's due, in part, by an amazing little device.  According to the popular WWW.howstuffworks.com web site1, these devices are in a surprising number of ordinary products.  They are in kitchen appliances, TVs, VCRs, cameras, telephones, and many others.  Modern automobiles contain at least one, and perhaps as many as six of them.  What is this device that is changing our world before our very eyes?  It's called a microcontroller.

What is a microcontroller?

In the PIC Microcontroller Project Book2, author John Iovine defines a microcontroller as a single chip computer.  This definition refers to the fact that they contain all of the functional sections (CPU, RAM, ROM, I/O, ports and timers) of a traditionally defined computer on a single integrated circuit.  The WWW.howstuffworks.com web site1 goes a bit further with their definition of a microcontroller.  They describe them as special purpose computers with several qualifying distinctions that separate them from other computers.  Quoting directly from the web site:

 

"If a computer matches a majority of these characteristics, then you can call it a microcontroller:

 

Microcontrollers are "embedded" inside some other device (often a consumer product) so that they can control the features or actions of the product.  Another name for a microcontroller, therefore, is "embedded controller."

 

Microcontrollers are dedicated to one task and run one specific program.  The program is stored in ROM (read-only memory) and generally does not change.

 

Microcontrollers are often low-power devices. A desktop computer is almost always plugged into a wall socket and might consume 50 watts of electricity.  A battery-operated microcontroller might consume 50 milliwatts.

 

A microcontroller has a dedicated input device and often (but not always) has a small LED or LCD display for output.  A microcontroller also takes input from the device it is controlling and controls the device by sending signals to different components in the device.

 

A microcontroller is often small and low cost. The components are chosen to minimize size and to be as inexpensive as possible.

 

A microcontroller is often, but not always, ruggedized in some way.  The microcontroller controlling a car's engine, for example, has to work in temperature extremes that a normal computer generally cannot handle.  A car's microcontroller in Alaska has to work fine in -30 degree F (-34 C) weather, while the same microcontroller in Nevada might be operating at 120 degrees F (49 C).  When you add the heat naturally generated by the engine, the temperature can go as high as 150 or 180 degrees F (65-80 C) in the engine compartment. On the other hand, a microcontroller embedded inside a VCR hasn't been ruggedized at all."

 

Clearly, the distinction between a computer and a microcontroller is sometimes blurred.  Applying these guidelines will, in most cases, clarify the role of a particular device.

Why are they so popular?

Figure 1.

 

The programmability of modern desktop PCs makes them extraordinarily versatile.  The functionality of the entire machine can be altered by merely changing its programming.  Microcontrollers share this attribute with their desktop relatives.  The chips are manufactured with powerful capabilities and the end user determines exactly how the device will function.  Often, this makes a dramatic difference in the cost and complexity of a particular design.  The true impact of this statement is best illustrated by example.  Figure 1 shows the schematic for a sequence counter taken from a popular logic design textbook3.  For every clock pulse, this circuit produces one of the three bit numbers in the sequence 000, 100, 111, 010, 011. This design has been implemented with three flip-flops and seven discrete gates as well as a significant amount of wiring.  The design of this system can be quite laborious.  One must begin with a state graph followed by a state table.  Then, the flip-flop T input equations must be derived from a set of Karnaugh maps.  Next, the T input equations must be transformed into the actual T input network.  All of this circuitry must then be wired together; a task that's time consuming and sometimes error prone.  Figure 2, on the other hand, shows how this can be accomplished with a simpler, less costly microcontroller design. Notice the dramatic difference in the amount of hardware and wiring.  This simple circuit, along with about a dozen lines of code, will perform the same task as the circuit in figure 1.  There are other benefits as well.  The microcontroller implementation does not have to contend with the undetermined states that sometimes occur with discrete designs. Also consider for a moment what would be required to change the sequence of numbers in the circuit of figure 1.  What if the output needs to be changed to eight bits instead of three?  These are trivial modifications for the microcontroller while the discrete circuit would require a complete redesign.

Figure 2.

 

The example above is not an obscure case.  The effects of this device are being felt in almost every facet of digital design.  A sure method of determining the popularity of an electronic device is to note when they attain widespread use by hobbyists.  The author of the PIC Microcontroller Project Book2 writes, “The future of electronics is here – and it’s microcontrollers…. It therefore becomes essential that the electronics engineer or hobbyist learn to program these microcontrollers to maintain a level of competence and to gain the advantages microcontrollers provide in his or her own circuit designs.”  Certainly, if one were in the business of selling sequence counters it wouldn’t be difficult to decide which design to take to market!

Introducing the Microchip PIC microcontroller.

The example in figure 2 uses the PIC 16F84 microcontroller made by Microchip Technology, Inc of Chandler, Arizona.  This device is one of the most popular microcontrollers in use today.  Appropriately, the term PIC stands for Programmable Interface Controller.  The 16F84 has at least two important advantages over some of its competitors.   First, the PIC’s program memory is integral to the chip.  Many of its competitors are modular designs that must access external memory by a local serial interface.  As a result, these microcontrollers are sometimes 30 to 100 times slower than the PIC2.  The second advantage of the PIC is its small size, which is also due to its on-board memory.  This device is also easy to program, reusable, and inexpensive.  All of these characteristics fulfill the criteria for inclusion in this report.  The intent of this work is to provide entry-level information on the PIC microcontroller, which will serve as a solid foundation for more advanced study.


II. A Closer Look At The PIC

Architecture

In the introduction, some parallels were drawn between desktop PCs and microcontrollers.  This cannot be done when speaking about architecture.   Most desktop computers use von Neumann architecture, which means that programs and data share a single memory area that is accessed over a common bus.  This scheme works well for general use computers but may not be of particular advantage for microcontrollers.  This is one reason that the PIC microcontroller uses Harvard architecture.  This design uses separate memory areas and buses for data and programs2.  Harvard architecture allows the instruction bus to be a different width than the data bus.  Since the instruction bus is custom tailored, an instruction can be fetched in a single clock cycle.  According to Microchip4, the last instruction can execute while the next one is being fetched, all while data memory is simultaneously being accessed.

Figure 3.  von Neumann Architecture.

Figure 4.  Harvard Architecture.

 

 

 

 

 

 

 


Memory varieties

Microchip produces field programmable microcontrollers in three basic varieties, EPROM, OTP, and Flash.   The EPROM type can be programmed electrically and erased, if needed, by a special ultraviolet light.  The device is made with a transparent window in the center of the chip that allows the UV light to act on the internal components.  The OTP variety can be programmed only once and is the least expensive of the three.  In fact, the term OTP stands for “One Time Programmable”.  This type is used for the mass production of mature applications where the program is stable and bug-free.  The Flash programmable device can be both programmed and erased by electrical means.  The PIC 16F84 chip mentioned in the introduction is a flash programmable device and will be the focus of more attention later in the report.  Flash programmable devices are ideal choices for microcontroller development systems because they can be reused hundreds of times and retain their memory for over forty years with no power5.

Inside the PIC Microcontroller

CPU

The CPU, or central processing unit, of the PIC chip performs the same functions as the one in a desktop PC.  Frequently, it's referred to as the brain of the system.  The CPU in the PIC is a RISC chip.  RISC is an acronym for Reduced Instruction Set Computer, which means that it has been designed to operate with fewer commands than other types.  The PIC has only 35 opcodes in its instruction set compared with more than 256 for a DEC Vax system6.  It is generally believed that this produces faster execution speeds and, without question, makes the chip easier to learn.  The CPU is responsible for fetching, decoding and executing instructions, and serves as a traffic cop for the program and data buses.  It also controls access to a special section of memory called the stack.  The stack retains the return address for program execution in the event of a program branch.  The CPU must also coordinate operations with the Arithmetic Logic Unit  (ALU).  This part of the chip performs the math and logic functions as well as bit shifting.

Oscillator

If the CPU is the brain of the system then the oscillator, or clock, is the heartbeat.  It provides the critical timing functions for the rest of the chip.  The original version of the 16F84 can operate at up to 4-MHz while the newer chip has a 20-MHz upper limit.  This section of the PIC is extremely versatile.  There are three principal ways to clock a PIC chip. The three clocking methods and their characteristics are listed below.

Figure 5. Crystal controlled oscillator

 

 


The greatest timing accuracy is achieved with a crystal or ceramic resonator.  For crystals of 2.0 to 10.0 MHz, the recommended capacitor values should be in the range of 15 to 33pF2.  This clocking scheme will provide a 50 ppm accuracy.


Figure 6. RC Oscillator

 


For non-critical applications, the PIC can function with a resistor/capacitor (R/C) network to set the oscillator frequency.  The manufacturer recommends an R- value of 5 -10 kW and a capacitance of greater than 20 pF.  There are no formulas for computing the RC values.  Microchip provides this information the form of graphs given in the device data sheet2.

 

Figure 7. External clock

 


The PIC can also be clocked from an external source.  The example circuit in figure 2 of the introduction uses this method.  This method is useful when the chip must be synchronized with other components or an entire system must be operated from a single clock source2.

 

 

 

Program Counter

The program counter (PC) generates addresses for the "next" instruction to be fetched.  It is this number that gets pushed onto the stack when an interrupt or program branch occurs4.  

Program Memory

As stated earlier, the PIC 16F84's program memory is separate from its data memory.  There is a total of 1K of program memory available across a 14 bit bus.  Program memory resides at the addresses from 000h to 3FFh.

Figure 8.  Register map and addresses.

 

Data Memory

Data memory is composed of two main sections, the Special Function Registers (SFRs), and the General Purpose Registers (GPRs).  The SFRs are used by the CPU and Peripheral modules to control the operation of the device.  These registers are implemented as static ram.  The GPRs are used for general data storage and scratch pad operations4.  A complete register map with individual addresses is shown in figure eight2.  It is helpful to think of the registers merely as a block of individual memory cells that contain control and general data.  Learning to manipulate the control registers is the key to fully utilizing the PIC chip. This is a task that could easily make up an entire course.  Fortunately, Microchip offers an abundance of free information on its web site at WWW.microchip.com.  This report will focus entirely on manipulating the TRISB and PORTB registers.

Timers

The PIC 16F84 has two timers, the Timer0 (T0CK) real time clock/counter and the Watchdog Timer (WDT).  The Timer0 clock is used for time measurement and event counting and can be incremented by an external or internal signal.  Figure 8 shows the control register for Timer0 located at 01h, which can be read and written just like any other register.  It can even be pre-scaled if needed. 

 

The Watchdog Timer is a special timer that must be reset at a specific time or it will generate a processor reset.  Under normal conditions, the program will reset the WDT at predetermined intervals.  If the program happens to get trapped in an infinite loop, leap past the reset point, or lock up, the WDT will trigger a full processor reset.  This is the PIC version of what happens when control-alt-delete is pressed on a desktop PC.  The only difference is that it happens automatically.  The WDT is also used to bring the 16F84 out of sleep mode, a special power saving capability of the chip. 

I/O Ports

Figure 9  Pin-out of the PIC 16F84.

The I/O ports are one of the most intriguing sections of the PIC 16F84.  There are a total of 13 I/O pins available on this chip.  Port A is comprised of the five I/O pins, RA0 to RA4, shown in the pin-out in figure 9.  Port B is an eight-bit port made up of pins RB0 to RB7.  The amazing part about these ports is that they can be programmed to be either input or output ports, even "on the fly" during operation!  Each pin can source 20 mA (max) so it can directly drive an LED.  They can also sink a maximum of 25 mA2. 


III. Programming

Overview

Programming Steps

Figure 10.  Generating a hex file.


Programming the PIC chip is a very flexible multi-step process.  First, the source code is entered in a common text file and saved with a .asm extension.  In a process similar to compiling a C or Fortran program, the assembler software then transforms the source code file into a form that can be accepted by

 

the programmer software.  Microchip provides a free assembler called MPASM or one of several "Third Party" software packages can be used.  The output file from the assembler will have a .hex extension.  This phase of the process is shown graphically in figure ten.

 

As stated above, the hex file is in a form that can be understood by the programmer software.  The programmer software controls the programmer hardware connected to the PC's parallel port.  Finally, this hardware/software combination, sometimes referred to as the burner, physically programs the hex file into the PIC chip. 

Figure 11.  "Burning" the program into the PIC chip.


 

The Language Of PICs

A Low Level Language

Several third-party companies offer assemblers and compilers to generate hex files for the PIC.  Most of them use the Basic or C languages but Microchip's free software, called MPASM, uses assembly language.  Assembly language is generally considered to be a second-generation language situated between machine code and the higher level languages such as Basic or C.  Assembly language uses mnemonic codes that correspond to machine language instructions.  Many people don't like assembly language because it is machine dependent.  This means that the assembly code for one microprocessor type may not be the same for another.

Advantages of Assembly Language

Even though assembly language is sometimes difficult to learn, it has several powerful advantages.  It uses the less memory than any of the high level languages and results in the fastest execution speed.  Assembly language also allows for very specialized data manipulation6 and is probably the main reason that Microchip selected it for use with the PIC.

Source Code

The source code is the raw program to be assembled into a hex file.  Source code for the PIC is entered in free form in much the same manner as a C program.  Normally, assembler directives are entered first followed by variable declarations.  There are a few conventions that must be followed for the actual body of the program.  First, labels must start in column one followed in column two and beyond by mnemonics. Operands must follow the mnemonics with any comments after that.  The source code is entered and saved into a common text file using a text editor.  The example program in Section IV shows a source code listing, complete with comment lines.

Assembler Directives

The source code for a PIC program consists of three basic types of information: comment lines, assembler directives, and opcodes.  It is always a good idea to include comments so that the code is properly documented.  Before any opcodes are used in the program, a few instructions must be sent to the assembler so that it will know how to process the other program elements.  This task is accomplished through the use of assembler directives.  Assembler directives that appear in the source code do not get translated into instructions for the PIC; their only function is to control the assembler.   The Microchip MPASM manual lists five types of assembler directives7:

 

• Control Directives – Control directives permit sections of conditionally

assembled code.

• Data Directives – Data Directives are those that control the allocation of

memory and provide a way to refer to data items symbolically, that is, by

meaningful names.

• Listing Directives – Listing Directives are those directives that control

the MPASM listing file format. They allow the specification of titles, pagination,

and other listing control.

• Macro Directives – These directives control the execution and data allocation

within macro body definitions.

• Object File Directives – These directives are used only when creating

an object file.

 

This report will only focus on the control and data directives that are used in the example program in Section IV.  Full documentation of assembler directives and a wealth of other PIC information can be found at the WWW.microchip.com web site.

 

The example program shown in Section IV of this report uses six of the most common assembler directives.  Five of these are control directives and one is a data directive.  They are listed below along with their syntax and meaning.

 

Control directive (as used)           Description

 


processor 16F84                        Tells the assembler which processor will be used.

 

include <p16f84.inc>                  Tells assembler to use the header file for the PIC

                                                16F84.  Functions like a C language header file.

 

J   equ   H'1F'                            Creates the variable J and stores it at address 1F (hex)

 

org   0                                       Sets the beginning program address at zero.

 

end                                           Marks the end of the program block for the assembler.

 

 

Data directive (as used)                             Description

 


__config RC_OSC & WDT_OFF &_PWRTE_ON   Issues PIC setup instructions.

 

The config directive is very important.  In the example, it tells the assembler to set up the PIC to use an RC oscillator, turn the watchdog timer off, and turn on the power-on reset timer.  There are other ways to configure the chip.  However, this is the best way because the directives are permanently written into the source code where they are recorded and can be documented.

The Core Instruction Set

The CPU, ALU, memory, and support sections of the PIC are collectively called the "core" by Microchip.  They are simply the sections that make the chip operate.   The instruction set is a collection of all of the opcodes available for use in PIC programs.  Since the PIC is a RISC chip, there are only 35 opcodes in the entire instruction set.  For the reasons mentioned earlier, Microchip prefers to use assembly language to program many of their microcontrollers.  It is sometimes helpful to think of assembly language as the clever manipulation of a matrix of register values and the instruction set provides the tools to get that done.  The names for opcodes are usually chosen as mnemonic references for the instructions supported by the architecture.  For example, the PIC mnemonic that adds the values contained in register W and another register is ADDWF.  The other register, F, is named as an argument to the mnemonic.  Another, more powerful instruction is DECFSZ.  This instruction is used as a control instruction in loop structures.  It decrements the target register (F) and then causes the program to skip the next instruction when the value of the target register is zero.  Again, the F is replaced with the actual name of the target register and is supplied as an argument. For a complete listing of PIC 16F84 instructions, see the Microchip web site for their Mid-Range MCU Family Reference Manual.  This manual contains a handy quick reference guide that lists all of the instructions with their meaning and function.  Some of the most commonly used opcodes are listed below along with a description of their function.

 

Mnemonic          Description

 

 


MOVLW             Moves a literal (a number) to the working register (W).

 

TRIS                  Moves the contents of the W register into the TRISB control register.

 

MOVWF            Moves the contents of the W register to a named target register.

 

RLF                   Rotates the bits of a named register to the left one space.

 

GOTO                Branches program execution to a point specified in the argument.

Introducing MPASM - Microchip's Assembler

MPASM is Microchip's free assembler for their microcontroller and other products.  This software will seem very familiar to those who have compiled a C or Fortran program with a command line compiler.  MPASM takes the source code file (*.asm) and assembles it into the hex file (*.hex) that will be used by the programmer hardware/software to program the PIC.  The program is available in DOS or Windows formats.  It requires an IBM PC or compatible running DOS version 5.0 or greater, or Windows 95/98 or NT.

Using MPASM Under DOS

The DOS version of MPASM is supplied as a single executable file named MPASM.exe.  Its operation is very simple.  The screen capture in figure 12 shows the first screen that appears when the program is run.  MPASM first asks for the source code filename and processor type.  The processor field can be

Figure 12.  MPASM opening screen.


changed by repeatedly pressing the ENTER key until the proper selection appears.  It is wise to generate an error file and a listing file when assembling a program.  They should also bear the same file name as the source code file.  This will make them much easier to find if they are needed.  Don't worry about the filename extensions, MPLAB will put those in automatically.  There are several hex output file types but the only type needed for the example program in this report is the INHX8M type.  The final selection asks if an object file is needed.  This is only used when developing precompiled code modules and is not used in the example program.  When all of the information has been entered, press the F10 key and MPASM will assemble the source code.  If all goes well, the program will generate a summary screen that lists any errors, warnings, messages, and the total number of lines that were assembled.  The number of lines assembled may be considerably more than the number of lines in the original source code file.  This

happens because the header file lines are automatically inserted by the assembler.  The header files are provided with the assembler and should be in the same directory with the source code file and assembler when the program is started.  The header files will have the processor name and a .inc extension.  For the PIC 16F84, the include file is named p16F84.inc.  Any errors that are generated by the assembler must be corrected before proceeding.  However, an assembler warning is mainly just a complaint or advisory.

 

The assembler will generate one or more output files, depending on what information was entered in the opening screen.  In the example of Section IV, MPASM will generate four files.  One of them will be the hex file that will be needed later.  The others are provided for convenience and diagnostic purposes.  The file with the .cod extension is used with the integrated development environment program that will be covered later.  The file with the .err extension lists any errors that were generated during the assembly process.  One of the most useful files that MPASM generates is the .lst file.  This file is a listing of the source code along with information about the include file, any error messages at the point of their occurrence, and a symbol table.  It also provides a memory usage map and a summary.  This file is particularly useful when developing PIC programs without the fancy simulation capabilities of the integrated development environment.

Using MPASM Under Windows

Figure 13   MPASMWIN.exe opening screen.

Microchip also provides a free version of MPASM with a Windows shell interface.  This version is supplied as a windows executable with the file name MPASMWIN.exe.  The program operates the same and requires the same input information as its DOS counterpart.  It is written for IBM or compatible computers running Windows 95/98 or Windows NT.  For more information on all versions of MPASM, obtain the MPASM & MPLINK manual (document number 33014g) from the Microchip web site.  Figure 13 shows the more polished appearance of the Windows opening screen7.

MPLAB - The Integrated Development Environment

Introducing the IDE

The Integrated Development Environment, or IDE, is a free software package offered by Microchip for use with its microcontroller products.  This program is also written for the IBM PC running Windows 95/98 or NT and requires 16 MB of ram and at least 45MB of hard drive space.  The IDE is a collection of development tools for writing, debugging, and optimizing applications for the PIC microcontroller.  It features a complete text editor, project manager, simulator, and more.  While the IDE is not actually required in order to program a PIC chip, it makes certain aspects of the task much easier.  The program's simulator function can save an enormous amount of time by proving that the program operates as intended before it is actually burned into the chip.  If desired, the program is capable of performing all of the required tasks.  It can interface with Microchip's programmer hardware as well as some third party hardware to make it a complete development system.  For the example in this report, the IDE will only be used to simulate the PIC program.  It is not known if MPLAB will interface with the NOPPP programmer system used in this report.  However, this does not prevent MPLAB from using a copy of the hex file in its simulator.  The following sections will show how to build and simulate a PIC program.

Creating and Building a Project

Figure 14  The IDE screen.

 

The look and feel of the IDE is similar to most other Windows programs.  It has a menu bar, toolbar, workspace, and status bar as shown in figure 14.  To create a new project, first select FILE>NEW on the menu bar.  This will open a blank editor screen where the source code can be entered.  Click FILE>SAVE to save the file when finished.  The source code file should be saved to the folder where the project will reside.  On the menu bar select PROJECT>INSTALL LANGUAGE TOOL and select MPASM.  The development mode must then be set by clicking OPTIONS>DEVELOPMENT MODE and select the simulator. From the menu bar, select PROJECT>NEW PROJECT.  Enter a name for the project and select the destination folder.  In the edit project box that pops up, enter the path for the include file that will be used.  For the example in this report, the include file is named P16F84.inc. Next, an EDIT PROJECT box will appear. This file should also be in the same folder as the project and source file, usually c:\progra~1\mplab. Next, an EDIT PROJECT box will appear.  Enter the target file name, the path for the include files, and the language and development tools.   Click the source code file in the PROJECT FILES box and then click on the ADD NODE button.  Click the OK button.  Finally, click PROJECT>BUILD ALL and MPLAB will invoke the MPASM assembler in the background.  All of the files that are created by the command line version of MPASM will be created in the destination folder.  The newly created hex file can now be used in the MPLAB simulator or programmed into a PIC chip, preferably both.

Using the Simulator

One of the most powerful features of MPLAB is the simulator.  The simulator is used after the source code is cleanly assembled.  That is, after all syntax errors and assembler errors have been corrected and a hex file has been generated.  Using the simulator allows the program to be tested without actually burning it into a PIC chip.  Obviously, this can save a lot of time.  The simulator can set break points and trace points in the source code so that the program can be stopped and analyzed at strategic points.  Another useful feature is called a Watch Window.  This is a text box that displays the contents of user selected registers as the program is run either in real time or a line at a time, called single stepping.  Single stepping can even be done automatically using the Animate feature.  The Animate feature rapidly single steps the program so that the register values can be seen dynamically changing in the watch window.  The use of the simulator allows the source code to be fully debugged and tested so that it can be burned into the PIC with greater confidence.

 

Writing The Program To The Chip

Overview Of The NOPPP Programming System

The NOPPP programming system consists of a software/hardware combination that operates through the printer port of an IBM PC or compatible.  This system loads the hex file that was created by the assembler and physically writes it into the PIC chip.  A separate power supply is also needed to provide the 5-volt operating voltage and the 12-volt programming voltage.  After the programmer has been connected to the computer and power supply, the NOPPP software is started.  The software requests information and provides instructions to the user as needed.  The following paragraphs provide a detailed description of both the software and the hardware.

The Programmer Hardware

Theory

The key to understanding the operation of the NOPPP programmer lies in the sequence of events that occur on pins 4, 12, and 13.  In order to program the PIC, 12 to 13 volts must first be applied to pin number 4.  Next, program and data bits are applied to pin 13.  When a program/data bit on pin 13 is ready, pin 12 is brought high for at least 0.1 microsecond and then brought back to ground.  The next program/data bit is applied to pin 13 and the sequence begins again.  The process continues until the entire program has been serially clocked in.  Pin 13 can also be used to transmit information in reverse, from the PIC back to the computer.  In a process called verification, the PIC transmits a copy of its program and data back to the computer so that it can be compared to the original.  The verification process is successful if no differences are found.  The timing for the signals applied to the programmer are critical.  If the timing pulses are too short, the PIC will not be programmed.  If they are too long, the programming process will be too slow.  This is one of the reason the NOPPP software is a DOS application.  Full screen DOS programs get full control of the computer5.

 

Operation

Figure 15.  NOPPP programmer schematic diagram.

 

Referring to the schematic diagram in figure 15, Q1 controls the programming voltage to pin 4 via parallel port line 2.  Program and data bits are sent to pin 13 of the PIC through resistor R2.  Parallel port line 1 provides the clocking signal for pin 12 through resistor R3.  Most of the circuit complexity for the programmer surrounds the D1, D2, and R1 components.  These circuit elements allow pin 13 to be used for both program input and verification output.  When parallel port pin 17 is made low, D1 conducts and the anode of D2 is grounded which prevents D2 current flow.  This allows pin 13 of the PIC to accept program/data bits from pin 14 of the printer port.  When parallel port pin 17 is brought high, D2 and R1 provide a pull-up voltage for the data signal on pin 13.  This allows the NOPPP software to read data through parallel port pin 11 for verification purposes.  Resistors R7 and R8 are pull-up resistors for parallel

Figure 16.  The programmer circuit board.

port lines 1 and 2.  Capacitors C1 and C2 eliminate electrical noise by de-coupling the power supply.  The schematic diagram shows that pins 18 through 25 must be grounded.  This is important because these lines supply shielding grounds for the other wires inside the parallel port cable.  Without these grounds, cross talk between the wires will cause errors in transmission through the cable.  The circuit can be built using point-to point wiring or on a universal printed circuit board.   Figure 16 shows the completed circuit board.

The Programmer Software

The NOPP software was originally written by Michael A. Covington for an article in the September 1998 edition of Electronics Now magazine.  As mentioned above, the NOPPP software is in total control of the critically timed signals to the programmer.  The program will run under MS-DOS, Windows 3.1, Windows 95, 98, or ME.  It is best to run the program full-screen instead of in a window when running under Windows because this gives full control of the computer.  The program is supplied as a single DOS executable file named NOPPP.exe.  When executed, the program interactively provides selections to program, verify, and erase several kinds of PIC microcontrollers.  A test mode is also provided so that the voltages at the programmer socket can be checked to insure that the hardware is functioning normally.  The software can be seen in action in the example project below.

IV. An Example Project

Introduction

The best way to learn about PIC microcontroller programming is to start with a simple guided example.  In this lab exercise, a PIC 16F84 microcontroller will be used to create a simple light chaser project with LEDs.  All eight pins of the PIC's PortB will be used to drive eight LEDs through current limiting resistors. The source code for the project will be entered, assembled, and simulated with the MPLAB integrated development environment.  Then, the PIC chip will be programmed with the NOPPP programmer described above.

A Simple Project

Step 1. Enter the source code.

Start the MPLAB program and on the menu bar, click on FILE>NEW.  In the editor box, enter the source code in Listing 1 below.  When finished, click FILE>SAVE and save the source code to the disk or folder where the project will be located.

Listing 1.

 

;File Demo.asm

;Assembly code for PIC 16F84 microcontroller.

 

;Blinks LEDs on PORTB outputs in a sequential pattern.

;With a 75 kHz oscillator, each LED stays on about 1/2 second.

 

;CPU configuration

;           PIC 16F84, RC oscillator, watchdog timer off, power-up timer enabled.

;            Note: two underscore characters before the config command.

 

            processor 16f84

            include  <p16f84.inc>

            __config _RC_OSC &_WDT_OFF &_PWRTE_ON

 

;Declare variables at two memory locations

 

J           equ       H'1F'     ;J stored at hex address 1F.

K          equ       H'1E'     ;K stored at hex address 1E.

 

;Program

 

            org        0          ;Start program at address zero.

 

            ;Set PORTB as output and initialize it.

 

            movlw   B'00000000'       ;Move 8 binary zeros to the W (working) register.

            tris        PORTB             ;Move Contents of W register to PORTB control register.

            movlw   B'00000001'       ;Move binary one to the W register.

            movwf   PORTB             ;Move binary one to PORTB.

 

mloop:  rlf          PORTB,f           ;Rotate PORTB bits left one space.

 

 

 

 

Listing 1. (continued)

 

 

            ;Waste some time by executing nested loops.

 

            movlw   D'5'       ;Move decimal 5 to the W register.

            movwf   J           ;Copy the decimal 5 from the W register to J.

jloop:    movwf   K          ;Copy the decimal 5 from the W register to K.

kloop:   decfsz   K,f        ;K=K-1, skip next instruction if zero.

            goto      kloop

            decfsz   J,f         ;J=J-1, skip next instruction if zero.

            goto      jloop

 

            ;Do it all again.

 

            goto      mloop

 

            end

 

 

 

 

Step 2. Set MPLAB properties.

Click PROJECT>INSTALL LANGUAGE TOOL on the menu bar.  Select Microchip, MPASM, Windowed.  Click OK.  Click OPTIONS>DEVELOPMENT MODE from the menu bar.  Click on the tabs to select MPLAB Simulator, RC clock at 75 kHz, WDT-none.  Leave the break points as they are.  Click OK.  If a message appears that says to "rebuild", press OK.

 

Step 3. Create a new project.

Click on PROJECT>NEW PROJECT on the menu bar.  Enter DEMO for the project name in place of the asterisk in the project name box.  Select the proper folder and drive for the project.  In the "List files Of Type" box, select Project files. Click OK.

 

Step 4. Set the project properties.

In the "Edit Project" box that pops up, enter the target filename (DEMO) if it's not there already.  This name should match the project name.   Set the path for the include files, usually C:\progra~1\mplab.

Set the Development Mode to MPLAB SIM PIC16F84 in the other box.  Set the Language Tool Suite to Microchip.  In the Project Files box, click "ADD NODE" and select the source code file (Demo.asm).  Click OK twice.

 

Step 5. Save the project.

Click PROJECT>SAVE PROJECT on the menu bar to save the project.

 

Step 6. Build the project (create the hex file).

Click PROJECT>BUILD ALL.  If there are no errors, the hex file will be created.  The assembler will complain mildly about the tris instruction, which is not supported in newer chips.  Assembler warnings are not critical and can be ignored in this case.

 

Step 7. Simulate the program using the MPLAB Simulator.

On the menu bar, click WINDOW>WATCH WINDOW>NEW WATCH WINDOW.  In the "Add Symbol" box, scroll down and add J, K, and PORTB.  Click CLOSE.   Next, click DEBUG>RUN>STEP.  Resize the windows and overlap them slightly with the watch window on the top.  Press F7 a few times and note the changes.  The dark bar indicates the program line that will execute the next time F7 is pressed.  This can be animated by clicking DEBUG>RUN>ANIMATE (or press CTRL F9).  Pressing the F5 key stops the animation.  Note that other useful features are available.  Click WINDOW>FILE REGISTERS and notice the 1F and 1E entries.  Also, select WINDOW>SPECIAL FUNCTION REGISTER and note the changes in the PORTB entry.  Notice that the PORTB bits are changing in a sequential pattern and then repeating. This shows that the program functions as expected.  The HELP selection on the menu bar is a good source for additional features and operating instructions.

 

Step 8. Connect and set up the NOPPP programmer.

Connect the DB-25 programmer cable to the lab station computer's parallel printer port.  Connect the 5-volt power supply and ground to the programmer at the marked locations.  Connect the variable power supply and ground to the 12-volt positions of the programmer terminal strip where marked.  Set the variable power supply to 12.5 volts then turn the power supply OFF.  The NOPPP program will prompt you when to apply power.  Figure 17 shows a properly connected NOPPP programmer.

Figure 17.  The properly connected NOPPP programmer.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



Step 9. Program the PIC.

Start the NOPPP.exe program.  The first screen will ask which LPT port to use.  Enter LPT1 for most computers.  The next screen will prompt you to apply power to the NOPPP programmer.  Next, the program asks which device you want to program.  Enter the F selection for the PIC 16F84 chip.  The next screen instructs you to insert the PIC chip into the programming socket.  Be particularly careful NOT to insert it backwards!  Align the pin number one dot on the chip with the pin one dot on the programmer label.  Figure 18 shows the next screen that will appear.  First, enter the S selection and select the PIC 16F84.  Then enter E to make sure that the PIC is blank (unless it is a new one).  Next, enter L to load the hex file.  Now everything is ready to burn the program into the chip.  Make the P selection to start the process.  If all goes well, a message appears saying that programming is complete.  Do NOT remove the PIC until the program tells you to do so.

 

Figure 18.  The NOPPP program main screen.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Step 10. Verification (optional).

Now we need to know if the PIC's program will hold if the power supply fluctuates.   This step must be done if the chip is going to be used in a real world application.  The process is very simple.  Set the 5-volt power supply for 4.25 volts and select the V option to verify the PIC.  Repeat this process in 0.25-volt increments until 5.5 volts is reached.  If the PIC verifies successfully each time then the chip passes the test.

Figure 19. The Light Chaser schematic.

Step 11. Exit the program and remove the chip.

Enter X to exit the program.  The program will now tell you that it is safe to remove the PIC from the socket.  Remove the chip and plug it into the Digital Experimenter project board.  Turn the power supply off and disconnect the programmer from the computer.  The programming process is now complete.

 

Step 12. Wire up the “Light Chaser” circuit in figure 19 and apply 5-volt power to the chip.  Note that the circuit works but the LEDs flash a bit too fast.  Do you know what program lines to change to slow the LED flash rate?

 

 

 

 

Improving the program

What is needed to slow the LED flash rate is a longer time delay.  Follow the steps below to upgrade the program.

Step 1. Open the MPLAB program and the DEMO project.  Select FILE>OPEN and open the original source code file.  Change the line that says:

 

movlw   D'5'       ;Move decimal 5 to the W register.

 

to

 

movlw   D'50'     ;Move decimal 50 to the W register.

 

This will increase the time delay by a factor of ten.  Now, save the changes and rebuild the project.

 

Step 2. Go back to step 8 of the programming process and repeat all of the steps to program the PIC with the improved hex file.  If all goes well, plug the chip back into the Digital Experimenter and apply power.  The chip should now flash at a more reasonable one-half second per LED rate.  Figure 20 shows the circuit in operation.

 

Figure 20. The Light chaser in operation.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


V. Parts List

Programmer Project

QTY      Vendor              Part #               Description                              Price ea.         Extension

 


2          Mouser             610-1N34A        1N34A Switching diode                 .34                    .68

1          Jameco             38359               2N3904 NPN transistor                 .08                    .08

3          RS                    271-1330           4.7k Ohm 1/4 W resistor                          .20                    .60

3          RS                    271-1321           1k Ohm 1/4 W resistor                 .20                    .60

1          RS                    271-1325           2.2k Ohm 1/4 W resistor                          .20                    .20

1          RS                    271-1315           330 Ohm 1/4 W resistor               .20                    .20

2          Jameco             15270               0.1 microfarad disc capacitor        .13                    .26

1          Jameco             15157               Male DB25 connector                   .89                    .89

1          Jameco             38113               18 pin IC socket                           .11                    .11

1          RS                    IC086                Universal circuit board                1.69                  1.69

1          Jameco             174001              DB25 Male ext. cable                 4.79                  4.79

1          RS                    270-1808           Project box 8x3x1                      3.99                  3.99

 


                                                                                                    Total --------------->            14.09

 

 

Light Chaser Project

QTY      Vendor              Part #               Description                              Price ea.         Extension

 


1          Jameco             145111              PIC 16F84A-04/P MCU               5.95                  5.95

1          Jameco             15270               0.1 microfarad disc capacitor        .13                    .13

1          Jameco             15190               0.001 microfarad disc capacitor     .07                    .07

1          RS                    271-1335           10k Ohm 1/4 W resistor               .20                    .20

8          RS                    271-1315           330 Ohm 1/4 W resistor               .20                  1.60

8          Mouser             512-MV5374C    Yellow LED                                 .23                  1.84

 


                                                                                                    Total ---------------->             9.79

 

 

 

 

 

 

Vendors

 

Radio Shack

Ft. Worth, TX

Stores everywhere

 

 

 

Jameco Electronics

1355 Shoreway Rd.

Belmont, CA  94002-4100

800-831-4242

WWW.Jameco.com

 

 

 

Mouser Electronics

958 N. Main

Mansfield, TX  76063-4827

800-346-6873

WWW.mouser.com

      

VI. Suggested Programmer Modifications

 

Programmer IC socket modifications.

The 18-pin programmer socket used in the original design was a low profile part.  The programmer would be easier to use if the IC socket slightly protruded through the project case.  For this reason, a wire wrap socket should be used at this point.  Four lengths of suitable insulation "spaghetti" can be used on the corner socket pins as standoffs while soldering it in place.  A zero insertion force (ZIF) socket would also be a nice addition to the project.

 

VII. Suggestions For Further Study.

 

In the course of this report, some questions arose that were never addressed due to the lack of funding or time.  The following suggestions were developed from these questions so that the project can be further refined.

 

(1.)    Can the MPLAB integrated development environment be made to recognize the NOPPP programmer system the same way as it does for the other third party programmers?  For example, MPLAB lists the Micro Engineering Labs Epic programmer as an option in the development tools selection box.  Can the NOPPP system be integrated into MPLAB in this way?

(2.)    MPLAB can simulate an external stimulus applied to an input pin.  This would be useful in a situation where an input pin is to receive pulse from a transducer and act on the information.  It would be interesting to see how this can be simulated in MPLAB.

(3.)    One of the sources for this report was the PIC Microcotroller Project Book.  This book has several very good motor control projects but they are written in the Basic language.  It would be interesting to re-write these programs in PIC assembly language and build the projects.

(4.)    Michael Covington, the author of the NOPPP magazine article (see item 5 in the References section), presented an experimental programmer circuit on his web site.  This circuit was presented as a follow-up to the original article.  The experimental circuit was never built or tested.  This may be a better design than the original because the AND gate will offer some degree of isolation between the computer and the programmer.  Also, the computer may be better protected in the event of a programmer component failure.  The schematic for the experimental programmer circuit is given below.  This circuit could be built and tested to see if it works as intended.

 


VIII. References

 

 

 

 

1HSW Media Network, 1998-2003.  How microcontrollers work. < http://WWW.howstuffworks.com>.  Accessed 2003 Jun 11.

 

2Iovine J. PIC microcontroller project book. New York: McGraw-Hill; 2000. 203 p.

 

3Roth C. Fundamentals of logic design. Boston: PWS; 1995. 770 p.

 

4Microchip Technology, Inc. Microchip PICmicro mid-range MCU family reference manual. Publication DS33023A. Chandler, AZ: Unknown publisher; 1997, 688 p.

 

5Covington M, Burn pic microcontrollers with a "no parts" pic programmer. Electronics Now 1998 Sep:35-43.

 

6Evans J, Eckhouse R, Alpha risc architecture for programmers. New Jersey: Prentice-Hall; 1999. 426 p.

 

7Microchip Technology, Inc.  MPASM user's guide with MPLINK and MPLIB. Publication DS33014. Chandler, AZ: Unknown publisher; 1999, 246 p.