Thursday, December 6, 2007

PIC programming?....you got it! (tutorial)

Microcontrollers
and PIC
Programming
(tutorial)

Microcontrollers:

The microcontroller is an entire computer on a single chip. The
advantage of designing around a microcontroller is that a large
amount of electronics needed for certain applications can be eliminated.
This makes it the ideal device for use with mobile robots
and other applications where computing power is needed. The
microcontroller is popular because the chip can be reprogrammed
easily to perform different functions, and is very inexpensive. The
microcontroller contains all the basic components that make up a
computer. It contains a central processing unit (CPU), read-only
memory, random-access memory (RAM), arithmetic logic unit,
input and output lines, timers, serial and parallel ports, digital-toanalog
converters, and analog-to-digital converters. The scope of
this book is to discuss the specifics of how the microcontroller can
be used as the processor for the various robots that will be built.

PIC 16F84 MCU

Microchip technology has developed a line of reduced instruction
set computer (RISC) microprocessors called the programmable
interface controller (PIC). The PIC uses what is known as “Harvard
architecture.” Harvard uses two memories and separate busses.
The first memory is used to store the program, and the other is to
store data. The advantage of this design is that instructions can be
fetched by the CPU at the same time that RAM is being accessed.
This greatly speeds up execution time. The architecture commonly
used for most computers today is known as Von Neumann
architecture. This design uses the same memory for control and
RAM storage, and slows down processing time.
We will be using the PIC 16F84, shown in Figure 3.1, as the
processor for the robots in the book. This device can be reprogrammed
over and over because it uses flash read-only memory
for program storage. This makes it ideal for experimenting because
the chip does not need to be erased with an ultraviolet light source
every time you need to tweak the code or try something new.
The PIC 16F84 is an 18-pin device with an 8-bit data bus and registers.
We will be using a 4-MHz crystal for the clock speed. This
is very fast for our application when you consider that it is running
machine code at 4 million cycles per second. The PIC 16F84
is equipped with two input/output (I/O) ports, port A and port B.
Each port has two registers associated with it. The first register is
the TRIS (Tri State) register. The value loaded into this register
determines if the individual pins of the port are treated as inputs
or outputs. The other register is the address of the port itself. Once
the ports have been configured using the TRIS register, data can
then be written or read to the port using the port register address.
Port B has eight I/O lines available and Port A has five I/O lines.



PicBasic Pro Compiler

MicroEngineering Labs developed the PicBasic Pro Compiler, shown
in Figure 3.3. It is a programming language that makes it quick and
easy to program Microchip Technology’s powerful PICmicro micro-
controllers. It can be purchased from microEngineering Labs,
whose Web site is located at www.microengineeringlabs.com.
The BASIC language is much easier to read and write than
Microchip assembly language, and will be used to program the
robots in this book. The PicBasic Pro Compiler is “BASIC Stamp IIlike,”
and has most of the libraries and functions of both the BASIC
Stamp I and II. Because it is a true compiler, programs execute
much faster, and may be longer than their Stamp equivalents.
One of the advantages of the PicBasic Pro Compiler is that it uses
a real IF..THEN..ELSE..ENDIF, instead of the IF..THEN(GOTO) of
the Stamps. These and other differences are spelled out in the PBP
manual.
PicBasic Pro (PBP) defaults to create files that run on a PIC 16F84-
04/P clocked at 4 MHz. Only a minimum of other parts are necessary:
two 22pf capacitors for the 4-MHz crystal, a 4.7K pull-upresistor tied to the /MCLR pin, and a suitable 5-volt power supply.
Many PICmicros other than the 16F84, as well as oscillators of frequencies
other than 4 MHz, may be used with the PicBasic Pro
Compiler.
The PicBasic Pro Compiler produces code that may be programmed
into a wide variety of PICmicro microcontrollers having
from 8 to 84 pins and various on-chip features, including A/D converters,
hardware timers, and serial ports. For general purpose
PICmicro development using the PicBasic Pro Compiler, the PIC
16F84, 16F876, and 16F877 are the current PICmicros of choice.
These microcontrollers use flash technology to allow rapid erasing
and reprogramming to speed program debugging. With the click of
the mouse in the programming software, the flash PICmicro can be
instantly erased and then reprogrammed again and again. Other
PICmicros in the 12C67x, 14C000, 16C55x, 16C6xx, 16C7xx,
16C9xx, 17Cxxx, and 18Cxxx series are either one-time programmable
(OTP) or have a quartz window in the top (JW) to allow erasure
by exposure to ultraviolet light for several minutes. The PIC
16F84 and 16F87x devices also contain between 64 and 256 bytes
of nonvolatile data memory that can be used to store program data
and other parameters, even when the power is turned off. This
data area can be accessed simply by using the PicBasic Pro
Compiler’s READ and WRITE commands. (Program code is always
permanently stored in the PICmicro’s code space, whether the
power is on or off.)
By using a flash PICmicro for initial program testing, the debugging
process may be sped along. Once the main routines of a program
are operating satisfactorily, a PICmicro with more capabilities
or expanded features of the compiler may be utilized.
Software Installation
The PicBasic Pro files are compressed into a self-extracting file on
the diskette. They must be uncompressed to your hard drive before
use. To uncompress the files, create a subdirectory on your hard
drive called PBP or another name of your choosing by typing:
md PBP
at the DOS prompt. Change to the directory:
cd PBP
Assuming the distribution diskette is in drive a:, uncompress the
files into the PBP subdirectory:
a:\pbpxxx -d
where xxx is the version number of the compiler on the disk. Don’t
forget the -d option on the end of the command. This ensures that
the proper subdirectories within PBP are created.
Make sure that FILES and BUFFERS are set to at least 50 in your
CONFIG.SYS file. Depending on how many FILES and BUFFERS are
already in use by your system, allocating an even larger number
may be necessary.
See the README.TXT file on the diskette for more information on
uncompressing the files. Also, read the READ.ME file that is
uncompressed to the PBP subdirectory on your hard drive for the
latest PicBasic Pro Compiler information. Table 3.2 lists the different
PicBasic Pro Compiler statements that are available to the
PICmicro software developer.
Statement Description
@ Insert one line of assembly language code.



  1. ADCIN Read on-chip analog to digital converter.
  2. ASM..ENDASM Insert assembly language code section.
  3. BRANCH Computed GOTO (equiv. to ON..GOTO).
  4. BRANCHL BRANCH Out of page (long BRANCH).
  5. BUTTON Debounce and auto-repeat input on specified pin.
  6. CALL Call assembly language subroutine.
  7. CLEAR Zero all variables.
  8. CLEARWDT Clear (tickle) Watchdog Timer.
  9. COUNT Count number of pulses on a pin.
  10. DATA Define initial contents of on-chip EEPROM.
  11. DEBUG Asynchronous serial output to fixed pin and baud.
  12. DEBUGIN Asynchronous serial input from fixed pin and baud.
  13. DISABLE Disable ON DEBUG and ON INTERRUPT processing.
  14. DISABLE DEBUG Disable ON DEBUG processing.
  15. DISABLE INTERRUPT Disable ON INTERRUPT processing.
  16. DTMFOUT Produce touch-tones on a pin.
  17. EEPROM Define initial contents of on-chip EEPROM.
  18. ENABLE Enable ON DEBUG and ON INTERRUPT processing.
  19. ENABLE DEBUG Enable ON DEBUG processing.
  20. ENABLE INTERRUPT Enable ON INTERRUPT processing.
  21. END FOR..NEXT Stop execution and enter low power mode.
  22. FOR..NEXT Repeatedly execute statements.
  23. FREQOUT Produce up to 2 frequencies on a pin.
  24. GOSUB Call BASIC subroutine at specified label.
  25. GOTO Continue execution at specified label.
  26. HIGH Make pin output high.
  27. HSERIN Hardware asynchronous serial input.
  28. HSEROUT Hardware asynchronous serial output.
  29. I2CREAD Read bytes from I2C device.
  30. I2CWRITEW rite bytes to I2C device.
  31. IF..THEN..ELSE..ENDIF Conditionally execute statements.
  32. INPUT Make pin an input.
  33. LCDIN Read from LCD RAM.
  34. LCDOUT Display characters on LCD.
  35. {LET} Assign result of an expression to a variable.
  36. LOOKDOWN Search constant table for value.
  37. LOOKDOWN2 Search constant/variable table for value.
  38. LOOKUP Fetch constant value from table.
  39. LOOKUP2 Fetch constant/variable value from table.
  40. LOW Make pin output low.
  41. NAP Power down processor for short period of time.
  42. ON DEBUG Execute BASIC debug monitor.
  43. ON INTERRUPT Execute BASIC subroutine on an interrupt.
  44. OUTPUT Make pin an output.
  45. PAUSEDelay (1mSec resolution).
  46. PAUSEUS Delay (1uSec resolution).
  47. PEEK Read byte from register. (Do not use.)
  48. POKEW rite byte to register. (Do not use.)
  49. POT Read potentiometer on specified pin.
  50. PULSIN Measure pulse width on a pin.
  51. PULSOUT Generate pulse to a pin.
  52. PWM Output pulse width modulated pulse train to pin.
  53. RANDOM Generate pseudo-random number.
  54. RCTIMEMeasur e pulse width on a pin.
  55. READ Read byte from on-chip EEPROM.
  56. READCODE Read word from code memory
  57. RESUME Continue execution after interrupt handling.
  58. RETURN Continue at statement following last GOSUB.
  59. REVERSE Make output pin an input or an input pin an output.
  60. SERIN Asynchronous serial input (BS1 style).
  61. SERIN2 Asynchronous serial input (BS2 style).
  62. SEROUT Asynchronous serial output (BS1 style).
  63. SEROUT2 Asynchronous serial output (BS2 style).
  64. SHIFTIN Synchronous serial input.
  65. SHIFTOUT Synchronous serial output.
  66. SLEEP Power down processor for a period of time.
  67. SOUND Generate tone or white-noise on specified pin.
  68. SWAP Exchange the values of two variables.
  69. TOGGLEMake pin output and toggle state.
  70. WHILE..WEND Execute statements while condition is true.
  71. WRITE Write byte to on-chip EEPROM.
  72. WRITECODE Write word to code memory.
  73. XIN X-10 input.
  74. XOUT X-10 output.

Compiling A Program

For operation of the PicBasic Pro Compiler, you will need a text
editor or word processor for creation of your program source file,
some sort of PICmicro programmer such as the EPIC Plus Pocket
PICmicro Programmer, and the PicBasic Pro Compiler itself. Of
course you also need a PC to run it.
Follow this sequence of events:
First, create the BASIC source file for the program, using your favorite
text editor or word processor. If you don’t have a favorite, DOS EDIT
(included with MS-DOS) or Windows NOTEPAD (included with
Windows and Windows 95/98) may be substituted. A great text editor
called Ultraedit is available at: www.ultraedit.com. It is geared
towards the software developer and does not add any undesirable
formatting characters that will cause the compiler to error out.
The source file name should (but is not required to) end with the
extension .BAS. The text file that is created must be pure ASCII
text. It must not contain any special codes that might be inserted
by word processors for their own purposes. You are usually given
the option of saving the file as pure DOS or ASCII text by most
word processors.

Once you are satisfied that the program you have written will work
flawlessly, you can execute the PicBasic Pro Compiler by entering
PBP, followed by the name of your text file at a DOS prompt. For
example, if the text file you created is named frog-test.bas, at the
DOS command prompt, enter:
PBP example.bas
The compiler will display an initialization (copyright) message and
process your file. If it likes your file, it will create an assembler
source code file (in this case, named example.asm) and automatically
invoke its assembler to complete the task. If all goes well, the
final PICmicro code file will be created (in this case, example.hex).
If you have made the compiler unhappy, it will issue a string of
errors that will need to be corrected in your BASIC source file
before you try compilation again.
To help ensure that your original file is flawless, it is best to start
by writing and testing a short piece of your program, rather than
writing an entire 100,000-line monolith all at once and then trying
to debug it from end to end.
If you don’t tell it otherwise, the PicBasic Pro Compiler defaults to
creating code for the PIC 16F84. To compile code for PICmicros.other than the F84, just use the -P command line option, described
later in the manual, to specify a different target processor. For
example, if you intend to run the above program, example.bas, on
a PIC 16C74, compile it using the command:
PBP -p16c74 example.bas

An assembler source code file for example.bas is also generated.
It is called example.asm. The assembler source code can be used
as a guide if you want to explore assembly language programming
because the listing shows the PicBasic Pro statement and
the corresponding assembly code on the next line. The rest of the
chapters discussing software will not be addressing assembly
code. All we really need to be concerned with is the PicBasic
source code and the generated .HEX machine code.

IMPORTANT:
If you do not have the resources to buy the PicBasic Pro compiler,
simply type the listings of the .HEX files that i provide, into a text editor and save
the file with the program name and .HEX extension.

example of a hex file content:
:100000007B28A0003B200C080D04031976287020E3
:1000100084132008800664000D280E288C0A03191A
:100020008D0F0B28800676288F0022088400200977
:100030003C2084138F0803197628F03091000E08B5
:1000400080389000F03091030319910003198F0359
:10005000031976282B283F2003010C1820088E1F37
:1000600020088E0803190301900F382880061F28E6s
:10007000392800002228FF3A8417800576280D08C9


Using the EPIC Programmer
to Program the PIC

The two steps left are putting your compiled program into the
PICmicro microcontroller and testing it. The PicBasic Pro Compiler
generates standard 8-bit Merged Intel HEX (.HEX) files that may
be used with any PICmicro Programmer, including the EPIC Plus
Pocket PICmicro Programmer, shown in Figure 3.4. PICmicros
cannot be programmed with BASIC Stamp programming cables.
An example of how a PICmicro is programmed using the EPIC
Programmer with the DOS programming software follows. If
Windows 95/98/NT is available, using the Windows version of
EPIC Programmer software is recommended.
Make sure there are no PICmicros installed in the EPIC
Programmer programming socket or any attached adapters. Hook
the EPIC Programmer to the PC parallel printer port using a DB25
male-to-DB25 female printer extension cable. Plug the AC adapter
into the wall and then into the EPIC Programmer (or attach two
fresh 9-volt batteries to the programmer and connect the “Batt
ON” jumper). The light-emitting diode (LED) on the EPIC
Programmer may be on or off at this point. Do not insert a
PICmicro into the programming socket when the LED is on or
before the programming software has been started.
Enter:
EPIC
at the DOS command prompt to start the programming software.
The EPIC software should be run from a pure DOS session or from
a full-screen DOS session under Windows or OS/2. (Running
under Windows is discouraged. Windows [all varieties] alters the
system timing and plays with the port when you are not looking,
which may cause programming errors.)
The EPIC software will look around to find where the EPIC
Programmer is attached and get it ready to program a PICmicro. If
the EPIC Programmer is not found, check all the above connections
and verify that there is not a PICmicro or any adapter connected
to the programmer.
Typing:
EPIC /?
at the DOS command prompt will display a list of available options
for the EPIC software.
Once the programming screen is displayed, use the mouse to click
on Open file or press Alt-O on your keyboard. Use the mouse (or
keyboard) to select frog-test.hex or any other file you would like to
program into the PICmicro from the dialog box. The file will load
and you should see a list of numbers in the window at the left.
This is your program in PICmicro code. At the right of the screen
is a display of the configuration information that will be programmed
into the PICmicro. Verify that it is correct before proceeding.
In general, the oscillator should be set to XT for a 4-MHz
crystal, and the Watchdog Timer should be set to ON for PicBasic
Pro programs. Most important, Code Protect must be OFF when
programming any windowed (JW) PICmicro. You may not be able
to erase a windowed PICmicro that has been code protected.
Figure 3.5 shows the EPIC MS-DOS interface.
Insert a PIC 16F84 into the programming socket and click on
Program or press Alt-P on the keyboard. The PICmicro will first be
checked to make sure it is blank, and then your code will be programmed
into it. If the PICmicro is not blank and it is a flash
device, you can simply choose to program over it without erasing
first. Once the programming is complete and the LED is off, it is
time to test your program.

Testing the Controller Board
Later in Chapter 4, when the controller board is finished and the
PIC 16F84 is programmed with the frog-test.hex program, insert
the PIC into the socket on the controller board. Place the PIC into
the 18-pin I.C. socket, with the notch and pin 1 facing toward the
LEDs as shown in Figure 3.6.
Place four AA batteries in the 6-volt battery pack and secure it in
position in the holder at the back of the robot. Make sure that the
battery clip is attached, and then turn the power switch to the on
position. If all is well, then the left and right LEDs should be alternatively
flashing on and off, while the piezo element is producing
robotic frog noises. When the flashing is finished, the servos
should start rotating in a forward direction. This ensures that the
16F84 was programmed and that the controller board is functioning
properly.
If nothing is happening when the power is switched on, try going
through the process of programming the PIC again, and choose the
verify option from the EPIC user interface. If the chip fails verifica-tion, check the RS-232 cable and power supply to the programmer.
If that does not work, try using a different 16F84 chip.
If there was no error when programming the PIC, insert it back into
the controller board and make sure that pin 1 is facing toward the
LEDs. Check the battery wiring and verify that the 6-V DC polarity
is not reversed to the power connectors. Check the controller board
for any missed components or cold solder connections.
MicroCode Studio Visual Integrated
Development Environment
Mecanique’s MicroCode Studio is a powerful, visual Integrated
Development Environment (IDE), with an In Circuit Debugging
(ICD) capability designed specifically for microEngineering Labs’
PICBasic Pro Compiler. The MicroCode Studio user interface is
shown in Figure 3.7.
This studio makes programming PIC microcontrollers very easy
with a one-button process of compiling, assembling, and programming.
MicroCode Studio is completely free for noncommercial use
and can be downloaded at www.mecanique.co.uk/code-studio/. It
is not time-limited in any way, and does not have any nag screens.
However, you can only use one ICD model with MicroCode Studio.
MicroCode Studio is not copyright-free. If you wish to redistribute
MicroCode Studio, or make it available on another server, you must
contact Mecanique and obtain permission first.
The main editor provides full syntax highlighting of your code,
with context-sensitive keyword help and syntax hints. The code
explorer allows you to automatically jump to include files,
defines, constants, variables, aliases and modifiers, symbols, and
labels that are contained within your source code. Full cut, copy,
paste, and undo is provided, together with search and replace
features. It also gives you the ability to identify and correct com-pilation and assembler errors. MicroCode Studio lets you view
serial output from your microcontroller. It includes keywordbased
context-sensitive help, and also supports MPASM and
MPLAB.
It is easy to set up your compiler, assembler, and programmer
options, or you can let MicroCode Studio do it for you with its
built-in autosearch feature, as shown in Figure 3.8.
MicroCode Studio has support for MPLAB-dependent programmers
such as PICStart Plus. Compilation and assembler errors can
be easily identified and corrected using the error results window.
Just click on a compilation error and MicroCode Studio will automatically
take you to the error line. MicroCode Studio even comes
with a serial communications window, allowing you to debug and
view serial output from your microcontroller.With MicroCode Studio, you can start your preferred programming
software from within the IDE. This enables you to compile and
then program your microcontroller with just a few mouse clicks (or
keyboard strokes, if you prefer). MicroCode Studio also supports
MPLAB dependant programmers.

Summary
Now that the concept of programming and compiling code for
micro controllers has been covered, it will be easy to program the
robots in the comming posts. Using MicroCode Studio for creating
your source code, compiling the code, and programming PIC
micro controllers makes development much faster.

1 comment:

David Cary said...

The OpenServo wiki has photos of various servo internals.
OpenServo uses Atmel AVR microcontrollers to control servos.