For i = 1 To 10

Gosub nextchar
Serout 0,N2400,[#C
count = count * 2
Next i
Dtmfout 1,[1,2,3,4]
I2cread cont,addr,[idata]
If PORTA.1 = 0 Then pbpressed
* slip + count + 1
loop
0
1
0
0
1
1
Pi cBasi c Compi l er
micr oEngineer ing Labs, Inc.
COPYRIGHT NOTICE
Copyright ©2000 microEngineering Labs, Inc.
All rights reserved.
This manual describes the use and operation of the PicBasic Compiler
from microEngineering Labs, Inc. Use of the PicBasic Compiler without
first obtaining a license is a violation of law. To obtain a license, along
with the latest version of the product and documentation, contact
microEngineering Labs, Inc.
Publication and redistribution of this manual over the Internet or in any
other medium without prior written consent is expressly forbidden. In all
cases this copyright notice must remain intact and unchanged.
microEngineering Labs, Inc.
Box 7532
Colorado Springs CO 80933-7532
(719) 520-5323
(719) 520-1867 fax
email: support@melabs.com
web: www.melabs.com
TRADEMARKS
EPIC and PicBasic are trademarks of microEngineering Labs, Inc.
BASIC Stamp and PBASIC are trademarks of Parallax, Inc.
PICmicro is a registered trademark of Microchip Technology Inc.
11/00
Pi cBasi c Compi l er

PicBasic Compiler
i
TABLE OF CONTENTS
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. About This Manual . . . . . . . . . . . . . . . . . . . . . . . . 2
2. Compiler Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1. The PICmicros . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2. The Pins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3. Software Installation . . . . . . . . . . . . . . . . . . . . . . . 5
2.4. Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5. Program That PICmicro . . . . . . . . . . . . . . . . . . . . 7
2.6. It’s Alive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.7. I’ve Got Troubles . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.8. Coding Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.8.1. Comments . . . . . . . . . . . . . . . . . . . . . . 11
2.8.2. Symbols . . . . . . . . . . . . . . . . . . . . . . . 12
2.8.3. Labels . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.8.4. GOTO . . . . . . . . . . . . . . . . . . . . . . . . . 13
3. Command Line Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1. Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2. Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.1. Option -C . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.2. Option -D . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.3. Option -L . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.4. Option -OB . . . . . . . . . . . . . . . . . . . . . 17
3.2.5. Option -P## . . . . . . . . . . . . . . . . . . . . . 17
3.2.6. Option -Q . . . . . . . . . . . . . . . . . . . . . . 18
3.2.7. Option -S . . . . . . . . . . . . . . . . . . . . . . . 18
4. PicBasic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.1. Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.2. Numeric Constants . . . . . . . . . . . . . . . . . . . . . . . 19
4.3. String Constants . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.4. Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.5. Line Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.6. Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.7. Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.8. Multi-statement Lines . . . . . . . . . . . . . . . . . . . . . 23
PicBasic Compiler
ii
5. PicBasic Pro Statement Reference . . . . . . . . . . . . . . . . . . 25
5.1. BRANCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.2. BUTTON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.3. CALL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.4. DEBUG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.5. EEPROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5.6. END . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.7. FOR..NEXT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.8. GOSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.9. GOTO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.10. HIGH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.11. I2CIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.12. I2COUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.13. IF..THEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.14. INPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.15. {LET} . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.15.1. Multiplication . . . . . . . . . . . . . . . . . . . 43
5.15.2. Bitwise NOT Operators . . . . . . . . . . . 43
5.16. LOOKDOWN . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.17. LOOKUP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.18. LOW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.19. NAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.20. OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.21. PAUSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.22. PEEK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.23. POKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.24. POT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.25. PULSIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.26. PULSOUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.27. PWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.28. RANDOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.29. READ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.30. RETURN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.31. REVERSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.32. SERIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.33. SEROUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.34. SLEEP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.35. SOUND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.36. TOGGLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.37. WRITE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
PicBasic Compiler
iii
6. Structure of a Compiled Program . . . . . . . . . . . . . . . . . . . . 69
6.1. Target (PICmicro) Specific Header (B##.INC) . . 69
6.2. PBH.INC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3. PBC Generated Code . . . . . . . . . . . . . . . . . . . . . 71
6.4. PBL.INC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7. Other PicBasic Considerations . . . . . . . . . . . . . . . . . . . . . . 73
7.1. How Fast is Fast Enough? . . . . . . . . . . . . . . . . . 73
7.2. Assembly Language . . . . . . . . . . . . . . . . . . . . . . 74
7.2.1. Programming in Assembly Language 74
7.2.2. Assembly Language Examples . . . . . 75
7.2.3. Placement of In-line Assembly . . . . . . 78
7.2.4. The PICmicro Macro Assembler . . . . 79
7.3. Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.4. Life After 2K . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
8. Compiler / Stamp Differences . . . . . . . . . . . . . . . . . . . . . . . 83
8.1. Execution Speed . . . . . . . . . . . . . . . . . . . . . . . . . 83
8.2. Digital I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
8.3. Missing PC Interface . . . . . . . . . . . . . . . . . . . . . . 84
8.4. BUTTON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
8.5. EEPROM, READ and WRITE . . . . . . . . . . . . . . 85
8.6. GOSUB/RETURN . . . . . . . . . . . . . . . . . . . . . . . . 85
8.7. RANDOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.8. SERIN/SEROUT . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.9. Low Power Instructions . . . . . . . . . . . . . . . . . . . . 86
8.10. SLEEP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Appendix A
Summary of Microchip Assembly Instruction Set . . . . 89
Appendix B
Contact Information . . . . . . . . . . . . . . . . . . . . . . . . . . 91
PicBasic Compiler
iv
PicBasic Compiler
1
1. Introduction
The PicBasic Compiler (or PBC) makes it quick and easy for you to
program Microchip Technology’s powerful PICmicro microcontrollers.
The English-like BASIC language is much easier to read and write than
the quirky Microchip assembly language.
PBC also allows programs written for the original BASIC Stamp I to be
compiled for direct execution on members of the PICmicro family of
microcontrollers. Why would you want to do this?
Speed
Since PBC programs execute directly from the code space of the
PICmicro rather than being fetched from a serial EEPROM, PBC
programs execute much faster than equivalent programs on a BASIC
Stamp. In fact, some instructions execute hundreds of times faster!
Cost
Why pay $34 per project or, worse yet, per product? PBC allows
programs to be compiled directly into PICmicros costing $2 to $10. With
this kind of savings, the investment in the PicBasic Compiler and a
PICmicro programmer could easily pay for itself after only a few
projects. Better yet, this lower cost could turn what was just a good idea
into a viable and competitive product.
Program Size
There is no fixed limit on the number of statements a program can have.
Maximum program length is dependent upon how many different
instructions are used (i.e. the number of different library routines that
must be loaded) and the code space available in the particular
PICmicro.
PICmicro Hardware
PBC defaults to create files that run on a PIC16F84 (or PIC16F84A)
clocked at 4MHz. Only a minimum of other parts are necessary: 2 22pf
capacitors for the 4MHz crystal, a 4.7K pull-up resistor tied to the /MCLR
pin and a suitable 5- volt power supply.
PicBasic Compiler
2
Many PICmicros other than the 16F84 may be used with the PicBasic
Compiler. However, the PicBasic Compiler will not work with the older
16C5x series PICmicros. The 16C5x only provides a two level stack.
The PicBasic Compiler requires the 8 level stack provided by the newer
PICmicros.
1.1. About This Manual
This manual cannot be a full treatise on the BASIC language. It
describes the PicBasic Compiler instruction set and provides examples
on how to use it. If you are not familiar with BASIC programming, you
should acquire a book on the topic. Or just jump right in. BASIC is
designed as an easy-to-use language and there are additional example
programs on the disk and web site that can help get you started.
The next section of this manual covers installing the PicBasic Compiler
and writing your first program. Following is a section that describes
different options for compiling programs.
Programming basics are covered next, followed by a reference section
listing each PicBasic command in detail. The reference section shows
each command prototype, a description of the command and some
examples. Curly brackets, {}, indicate optional parameters.
The remainder of the manual provides information for advanced
programmers - all the inner workings of the compiler.
PicBasic Compiler
3
2. Compiler Basics
2.1. The PICmicros
The PicBasic Compiler produces code that may be programmed into a
wide variety of PICmicro microcontrollers having from 8 to 40 or more
pins and various on-chip features including A/D converters and
hardware timers and serial ports.
There are some PICmicros that will not work with the PicBasic Compiler,
notably the PIC16C5x series including the PIC16C54 and PIC16C58.
These PICmicros are based on the older 12-bit core rather than the
more current 14-bit core. The PicBasic Compiler requires some of the
features only available with the 14-bit core, the foremost of which being
the 8-level stack.
There are many, many PICmicros, some pin compatible with the ‘5x
series, that may be used with the PicBasic Compiler. Currently, the list
includes the PIC12C671, 672, PIC14C000, PIC16C554, 558, 61,
62(AB), 620(A), 621(A), 622(A), 63(A), 64(A), 642, 65(AB), 66, 662, 67,
71, 710, 711, 712, 715, 716, 717, 72(A), 73(AB), 74(AB), 76, 77, 770,
771, 773, 774, 84, 923, 924, PIC16F627, 628, 83, 84(A), 870, 871, 872,
873, 874, 876 and 877. See the READ.ME file for the latest chip support
list. For direct replacement of a PIC16C54, 56 or 58, the PIC16C554,
558, 620(A), 621(A) and 622(A) work well with the compiler and are very
nearly the same price.*
For general purpose PICmicro development using the PicBasic
Compiler, the PIC16F84 and PIC16F628 are the current PICmicros of
choice. These 18-pin microcontrollers uses flash technology to allow
rapid erasing and reprogramming to speed program debugging. With
the click of the mouse in the programming software, the PICmicro can
be instantly erased and then reprogrammed again and again. Other
PICmicros in the 12C67x, 14C000 and 16Cxxx 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 PIC16F84 also contains 64 bytes (128 bytes for the PIC16F628) of
non-volatile data EEPROM 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 Compiler’s READ
PicBasic Compiler
4
and WRITE commands. (Program code is always permanently stored in
the PICmicro’s code space whether the power is on or off.)
By using the ‘F84 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.
While many PICmicro features will be discussed in this manual, for full
PICmicro information it is necessary to obtain the appropriate PICmicro
Data Sheets or the CD-ROM from Microchip Technology. Refer to
Appendix B for contact information.
*Selling price is dictated by Microchip Technology Inc. and its distributors.
2.2. The Pins
Pins used by PicBasic Compiler commands are numbered 0 - 7 as with
the BASIC Stamp I. These pins are mapped onto PICmicro hardware
port B such that Pin0 refers to PORTB pin 0 or simply PORTB.0 (or
RB0), Pin1 refers to PORTB.1 and so forth up to Pin7 referring
PORTB.7. The pin number, 0 - 7, has nothing to do with the physical
pin number of a PICmicro. Depending on the particular PICmicro, Pin0
could be physical pin 6, 21 or 33, but in every case it is PORTB.0.
PicBasic instructions that reference a pin number such as HIGH or LOW
want only the pin number 0 - 7, eg. High 3 (set Pin3 high). If High
Pin3 is entered instead, the results are unexpected. Always use only
the number or a SYMBOL that equates to a number with pin manipulation
instructions.
On the other hand, if the current state of a pin is required, to read a
switch for example, the whole pin name would be used, eg. If Pin4 =
0 Then loop. In this case the state of Pin4 (PORTB.4) is read and if
it is low (0) the program jumps to the label loop:. If Pin4 is high (1),
the program continues with the next instruction after the If..Then.
All of the pins may be set at the same time using the predefined variable
Pins. For example, Pins = 255 sets all of the pins high. The variable
Dirs is also predefined to allow setting of the pin’s directions.
PicBasic Compiler
5
There are only 8 pins, Pin0 - Pin7, defined by the BS1 while a
PICmicro may have 13, 22, 33 or more actual I/O pins. Some library
routines such as I2COUT make use of some of these additional I/O pins
automatically. For access to other I/O pins, the PEEK and POKE
instructions were created.
2.3. Software Installation
The included software should be copied to your hard drive before use.
Create a subdirectory on your hard drive called PBC or another name of
your choosing by typing:
md c:\pbc
at the DOS prompt. Copy all of the files from the included diskette into
the newly created subdirectory by typing:
xcopy /s a:*.* c:\pbc
The /s option will insure that all of the necessary subdirectories will be
created within The PBC subdirectory. Please see the READ.ME file on
the disk for additional information.
2.4. Getting Started
For operation of the PicBasic Compiler you’ll need a text editor or word
processor for creation of your BASIC source file, some sort of PICmicro
programmer such as our EPIC Plus Pocket PICmicro Programmer, and
the PicBasic Compiler itself. Of course you also need a PC to run it all
on.
The sequence of events goes something like this:
First you 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) may be substituted. The source file name should end with
(but isn’t required to) 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
PicBasic Compiler
6
own purposes. You are usually given the option of saving the file as
pure DOS or ASCII text by most word processors.
The following program provides a good first test of a PICmicro in the
real world. You may type it in or you can simply grab it from the
SAMPLES subdirectory included on the original PicBasic Compiler
distribution disk. The file is named BLINK.BAS. The BASIC source file
should be created in or moved to the same directory where the
PBC.EXE file is located.
‘Example program to blink an LED connected to PORTB.0
about once a second
loop: High 0 ‘Turn on LED
Pause 500 ‘Delay for .5 seconds
Low 0 ‘Turn off LED
Pause 500 ‘Delay for .5 seconds
Goto loop ‘Go back and blink LED forever
End
Once you are satisfied that the program you have written will work
flawlessly, you can execute the PicBasic Compiler by entering PBC
followed by the name of your text file at a DOS prompt. For example, if
the text file you created is named BLINK.BAS, at the DOS command
prompt enter:
PBC blink
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 BLINK.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, BLINK.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 to write the
entire 100,000 line monolith all at once and then try to debug it from end
to end.
PicBasic Compiler
7
The PicBasic Compiler defaults to creating code for the PIC16F84. To
compile code for PICmicros other than the ‘F84, simply 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,
BLINK.BAS, on a PIC16C74, compile it using the command:
PBC -p16C74 blink
2.5. Program That PICmicro
There are two steps left - putting your compiled program into the
PICmicro microcontroller and testing it.
The PicBasic Compiler generates standard 8-bit Merged Intel HEX
(.HEX) files that may be used with any PICmicro programmer including
our EPIC Plus Pocket PICmicro Programmer. PICmicros cannot be
programmed with the BASIC Stamp programming cables.
The following is an example of how a PICmicro may be programmed
using our EPIC Programmer.
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 2 fresh 9-volt batteries to the programmer and connect the
“Batt ON” jumper.)
The LED(s) on the EPIC Programmer may be on or off at this point. Do
not insert a PICmicro into the programming socket when an LED is on
or before the programming software has been started.
From Windows, start EPICWin. EPICWin is the 32-bit Windows version
of the programming software and should be used with Windows 95, 98,
NT, 2000 or ME.
If you only have DOS or Windows 3.1, use the DOS version of EPIC.
The EPIC DOS software should be run from a pure DOS session. The
EPIC DOS software only supports a limited number of PICmicros. Use
PicBasic Compiler
8
EPICWin for programming the latest PICmicro microcontrollers. See
the EPIC readme file for the complete support list.
The EPIC software will take a 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 of the above connections and
verify that there is not a PICmicro or any adapter connected to the
programmer.
Once the programming screen is displayed, use the mouse to click on
Open file. Select BLINK.HEX or another file you would like to program
into the PICmicro from the dialog box.
The file will load and you can look at the Code window to see your
PICmicro program code. You should also look at the Configuration
window and verify that it is as desired before proceeding.
In general, the Oscillator should be set to XT for a 4MHz crystal and the
Watchdog Timer should be set to ON for PicBasic programs. Most
importantly, Code Protect should be OFF when programming any
windowed (JW) PICmicros. You may not be able to erase a windowed
PICmicro that has been code protected. You can find more information
on these configuration fuses in the Microchip data sheet for the device
you are using.
When it all looks marvelous, it is time to insert a PICmicro into the
programming socket and click on Program. 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 16F84 or
other flash or EEPROM 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.
2.6. It’s Alive
The sample schematic below gives you an idea of the few things that
need to be connected to the PICmicro to make it work. Basically all you
need is a pull-up resistor on the /MCLR line, a 4MHz crystal with 2
capacitors, and some kind of 5-volt power supply. We have added an
LED and resistor to provide the output from the BLINK program.
PicBasic Compiler
9
LED
470
+5V +5V
22pf 22pf
4Mhz
4.7K
.1uf
PIC16F84
1
MCLR
Vss
OSC1
OSC2
Vdd
4
5 14
15
16
17
18
RA0
RA1 RA2
RA3
RA4
RB0
RB1
RB2
RB3 RB4
RB5
RB6
RB7
2
3
6
7
8
9 10
11
12
13
Build and double check this simple circuit on a breadboard and plug in
the PICmicro you just programmed. Our line of PICProto prototyping
boards is perfect for this kind of thing.
Connect a power supply. Your PICmicro should come to life and start
blinking the LED about once a second. If it does not blink, check all of
the connections and make sure 5 volts is present at the appropriate pins
on the PICmicro.
From these simple beginnings, you can create your own world-
conquering application.
2.7. I’ve Got Troubles
The most common problems with getting PICmicros running involve
making sure the few external components are of the appropriate value
and properly connected to the PICmicro. Following are some hints to
help get things up and running.
Make sure the /MCLR pin is connected to 5 volts either through some
kind of voltage protected reset circuit or simply with a 4.7K resistor. If
you leave the pin unconnected, its level floats around and sometimes
the PICmicro will work but usually it won’t. The PICmicro has an on-
chip power-on-reset circuit so in general just an external pull-up resistor
PicBasic Compiler
10
is adequate. But in some cases the PICmicro may not power up
properly and an external circuit may be necessary. See the Microchip
PICmicro data books for more information.
Be sure you have a good crystal with the proper value capacitors
connected to it. Capacitor values can be hard to read. If the values are
off too much, the oscillator won’t start and run properly. A 4MHz crystal
with two 22pf (picofarad) ceramic disk capacitors is a good start for most
PICmicros. Once again, check out the Microchip data books for
additional thoughts on the matter.
Make sure your power supply is up to the task. While the PICmicro
itself consumes very little power, the power supply must be filtered fairly
well. If the PICmicro is controlling devices that pull a lot of current from
your power supply, they can put enough of a glitch on the supply lines to
cause the PICmicro to stop working properly. Even an LED display can
create enough of an instantaneous drain to momentarily clobber a small
power supply (like a 9-volt battery) and cause the PICmicro to lose its
place.
Check the PICmicro data sheets. Some devices have features that can
interfere with expected pin operations. The PIC16C62x and ‘F62x parts
(the 16C620, 621, 622, 16F627 and 628) are a good example of this.
These PICmicros have analog comparators on PORTA. When these
chips start up, PORTA is set to analog mode. This makes the pin
functions on PORTA work in an unexpected manner. To change the
pins to digital, simply add the lines:
Symbol CMCON = $1f
Poke CMCON, 7
near the front of your program.
Any PICmicro with analog inputs, such as the PIC12C67x, PIC16C7xx
and PIC16F87x series devices, will come up in analog mode. You must
set the pins to digital if that is how you intend to use them:
Symbol ADCON1 = $9f
Poke ADCON1, 7
Another example of potential disaster is that PORTA, pin 4 exhibits
unusual behavior when used as an output. This is because the pin has
an open collector output rather then the usual bipolar stage of the rest of
PicBasic Compiler
11
the output pins. This means it can pull to ground when set to 0, but it
will simply float when set to a 1, instead of going high. To make this pin
act in the expected manner, add a pull-up resistor between the pin and
5 volts. The value of the resistor may be between 1K and 33K,
depending on the drive necessary for the connected input. This pin acts
as any other pin when used as an input.
All of the PICmicro pins are set to inputs on power-up. If you need a pin
to be an output, set it to an output, or use a PicBasic command that
does it for you. Once again, review the PICmicro data sheets to
become familiar with the idiosyncrasies of a particular part.
Start small. Write short programs to test features you are unsure of or
might be having trouble with. Once these smaller programs are working
properly, you can build on them.
Try doing things a different way. Sometimes what you are trying to do
looks like it should work but doesn’t, no matter how hard you pound on
it. Usually there is more than one way to skin a program. Try
approaching the problem from a different angle and maybe
enlightenment will ensue.
2.8. Coding Style
Writing readable and maintainable programs is an art. There are a few
simple techniques you can follow that may help you become an artist.
2.8.1. Comments
Use lots of comments. Even though it may be perfectly obvious to you
what the code is doing as you write it, someone else looking at the
program (or even yourself when you are someone else later in life) may
not have any idea of what you were trying to achieve. While comments
take up space in your BASIC source file, they do not take up any
additional space in the PICmicro so use them freely.
Make the comments tell you something useful about what the program
is doing. A comment like “Set Pin0 to 1" simply explains the syntax of
the language but does nothing to tell you why you have the need to do
this. Something more like “Turn on the Battery Low LED” might be a lot
more useful.
PicBasic Compiler
12
A block of comments before a section of code and at the beginning of
the program can describe what is about to happen in more detail than
just the space remaining after each statement. But don’t include a
comment block instead of individual line comments - use both.
At the beginning of the program describe what the program is intended
to do, who wrote it and when. It may also be useful to list revision
information and dates. Even specifying what each pin is connected to
can be helpful in remembering what hardware this particular program is
designed to run on. If it is intended to be run with a non-standard crystal
or special compiler options, be sure to list those.
2.8.2. Symbols
Use SYMBOL to make the name of a pin or variable something more
coherent than Pin0 or B1. In addition to the liberal use of comments,
descriptive pin and variable names can greatly enhance readability.
The following code fragment demonstrates:
Symbol BattLED = Pin0 ‘Assign Pin0 a more
useful name
Symbol Capacity = B1 ‘Variable B1 will
contain the remaining
battery capacity
If Capacity < 10 Then battlow ‘If battery
capacity is
low, go
indicate it
Goto othercode ‘Else go do something
else
battlow: BattLED = 1 ‘Turn on the Battery Low
LED
Goto othercode ‘Go about other business
PicBasic Compiler
13
2.8.3. Labels
Labels should also be more meaningful than “label1:" or “here:”. Even a
label like “loop:” is more descriptive (though only slightly). Usually the
line or routine you are jumping to does something unique. Try and give
at least a hint of its function with the label, and then follow up with a
comment.
2.8.4. GOTO
Finally, try not to use too many GOTOs. While the language is not as
robust as it might be and GOTOs are a necessary evil, try to minimize
their use as much as possible. Try to write your code in logical sections
and not jump around too much. GOSUBs can be helpful in achieving
this.
PicBasic Compiler
14
PicBasic Compiler
15
3. Command Line Options
3.1. Usage
The PicBasic Compiler can be invoked from the DOS command line
using the following command format :
PBC Options Filename
Zero or more options can be used to modify the manner in which PBC
compiles the specified file. Options begin with a minus ( '-' ). The
character following the minus is a letter which selects the option.
Additional characters may follow if the Option requires more
information. Each Option must be separated by a space though no
spaces may occur within an Option. Any Option not recognized by
PBC will generate a fatal error.
The first item not starting with a minus is assumed to be the filename. If
no extension is specified and the -Q option is not invoked, the default
extension .BAS is used. If a path is specified, that directory is searched
for the named file. Regardless of where the source file is found, files
generated by PBC are placed in the current directory.
By default, PBC automatically launches the assembler (PM.EXE) if the
compilation is performed without error. PBC expects to find PM.EXE in
the same directory as PBC.EXE. If the compilation has errors or the -S
option is used, PM is not launched.
If PBC is invoked with no parameters or filename, a brief help screen is
displayed.
PicBasic Compiler
16
3.2. Options
Option Description
C
Suppress PBC Extensions
D

Generates Listing, Symbol Table, and Map File
L

Generates Listing
OB

Generates Binary rather than Merged Intel HEX
P##
Specify Target (e.g. PIC16F84)
Q
Forces use of explicit extension for Source Name
S
Skips execution of Assembler when done
† Option is passed directly to PM, if invoked after compilation.
3.2.1. Option -C
In order to given the user options in extending the PBASIC language,
PBC provides some additional capabilities above and beyond the
original specifications for PBASIC. Commands such as PEEK and POKE,
inline assembly, the CALL statement, and additional variables (W7
through W39 and B14 through B79) are language extensions. The -C
option disables these extensions, forcing strict compatibility with original
PBASIC on the program being compiled. Using any of these extensions
with -C will generate errors.
This option is useful mainly for programs developed on the BASIC
Stamp I which may have variable names which conflict with extension
keywords.
3.2.2. Option -D
The -D option causes the assembler to generate a symbol table, a
listing and a map file in addition to the normal executable image. See
the PICmicro Macro Assembler's manual on disk for more information
on the -D option.
PicBasic Compiler
17
3.2.3. Option -L
The -L option causes the assembler to generate a listing in addition to
the normal executable image. See the PICmicro Macro Assembler's
manual on disk for more information on the -L option.
Unlike PM, PBC's -L option doesn't allow the user to select an arbitrary
name for the listing file.
3.2.4. Option -OB
The -OB option forces the assembler to generate the program's
executable image as binary rather than the normal Merged Intel HEX.
See the PICmicro Macro Assembler's manual on disk for more
information on the -OB option.
3.2.5. Option -P##
By default, PBC compiles programs for the PIC16F84. PBC
accomplishes this by adding the following line to the beginning of
generated programs:
include "B16F84.INC"
The -P option can be used to select another target from the PICmicro
family. For example:
PBC -p16F628 filename
would generate this line at the start of the program:
include "B16F628.INC"
This would allow the generated program to assemble and run on a
PIC16F628. Check the INC directory for available B*.INC files.
PicBasic Compiler
18
3.2.6. Option -Q
Normally, when no extension is explicitly specified for the source
filename, the default extension .BAS is used. The -Q option prevents
this and forces the programmer to explicitly define the extension (if any)
of the source filename.
3.2.7. Option -S
Normally, when PBC successfully compiles a program, it automatically
launches the assembler. This is done to convert the assembler output of
PBC to an executable image. The -S option prevents this, leaving
PCB's output in the generated .ASM file.
Since -S prevents the assembler from being invoked, options that are
simply passed to the assembler (-D, -L, and -OB) are effectively
overridden by -S.
PicBasic Compiler
19
4. PicBasic Programming
4.1. Comments
All well written programs contain adequate comments, unless you're
Microsoft, in which case they're contained on three CD-ROMs. A PBC
comment starts with either the REM keyword or the single quote (‘ ). All
following characters on this line are ignored.
4.2. Numeric Constants
PBC allows numeric constants to be defined in the three bases:
decimal, binary and hexadecimal. Binary values are defined using the
prefix '%' and hexadecimal values using the prefix '$'. Decimal values
are the default and require no prefix.
100 ‘ Decimal Value 100
%100 ‘ Binary Value for Decimal 4
$100 ‘ Hexadecimal Value for Decimal 256
For ease of programming, single characters are converted to their ASCII
equivalents. Character constants must be quoted using double quotes
and must contain only one character (otherwise, they are string
constants).
"A" ‘ ASCII Value for Decimal 65
"d" ‘ ASCII Value for Decimal 100
4.3. String Constants
PBC doesn't provide string handling capabilities, but strings can be used
with some commands. A string contains one or more characters and is
delimited by double quotes. No escape sequences are supported for
non-ASCII characters (although most PBC commands have this
handling built-in).
"Hello" ‘ String (Short for "H","e","l","l","o")
Strings are usually treated as a list of individual character values.
PicBasic Compiler
20
4.4. Identifiers
An identifier is, quite simply, a name. Identifiers are used in PBC for line
labels and symbol names. An identifier is any sequence of letters, digits,
and underscores, although it must not start with a digit. Identifiers are
not case sensitive, thus label, LABEL and Label are all treated as
equivalent. And while labels might be any number of characters in
length, PBC only recognizes the first 32.
4.5. Line Labels
In order to mark statements that the program might wish to reference
with the GOTO or GOSUB commands, PBC uses line labels. Unlike many
older BASICs, PBC doesn't allow line numbers and doesn't require that
each line be labeled. Rather, any PBC line may start with a line label,
which is simply an identifier followed by a colon ( : ).
here: serout 0,N2400,("Hello, World!",13,10)
goto here
4.6. Variables
A number of variables have been predefined for temporary data storage
in your PicBasic program. Byte-sized variables are named B0, B1, B2
and so forth. Word-sized variables are named W0, W1, W2 and so forth.
These word-sized variables are made up of two byte-sized variables.
For example, W0 consists of B0 and B1; W1 is made up of B2 and B3 and
so forth. Any of these variables can, in effect, be renamed using the
SYMBOL command to have more meaning within your program.
These variables are actually stored in the PICmicro’s RAM registers. B0
is stored in the first available RAM location, $0C for the PIC16F84 and
some of the smaller PICmicros, or $20 for the PIC16C74 and other
larger PICmicros. Refer to the Microchip PICmicro data books for the
actual location of the start of the RAM registers for a given PICmicro.
The variables are assigned to RAM sequentially up to and including B21
at which point variables internal to the compiler library subroutines are
assigned. These assignments are done in the file PBH.INC in the INC
subdirectory. You may refer to it for additional information.
PicBasic Compiler
21
For a PICmicro with only 36 bytes of RAM, such as the PIC16C84, the
22 user variable bytes and the internal library variables use all of the
RAM that is available. For larger PICmicros like the PIC16F84 with 68
bytes of RAM and the PIC16C74 with 192 bytes of RAM, additional user
variables may be accessed. These variables continue at B22 and run
through B79 (also W11 through W39.) A particular PICmicro may not
have actual RAM at all of these additional locations. If you try to use a
variable with no RAM location, the compiler will not generate an error,
but your program will not do what you expect.
This table lists the highest user variable names that should be used with
each PICmicro:
BASIC Stamp I
B13 W6
PIC16C61
B21 W10
PIC16C71
PIC16C710
PIC16C84
PIC16F83
PIC16C711
B51 W25
PIC16F84
PIC16C554
B63 W31
PIC16C620
PIC16C621
All other
supported
PICmicros
B79 W39
The first two bytes, B0 and B1, may also be used as bit variables: Bit0,
Bit1, ..., Bit15.
Additionally, the variable names Port, Dirs and Pins are predefined.
Pins references PICmicro hardware PORTB. Dirs references the data
direction register for PICmicro hardware PORTB (TRISB). A Dir of 0
PicBasic Compiler
22
sets its associated Pin to an input and a Dir of 1 sets its associated
Pin to an output. Most instructions set the Pin’s direction
automatically. Port is a word variable that combines Pins and Dirs.
Like W0, these are overlaid and can be referenced as bits (Pin0, Pin1...
and Dir0, Dir1...).
When powered up or reset, Dirs is set to $00 (all pins input) and all
other variables are set to $00. All variable values are unsigned. Thus,
bits have the value 0 or 1, bytes 0 to 255, and words 0 to 65535.
The following table lists the predefined variables:
Word
Variables
Byte Variables Bit Variables
W0
B0 Bit0,Bit1,... Bit7
B1 Bit8,Bit9,... Bit15
W1
B2
B3
W2
B4
B5
...
...
...
W39
B78
B79
Port
Pins Pin0,Pin1,... Pin7
Dirs Dir0,Dir1,... Dir7
While the use of fixed names might seem to be limiting and lead to ugly
programs, these variables may be given more useful names via the
SYMBOL statement.
PicBasic Compiler
23
4.7. Symbols
In order to make programs more readable, PBC allows the user to
define his own symbols. These symbols may be used to represent
constants, variables or other symbols. They may not be used for line
labels. Only one symbol may be defined per SYMBOL statement.
Symbol Ten = 10 ‘ Symbolic Constants
Symbol Count = W3 ‘ Named Word Variable
Symbol BitVar = BIT0 ‘ Named Bit Variable
Symbol Alias = BitVar ‘ An Alias for BitVar
4.8. Multi-statement Lines
In order to allow more compact programs and logical grouping of related
commands, PBC supports the use of the colon (:) to separate
statements placed on the same line. Thus, the following two examples
are equivalent:
W2 = W0
W0 = W1
W1 = W2
is the same as:
W2 = W0 : W0 = W1 : W1 = W2
This does not, however, change the size of the generated code.
PicBasic Compiler
24
PicBasic Compiler
25
5. PicBasic Pro Statement Reference
BRANCH Computed GOTO (equiv. to ON..GOTO).
BUTTON Debounce and auto-repeat input on specified pin.
CALL Call assembly language subroutine at specified label.

DEBUG Debugging statement (Ignored by PBC).
EEPROM Define initial contents of on-chip EEPROM.
END Stop execution and enter low power mode.
FOR..NEXT Repeatedly execute statement(s).
GOSUB Call BASIC subroutine at specified label.
GOTO Continue execution at specified label.
HIGH Make pin output high.
I2CIN Read bytes from I
2
C device.

I2COUT Write bytes to I
2
C device.

IF..THEN GOTO if specified condition is true.
INPUT Make pin an input.
[LET] Perform math and assign result to variable.
LOOKDOWN Search table for value.
LOOKUP Fetch value from table.
LOW Make pin output low.
NAP Power down processor for short period of time.
OUTPUT Make pin output.
PAUSE Delay (1mSec resolution).
PEEK Read byte from PICmicro register.

POKE Write byte to PICmicro register.

POT Read potentiometer on specified pin.
PULSIN Measure pulse width (10uSec resolution).
PULSOUT Generate pulse (10uSec resolution).
PWM Output pulse width modulated pulse train to pin.
RANDOM Generate pseudo-random number.
READ Read byte from on-chip EEPROM.
RETURN Continue execution at statement following GOSUB.
REVERSE Make output pin an input or an input pin an output.
SERIN Asynchronous serial input (8N1).
SEROUT Asynchronous serial output (8N1).
SLEEP Power down processor.
SOUND Generate tone or white-noise on specified pin.
TOGGLE Make pin output and toggle state.
WRITE Write byte to on-chip EEPROM.
† PicBasic language extension not found in PBASIC.
PicBasic Compiler
26
5.1. BRANCH
BRANCH Offset,( Label{, Label} )
Uses Offset to index into the list of labels. Execution resumes at the
indexed label. For example, if Offset is zero, execution resumes at the
first label specified in the list. If Offset is one, at the second label. And
so on. If Offset is equal to or greater than the number of labels, no
action is taken and execution resumes with the following statement.
Branch B10,(label1,label2,label3) ‘If B10=0
goto label1;
if B10=1
goto label2;
if B10=2
goto label3
PicBasic Compiler
27
5.2. BUTTON
BUTTON Pin, Down, Delay, Rate, Var, Action, Label
Read input, perform debounce and auto-repeat on Pin.
Pin Pin number (0..7).
Down State of pin when button is pressed (0..1).
Delay Cycle count before auto-repeat starts (0..255). If 0, no debounce
or auto-repeat is performed. If 255, debounce, but no auto-
repeat, is performed.
Rate Auto-repeat rate (0..255).
Var Byte variable used for delay/repeat countdown. Should be
initialized to 0 prior to use.
ActionState of button to perform GOTO (0 if not pressed, 1 if pressed).
Label Execution resumes at this label if Action is true.
10K
I/O
10K
I/O
Button 2,0,100,10,B0,0,skip ‘Check for button
pressed on Pin2
and goto skip if
not
PicBasic Compiler
28
5.3. CALL
CALL Label
Executes the assembly language subroutine named Label. CALL is a
PicBasic Compiler statement and is not supported on the BASIC Stamp.
See the section on assembly language for more information.
Call pass ‘Call assembly language subroutine
named pass
PicBasic Compiler
29
5.4. DEBUG
PBC does not support the PBASIC DEBUG statement. PBC will,
however, parse DEBUG statements correctly and report syntax errors.
PicBasic Compiler
30
5.5. EEPROM
EEPROM { Location, } ( Constant{, Constant} )
Stores constants in consecutive bytes in on-chip EEPROM. If the
optional location value is omitted, the first EEPROM statement starts
storing at address 0 and subsequent statements store at the following
locations. If the location value is specified, it specifies the location
where these values are stored.
Constant can be a numeric constant or a string constant. Only the
least significant byte of numeric values are stored. Strings are stored as
consecutive bytes of ASCII values. No length or terminator is added
automatically.
EEPROM only works with PICmicros with on-chip EEPROM such as the
PIC16F84 and PIC16F628. The data is stored in the EEPROM space at
the time the PICmicro is programmed, not each time the program is run.
Eeprom 5,(10,20,30) ‘Store 10, 20 and 30
starting at EEPROM
location 5
PicBasic Compiler
31
5.6. END
END
Stops program execution and enters the low power mode by executing
continuous NAP commands.
End
PicBasic Compiler
32
5.7. FOR..NEXT
FOR Index = Start TO End { STEP { - } Inc }
{ Body }
NEXT { Index }
The FOR..NEXT loop allows PBC programs to executes a number of
statements (the Body) some number of times using a variable as an
index. Due to its complexity and versatility, FOR..NEXT is best
described step by step:
1) The value of Start is assigned to the index variable, Index.
Index can be a variable of any type.
2) The Body is executed. The Body is optional and can be omitted
(perhaps for a delay loop).
3) The value of Inc is added to (or subtracted from) Index. If no
STEP clause is defined, Index is incremented by one.
4) If Index is still between Start and End (inclusive), execution
resumes at Step 2.
All loop calculations are performed using 16-bit arithmetic.
For B6 = 1 to 10 ‘Count from 1 to 10
Serout 0,N2400,(#B6,” “) ‘Send each
number to
Pin0
serially
Next B6 ‘Go back to top of For
and do next count
Serout 0,N2400,(10) ‘Send a linefeed
PicBasic Compiler
33
5.8. GOSUB
GOSUB Label
Executes the statements at Label. Unlike GOTO, when the RETURN
statement is reached, execution resumes with the statement following
the GOSUB statement. The code between Label and the RETURN
statement is called a subroutine.
Subroutines can be nested. In other words, it is possible for a subroutine
to call other subroutines. Such nesting should be restricted to no more
than four levels deep.
Gosub beep ‘Execute subroutine named beep
...
beep: High 0 ‘Turn on LED connected to Pin0
Sound 1,(80,10) ‘Beep speaker connected to
Pin1
Low 0 ‘Turn off LED connected to Pin0
Return ‘Go back to main routine that called
us
PicBasic Compiler
34
5.9. GOTO
GOTO Label
Program execution continues with the statements at Label.
Goto send ‘Jump to statement labeled send
...
send: Serout 0,N2400,(“Hi”) ‘Send “Hi” out Pin0
serially
PicBasic Compiler
35
5.10. HIGH
HIGH Pin
Makes the specified pin output high. The pin is automatically made an
output pin. Only the pin number itself, i.e. 0 to 7, is specified (i.e. NOT
Pin0.)
High 0 ‘Make Pin0 an output and set it high
(~5 volts)
PicBasic Compiler
36
5.11. I2CIN
I2CIN Control, Address, Var{, Var}
Sends Control and Address out the I
2
C clock and data lines and puts
the byte(s) received into Var.
I2CIN and I2COUT can be used to read and write data to a serial
EEPROM with a 2-wire I
2
C interface such as the Microchip 24LC01B,
24LC02B and similar devices. This allows data to be stored in non-
volatile memory so that it can be maintained even after the power is
turned off. These commands operate in the I
2
C master byte read and
write modes and may also be used to talk to other devices with an I
2
C
interface like temperature sensors and A/D converters.
The lower 7 bits of the Control byte contain the control code along
with chip select or additional address information, depending on the
particular device. The high order bit is a flag indicating whether the
following Address is to be sent as an 8 bit or 16 bit address. If this flag
is low, the Address is sent as 8 bits. The control code for a serial
EEPROM is %1010.
For example, when communicating with a 24LC01B, the Address
required is 8 bits, the control code is %1010 and the chip select is
unused so the Control byte would be %01010000 or $50. Formats of
Control bytes for some of the different parts follow:
PicBasic Compiler
37
Device Capacity Control Address size
24LC01B 128 bytes %01010xxx 8 bits
24LC02B 256 bytes %01010xxx 8 bits
24LC04B 512 bytes %01010xxb 8 bits
24LC08B 1K bytes %01010xbb 8 bits
24LC16B 2K bytes %01010bbb 8 bits
24LC32B 4K bytes %11010ddd 16 bits
24LC65 8K bytes %11010ddd 16 bits
bbb = block select (high order address) bits
ddd = device select bits
xxx = don’t care
See the Microchip Non-Volatile Memory Products Data Book for more
information on these and other devices that may be used with the
I2CIN and I2COUT commands.
The I
2
C data and clock lines are predefined in the main library as
PortA.0 and PortA.1 respectively. This gets them out of the way of the
PortB pins and makes it unnecessary to define them in each I2CIN or
I2COUT statement. They may be assigned to different pins by simply
changing the equates at the beginning of the I
2
C routines in the file
PBL.INC.
The I
2
C data line should be pulled up to Vcc with a 4.7K resistor per the
following schematic as it is run in a bi-directional open-collector manner.
PicBasic Compiler
38
Symbol con = %01010000
Symbol addr = B5
addr = 17 ‘ Set address to 17
I2Cin con,addr,B2 ‘ Read data at address
17 into B2
PicBasic Compiler
39
5.12. I2COUT
I2COUT Control, Address, ( Value{, Value })
I2COUT sends Control and Address out the I
2
C clock and data lines
followed by Value.
When writing to a serial EEPROM it is necessary to wait 10ms (device
dependent) for the write to complete before attempting communication
with the device again. If a subsequent I2CIN or I2COUT is attempted
before the write is complete, the access will be ignored.
While a single I2COUT statement may be used to write multiple bytes at
once, doing so would violate the above write timing requirement for
serial EEPROMs. The multiple byte write feature may be useful with I
2
C
devices other than serial EEPROMs that don’t have to wait between
writes.
See the I2CIN command above for the rest of the story.
Symbol con = %01010000
Symbol addr = B5
addr = 17 ‘ Set address to 17
I2Cout con,addr,(56) ‘ Send the byte 56
to address 17
Pause 10 ‘ Wait 10ms for write to
complete
addr = 127 ‘ Set address to 127
I2Cout con,addr,(B12) ‘ Send the byte in
B12 to address 127
Pause 10 ‘ Wait 10ms for write to
complete
PicBasic Compiler
40
5.13. IF..THEN
IF Comp { AND/OR Comp } THEN Label
Performs one or more comparisons. Each Comp term can relate a
variable to a constant or other variable and must be in the following
form:
Var ( < | <= | = | <> | >= | > ) Value
All comparisons are unsigned since PBC only supports unsigned types.
A variable must occur on the left.
The THEN in an IF..THEN is essentially a GOTO. If the condition is
true, the program will GOTO the label after the THEN. If the condition
evaluates to false, the program will continue at the next line after the
IF..THEN. Another statement may not be placed after the THEN, it
must be a label.
If Pin0 = 0 Then pushd ‘If button connected to
Pin0 is pushed (0), jump
to label pushd
If B0 >= 40 Then old ‘If the value in
variable B0 is greater
than or equal to 40,
jump to old
PicBasic Compiler
41
5.14. INPUT
INPUT Pin
Makes the specified pin an input. Only the pin number itself, i.e. 0 to 7,
is specified (i.e. NOT Pin0.)
Input 1 ‘Make Pin1 an input
PicBasic Compiler
42
5.15. {LET}
{ LET } Var = { - } Value { Op Value }
Assigns a value to a variable. The value may be a constant, the value of
another variable or the result of one or more binary operations. The
operations are performed strictly left to right and all operations are
performed with 16-bit precision. Unary negation may only be performed
on the first value. The operators supported are:
+ Addition
-
Subtraction
*
Multiplication
**
MSB of Multiplication
/
Division
//
Remainder
MIN
Minimum
MAX
Maximum
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
&/
Bitwise AND NOT
|/
Bitwise OR NOT
^/
Bitwise XOR NOT
Let B0 = 27 ‘Assign variable B0 the value 27
(“Let” is optional)
B1 = B0 / 2 ‘Assign variable B1 B0's value
shifted right one bit (divided by 2)
Pin2 = 0 ‘Make Pin2 low (does not set Pin2 to
an output)
PicBasic Compiler
43
5.15.1. Multiplication
PBC performs 16x16 multiplication. The '*' operator returns the lower 16
bits of the 32-bit result. This is the typical multiplication found in most
programming languages. The '**' operator returns the upper 16 bits of
the 32-bit result. These two operators can be used in conjunction to
perform 16x16 multiplication to produce 32-bit results.
W1 = W0 * 1000 ‘Multiply value in W0 by 1000
and place the result in W1
W2 = W1 ** W0 ‘Multiply W1 by W0 and place
the high order 16 bits (which
may be 0) in W2
5.15.2. Bitwise NOT Operators
Along with the normal bitwise binary operators (AND, OR, XOR), PBC also
supports NOT versions. These versions perform a bitwise complement
on the right-hand value prior to performing the operation.
B3 = B3 &/ %11110000 ‘Same as B3 = B3 &
%00001111
PicBasic Compiler
44
5.16. LOOKDOWN
LOOKDOWN Search, ( Constant{, Constant} ), Var
The LOOKDOWN statement searches a list of Constant values for the
presence of the Search value. If found, the index of the matching
constant is stored in Var. Thus, if the value is found first in the list, Var
is set to zero. If second in the list, Var is set to one. And so on. If not
found, no action is taken and Var remains unchanged.
The constant list can be a mixture of numeric and string constants. Each
character in a string is treated as a separate constant with the
character's ASCII value.
Serin 1,N2400,B0 ‘Get hexadecimal
character from Pin1
serially
Lookdown B0,(“0123456789ABCDEF”),B1 ‘Convert
hexadecimal
character in
B0 to
decimal
value B1
Serout 0,N2400,(#B1) ‘Send decimal value to
Pin0 serially
PicBasic Compiler
45
5.17. LOOKUP
LOOKUP Index, ( Constant{, Constant} ), Var
The LOOKUP statement can be used to retrieve values from a table of
constants. If Index is zero, Var is set to the value of the first
Constant. If Index is one, Var is set to the value of the second
Constant. And so on. If Index is greater than or equal to the number
of entries in the constant list, no action is taken and Var remains
unchanged.
The constant list can be a mixture of numeric and string constants. Each
character in a string is treated as a separate constant equal to the
character's ASCII value.
For B0 = 0 to 5 ‘Count from 0 to 5
Lookup B0,(“Hello!”),B1 ‘Get character
number B0 from
string to variable
B1
Serout 0,N2400,(B1) ‘Send character in
B1 to Pin0
serially
Next B0 ‘Do next character
PicBasic Compiler
46
5.18. LOW
LOW Pin
Makes the specified pin output low. The pin is automatically made an
output pin. Only the pin number itself, i.e. 0 to 7, is specified (i.e. NOT
Pin0.)
Low 0 ‘Make Pin0 an output and set it low (0
volts)
PicBasic Compiler
47
5.19. NAP
NAP Period
Places PICmicro in low power mode for short periods of time. During
this NAP, power consumption is reduced to minimum. The listed periods
are only approximate because the timing is derived from the Watchdog
Timer which is R/C driven and varies greatly from chip to chip and over
temperature:
Period
Delay (Approx.)
0 18 mSec
1 36 mSec
2 72 mSec
3 144 mSec
4 288 mSec
5 576 mSec
6 1.152 Sec
7 2.304 Sec
Nap 7 ‘Low power pause for about 2.3 seconds
PicBasic Compiler
48
5.20. OUTPUT
OUTPUT Pin
Make the specified pin an output. Only the pin number itself, i.e. 0 to 7,
is specified (i.e. NOT Pin0.)
Output 0 ‘Make Pin0 an output
PicBasic Compiler
49
5.21. PAUSE
PAUSE Period
Pauses the program for Period milliseconds. Period is 16-bits, so
delays can be up to 65,535 milliseconds (a little over a minute). Unlike
the other delay functions (NAP and SLEEP), PAUSE doesn't put the
PICmicro into low power mode. Thus, PAUSE consumes more power but
is also more accurate. It has the same accuracy as the system clock.
Pause 1000 ‘Delay for 1 second
PicBasic Compiler
50
5.22. PEEK
PEEK Address, Var
Reads the PICmicro register at the specified Address and stores the
result in Var. Special PICmicro features such as A/D converters and
additional I/O ports may be read using PEEK. PEEK is a PicBasic
Compiler statement and is not supported on the BASIC Stamp.
PEEK and POKE allow direct access to all of the registers on a PICmicro
including PORTA, PORTB, PORTC, PORTD, PORTE and their
associated data direction (TRIS) registers. PEEK and POKE operate on
all of the bits, i.e. the entire byte, of the particular register at once.
When you POKE data to PORTA, the entire port is updated, not just one
individual bit.
If substantial individual bit manipulation is required, it is recommended
that those I/O functions be assigned to a pin on PORTB and less
demanding byte access be left to the other I/O ports. Alternatively
variable B0 allows manipulation of its individual bits. It can first be set
up as desired and then POKEd to PORTA, for example, to ease bit
manipulation. Following are examples of this technique. This technique
may be used with any PICmicro register.
‘ Read PortA bits using intermediate variable B0
Symbol PortA = 5 ‘Define PortA register
location
Symbol TrisA = $85 ‘Define PortA direction
register location
Poke TrisA,255 ‘Make all PortA pins
inputs
loop: Peek PortA,B0 ‘Get current PortA pin
states to variable B0
If Bit0 = 1 Then zerohigh ‘Jump to
label
zerohigh if
Bit0 (RA0)
is high
PicBasic Compiler
51
If Bit1 = 0 Then onelow ‘Jump to label
onelow if Bit1
(RA1) is low
Goto loop ‘Go check some more
zerohigh: High 0 ‘Set Pin0 (RB0) high
Goto loop ‘Go do some more
onelow: Low 1 ‘Set Pin1 (RB1) low
Goto loop ‘Go do some more
End
‘ Set PortA bits using intermediate variable B0
Symbol PortA = 5 ‘Define PortA register
location
Symbol TrisA = $85 ‘Define PortA direction
register location
Poke TrisA,0 ‘Make all PortA pins
outputs
Peek PortA,B0 ‘Get current PortA pin
states to variable B0
Bit1 = 1 ‘Set Bit1 in B0 which will
become PortA pin 1 high
Bit3 = 0 ‘Set Bit3 in B0 which will
become PortA pin 3 low
‘Bit0, 2 and 4 will remain
unchanged
Poke PortA,B0 ‘Send the new byte to
PortA to complete the
change
End
PicBasic Compiler
52
5.23. POKE
POKE Address, Value
Writes Value to the PICmicro register at the specified Address.
Special PICmicro features such as A/D converters and additional I/O
ports may be written using POKE. POKE is a PicBasic Compiler
statement and is not supported on the BASIC Stamp. (See PEEK for
more information.)
Poke $85,0 ‘Write 0 to register hexadecimal 85
(Sets PortA to all outputs)
PicBasic Compiler
53
5.24. POT
POT Pin, Scale, Var
Reads a potentiometer (or some other resistive device) on Pin. Pins are
numbered 0 to 7.
The resistance is measured by timing the discharge of a capacitor
through the resistor (typically 5K to 50K). Scale is used to adjust for
varying R/C constants. For larger R/C constants, Scale should be set
low (a minimum value of one). For smaller R/C constants, Scale should
be set to its maximum value (255). If Scale is set correctly, Var should
be set to zero near minimum resistance and to 255 near maximum
resistance.
Unfortunately, Scale must be determined experimentally. To do so, set
the device under measure to maximum resistance and read it with
Scale set to 255. Under these conditions, Var will produce an
appropriate value for Scale. (NOTE: This is the same type of process
performed by the Alt-P option of the PBASIC environment).
0.1uF
5-50K
Pin
Pot 3,255,B0 ‘Read potentiometer on
Pin3 to determine scale
Serout 0,N2400,(#B0) ‘Send pot value serially
out Pin0
PicBasic Compiler
54
5.25. PULSIN
PULSIN Pin, State, Var
Measures pulse width in 10 uSec units on Pin. If State is zero, the
width of a low pulse is measured. If State is one, the width of a high
pulse is measured. The measured width is placed in Var, which can
take measurements from 10 uSec to 655,350 uSec for 16-bit variables.
If the pulse edge never happens or the width of the pulse is too great to
measure, Var is set to zero. If an 8-bit variable is used, only the LSB of
the 16-bit measurement is used. Pins are numbered from 0 to 7.
Pulsin 4,1,W3 ‘Measure high pulse on Pin4
and place width * 10uSec in W3
PicBasic Compiler
55
5.26. PULSOUT
PULSOUT Pin, Period
Generates a pulse on Pin of specified Period in 10 uSec units. Since
Period is 16-bits, pulses of up to 655,350 uSec can be generated. The
pulse is generated by toggling the pin twice, thus the initial state of the
pin determines the polarity of the pulse. The pin is automatically made
an output pin. Pins are number 0 to 7.
Pulsout 5,100 ‘Send a pulse 1mSec long to
Pin5
PicBasic Compiler
56
5.27. PWM
PWM Pin, Duty, Cycle
Outputs PWM pulse train on Pin. Each cycle of PWM consists of 256
steps. The Duty cycle for each PWM cycle ranges from 0 (0%) to 255
(100%). This PWM cycle is repeated Cycle times. Pins are numbered
from 0 to 7.
The pin is made an output just prior to pulse generation and reverts to
an input after generation stops. This allows a simple R/C circuit to be
used as a simple D/A converter:
10K
1uF
Pin Analog Out
Pwm 7,127,100 ‘Send a 50% duty cycle PWM
signal out Pin7 for 100 cycles
PicBasic Compiler
57
5.28. RANDOM
RANDOM Var
Performs one iteration of pseudo-randomization on Var. Var must be a
16-bit variable. (NOTE: PBC does not support the use of the PORT
variable with the RANDOM statement). The pseudo-random algorithm
used has a walking length of 65535 (only zero is not produced).
Random W4 ‘Get a random number to W4
PicBasic Compiler
58
5.29. READ
READ Address, Var
Reads the EEPROM byte at the specified Address and stores the result
in Var. If Address is 255 and the device is a PIC16C84, 16F627, 628,
83 or 84, Var is assigned the number of EEPROM bytes available.
Address 255 is not valid for 16F87x devices. This instruction may only
be used with a PICmicro that has an on-chip EEPROM data area such
as the PIC16C84, 16F62x, 8x and 87x.
Read 5,B2 ‘Put the value at EEPROM location 5
into B2
PicBasic Compiler
59
5.30. RETURN
RETURN
Returns from subroutine. RETURN resumes execution at the statement
following the GOSUB which called the subroutine.
Gosub sub1 ‘Go to subroutine labeled sub1
...
sub1: Serout 0,N2400,(“Lunch”) ‘Send “Lunch” out
Pin0 serially
Return ‘Return to main program after
Gosub
PicBasic Compiler
60
5.31. REVERSE
REVERSE Pin
If the pin is an input, it is made an output. If the pin is an output, it is
made an input. Pins are numbered 0 to 7.
Output 4 ‘Make Pin4 an output
Reverse 4 ‘Change Pin4 to an input
PicBasic Compiler
61
5.32. SERIN
SERIN Pin, Mode,{ (Qual{,Qual}), } Item{,Item}
Receives one or more items on Pin in standard asynchronous format
using 8 data bits, no parity and one stop bit. Mode is one of the
following:
Symbol Value Baud Rate Mode
T2400
0 2400
TTL True
T1200
1 1200
T9600
2 9600

T300
3 300
N2400
4 2400
TTL Inverted
N1200
5 1200
N9600
6 9600

N300
7 300
† 9600 baud is an addition to the PicBasic Compiler and is not available
on the BASIC Stamp I.
22K
Pin RS-232 TX
RS-232 GND
Pin 3
Pin 5 Pin 7
Pin 2
DB9 DB25
The list of data items to be received may be preceded by one or more
qualifiers enclosed within parenthesizes. SERIN must receive these
bytes in exact order before receiving the data items. If any byte received
does not match the next byte in the qualifier sequence, the qualification
process resets (i.e. the next received byte is compared to the first item
in the qualifier list). A Qualifier can be a constant, variable or a string
constant. Each character of a string is treated as an individual qualifier.
Once the qualifiers are satisfied, SERIN begins storing data in the
variables associated with each Item. If the variable name is used alone,
PicBasic Compiler
62
the value of the received ASCII character is stored in the variable. If
variable is preceded by a pound sign ( # ), then SERIN converts a
decimal value in ASCII and stores the result in that variable. All non-
digits received prior to the first digit of the decimal value are ignored and
discarded. The non-digit character which terminates the decimal value is
also discarded.
While single-chip RS-232 level converters are common and
inexpensive, the excellent I/O specifications of the PICmicro allow most
applications to run without level converters. Rather, inverted input
(N9600..N300) can be used is conjunction with a current limiting
resistor.
Serin 1,N2400,(“A”),B0 ‘Wait until the
character “A” is
received serially on
Pin1 and put next
character into B0
PicBasic Compiler
63
5.33. SEROUT
SEROUT Pin, Mode, Item{,Item}
Sends one or more items to Pin is standard asynchronous format using
8 data bits, no parity and one stop. Mode is one of the following:
Symbol Value Baud Rate Mode
T2400
0 2400
TTL True
T1200
1 1200
T9600
2 9600

T300
3 300
N2400
4 2400
TTL Inverted
N1200
5 1200
N9600
6 9600

N300
7 300
OT2400
8 2400
Open Drain
OT1200
9 1200
OT9600
10 9600

OT300
11 300
ON2400
12 2400
Open Source
ON1200
13 1200
ON9600
14 9600

ON300
15 300
† 9600 baud is an addition to the PicBasic Compiler and is not available
on the BASIC Stamp I.
SEROUT supports three different data types which may be mixed and
matched freely within a single SEROUT statement.
1) A string constant is output as a literal string of characters.
2) A numeric value (either a variable or a constant) will send the
corresponding ASCII character. Most notably, 13 is carriage
return and 10 is line feed.
3) A numeric value preceded by a pound sign ( # ) will send the
PicBasic Compiler
64
ASCII representation of its decimal value. For example, if W0 =
123, then #W0 (or #123) will send '1', '2', '3'.
While single-chip RS-232 level converters are common and
inexpensive, thanks to current RS-232 implementation and the excellent
I/O specifications of the PICmicro, most applications don't require level
converters. Rather, inverted TTL (N300..N9600) can be used. A current
limiting resistor is suggested (RS-232 is suppose to be short-tolerant).
1K
Pin RS-232 RX
RS-232 GND
Pin 2
Pin 5 Pin 7
Pin 3
DB9 DB25
Serout 0,N2400,(#B0,10) ‘Send the ASCII value of
B0 followed by a
linefeed out Pin0
serially
PicBasic Compiler
65
5.34. SLEEP
SLEEP Period
Places PICmicro in low power mode for Period seconds. Period is
16-bits, so delays can be up to 65,535 seconds (just over 18 hours).
SLEEP uses the Watchdog Timer to periodically wake up to see if the
Period has expired so its resolution is the maximum timeout for the
Watchdog Timer, 2.3 seconds.
Sleep 60 ‘Sleep for 1 minute
PicBasic Compiler
66
5.35. SOUND
SOUND Pin,( Note, Duration{, Note, Duration} )
Generates tone and/or white noise on the specified Pin. Note 0 is
silence. Notes 1-127 are tones. Notes 128-255 are white noise. Tones
and white noises are in ascending order (i.e. 1 and 128 are the lowest
frequencies, 127 and 255 are the highest). Duration is 0-255 and
determines how long the Note is played. Note and Duration needn't
be constants. Pins are numbered 0 to 7.
SOUND outputs TTL-level square waves. Thanks to the excellent I/O
characteristics of the PICmicro, a speaker can be driven through a
capacitor. Piezo speakers can be driven directly.
Pin
10uF
Sound 7,(100,10,50,10) ‘Send 2 sounds
consecutively to Pin7
PicBasic Compiler
67
5.36. TOGGLE
TOGGLE Pin
Inverts the state of the specified pin. The pin is automatically made an
output pin. Pins are numbered 0 to 7.
Low 0 ‘Start Pin0 as low
Toggle 0 ‘Change state of Pin0 to high
PicBasic Compiler
68
5.37. WRITE
WRITE Address, Value
Writes byte Value to the EEPROM at the specified Address. This
instruction may only be used with a PICmicro that has an on-chip
EEPROM data area such as the PIC16C84, 16F62x, 8x and 87x.
Write 5,B0 ‘Send value of B0 to EEPROM location
5
PicBasic Compiler
69
6. Structure of a Compiled Program
PBC is designed to be easy to use. Programs can be compiled and run
with little thought to PBC's internal workings. Some people, however,
only have confidence in a product when they understand its internal
workings. Others are just plain curious.
This section is for them. It describes the output generated by PBC and
gives some idea of exactly what is going on.
6.1. Target (PICmicro) Specific Header (B##.INC)
The first thing a PBC generated program does is define the symbol
PBCX to be 1 if PBC extensions are enabled, or 0 if PBC extensions are
disabled (-C option). This allows the library to selectively define
additional variables and functions needed for PBC extensions.
Next, a target specific header file is included. By default, this file is
B16F84.INC, although this can be changed using the -P option.
This header is, in turn, responsible for including (via MACLIB) the
processor specific header supplied with PM. The PM header, in turn,
defines all the processor specific information needed to assemble
programs for that PICmicro.
The B##.INC header then uses the DEVICE pseudo-op to set the
processor's fuses. For NAP and SLEEP to work, the Watchdog Timer
must be enabled. The oscillator must also be set appropriately. Other
fuse positions can be set at the user's discretion. See the Microchip
data sheet for the particular device for information about the
configuration fuses.
The DATA pseudo-op is next used to select the data segment as the
current segment. It should also place the load pointer at the base of
usable RAM in the target processor. In the case of a PIC16Cxxx, this
will either be 0Ch or 20h. Selecting one of these addresses is important
because PBC's internal bit numbering scheme relies on selecting one of
these two addresses.
The header should then execute NLIST to disable listing. This hides
tedious, uninteresting and unchanging implementation details in
PBH.INC.
PicBasic Compiler
70
Then PBH.INC is included. If desired, macro and bit addresses defined
in PBH.INC can be overridden by being defined here.
When PBH.INC is done, listing is enabled and the code segment is
selected. At this point, any target specific library routines should be
added. Since these routines must be assembled before the user's code
is assembled, they must assemble unconditionally (unlike the normal
library routines). Hence, such target specific routines should be as brief
as possible.
The last thing left to do is define the main label, which is where the
user's code will start execution.
6.2. PBH.INC
PBH.INC first defines user variables in the data segment. This is
followed by the definition of working and temporary registers used by
PBC's libraries. User variables can occupy up to 80 bytes of memory
unless the -C option is used, in which case only 14 bytes are used.
Working variables and temporary registers occupy another 13-16 bytes.
PINx, DIRx, and other bit locations are numbered. All bits of interest
(PORT, TRIS, and the bits of W0) need to be spanned by an 8-bit value in
order to take best advantage of the W register. Since normal PICmicro
numbering requires 11 bits, a custom system was developed. Its details
are uninteresting, but it is important to understand that PBC bit numbers
need to be converted before use and cannot be used verbatim in an
assembly language subroutine.
A number of macros are defined. Some are simple utility macros. Some
perform the bit mapping mentioned earlier. And some macros access
the PINS and DIRS registers. These are particularly interesting since
they can be overridden by definitions in B##.INC.
The code segment is then selected and startup code is generated. This
is followed by a set mandatory library routines. The FW@Pin and
FW@Mask functions are responsible for the run time mapping of PBC bit
numbers onto the FSR and W registers.
6.3. PBC Generated Code
PicBasic Compiler
71
B##.INC and PBH.INC have now laid all the ground work for the
compiled code. The code segment is the current segment and the load
pointer is set to main, the place where the user's code begins
execution.
After the user's code is assembled, PBC's library PBL.INC is included.
6.4. PBL.INC
PBL.INC contains library support routines. Most of the routines
corresponding to PBC statements end in the '@' character. Block
comments indicate each routine's functionality. Routines are ordered
such that every routine in the library is only dependent on routines which
occur later in the library. Each routine is conditionally assembled only if
it is explicitly referenced (via the REF operator). In this way, only needed
library routines are actually assembled.
The first module in PBL.INC is end@. Unlike other modules in the
library, end@ is always assembled. This simulates the END statement
implicitly at the end of each PBC program.
PicBasic Compiler
72
PicBasic Compiler
73
7. Other PicBasic Considerations
7.1. How Fast is Fast Enough?
The PicBasic Compiler generates programs intended to be run on a
PICmicro with a 4MHz crystal or ceramic resonator. All of the time
sensitive instructions assume a 1 microsecond instruction time for their
delays. This allows a Pause 1000, for example, to wait 1 second and
the SERIN and SEROUT command’s baud rates to be accurate.
There are times, however, when it would be useful to run the PICmicro
at a frequency other than 4MHz. Even though the compiled programs
move along at a pretty good clip, it might be nice to run them even
faster. Or maybe it is desirable to do serial input or output at 19,200
baud rather than the current top speed of 9600 baud.
PicBasic Compiler programs may be run at clock frequencies other than
4MHz if you pay attention to what happens to the time dependent
instructions. If you wish to run the serial bus at 19,200 as described
above, you would simply clock the PICmicro with an 8MHz crystal rather
than a 4MHz crystal. This, in effect, makes everything run twice as fast,
including the SERIN and SEROUT commands. If you tell SERIN or
SEROUT to run at 9600 baud, the doubling of the crystal speed will
double the actual baud rate to 19,200 baud.
However, keep in mind commands such as PAUSE and SOUND will also
run twice as fast. The Pause 1000 mentioned above would only wait
half a second with an 8MHz crystal before allowing program execution
to continue.
This technique may also be used to enhance the resolution of the
PULSIN and PULSOUT instructions. At 4MHz these instructions operate
with a 10 microsecond resolution. If a 20MHz crystal is used, the
resolution is increased 5 times to 2 microseconds. There is a tradeoff
however. The pulse width is still measured to a 16-bit word variable.
With a 2 microsecond resolution, the maximum measurable pulse width
would be 131,070 microseconds.
Going the other direction and running with a 32.768Khz oscillator is
problematic. It may be desirable to attempt this for reduced power
consumption reasons and it will work to some extent. The SERIN and
SEROUT commands will be unusable and the Watchdog Timer may
PicBasic Compiler
74
cause the program to restart periodically. Experiment to find out if your
particular application is possible at this clock speed. It doesn’t hurt to
try.
The time dependent instructions are I2CIN, I2COUT, PAUSE, POT,
PULSIN, PULSOUT, PWM, SERIN, SEROUT, SLEEP, and SOUND. It is
possible to modify the actual library routines to maintain proper
instruction timing at clock speeds other than 4MHz, although with some
functions a fair bit of effort may be required.
7.2. Assembly Language
Assembly language routines can be a useful adjunct to a PicBasic
Compiler program. While in general most tasks can be done completely
in PicBasic, there are times when it might be necessary to do a
particular task faster, or using a smaller amount of code space, or just
differently than the compiler does it. At those times it is useful to have
the capabilities of an in-line assembler.
It can be beneficial to write most of a program quickly using the PicBasic
language and then sprinkle in a few lines of assembly code to increase
the functionality. This additional code may be inserted directly into the
PicBasic program, added to the main library, or included as another file.
7.2.1. Programming in Assembly Language
PBC programs may contain in-line assembly; one or more lines of
assembly code preceded by the ASM keyword and ended by the ENDASM
keyword. Both keywords appear on their lines alone.
The lines of assembly are copied verbatim to the assembly output file.
This allows the PBC program to use all of the facilities of PM, the
PICmicro Macro Assembler. This also, however, requires that the
programmer have some familiarity with the PBC libraries. PBC’s
notational conventions are similar to other commercial compilers and
should come as no shock to programmers experienced enough to
attempt in-line assembly.
All symbol names defined in a PBC program are similarly defined in
assembly, but with the name preceded with an underscore ( _ ). This
allows access to user variables, constants, and even labeled locations,
PicBasic Compiler
75
in assembly. Similarly, system variable (such as W0) names are also
preceded by underscores (such as _W0).
Thus, any name defined in assembly starting with an underscore has
the possibility of conflicting with a PBC generated symbol. If conflict is
avoided, can these underscored assembly values be accessed from
PBC? No. Remember, the underscored names generated by PBC are
only shadows of the actual information defined in the compiler. Since in-
line assembly is copied directly to the output file and not processed by
the compiler, the compiler not only lacks any type or value information
about assembly symbols, it is completely unaware that they exist. If
variables are to be shared between assembly and PBC, either use
predefined system variables or define the variables in PBC.
Just as underscored symbols have possible conflicts, so do symbols not
starting with underscores. The problem is internal library variables.
Luckily, most library variables contain an '@' or make reference to one of
the working registers (such as R0). Avoiding such names should be
reduce problems. If you should have a name collision, the compiler will
report the duplicate definitions as an error.
7.2.2. Assembly Language Examples
To write a byte to PORTA in PicBasic you could simply:
Poke 5,B0 ‘Send whatever is in variable
B0 to PortA (register 5)
But for code speed and size reasons you might write:
asm ‘The following code is written
in assembler
clrb RP0 ;Make sure we’re pointing to
the proper register page
mov 5,_B0 ;Send whatever is in variable
B0 to PortA (register 5)
endasm
This code takes 3 words of code space and runs in 3 microseconds
(with a 4MHz oscillator) as opposed to the PicBasic statement which
takes up a little more code space but takes several microseconds longer
to execute. (The clrb RP0 isn’t strictly necessary. The compiler
PicBasic Compiler
76
normally clears that bit before returning from a library routine. But better
safe...)
Note that in the assembly example above the variable B0 was preceded
by an underscore ( _ ). By convention, PicBasic labels and variables
that are accessed in assembler must be preceded by an underscore.
This is to keep lower level label assignments from interfering with
PicBasic labels and variables.
You might also note that the comment delimiter changed from the single
quote (‘) in PicBasic to the semi-colon (;) after the ASM command.
Unfortunately, each language’s syntax has a different requirement for
this character.
Larger assembly language routines may be included in your program or
in a separate file. If a routine is used by only one particular PicBasic
program, it would make sense to include the assembler code within the
PicBasic file. This routine can then be accessed using the CALL
command.
‘PicBasic example program with embedded assembly
language subroutines
loop: For B0 = 0 To 255 ‘Count up B0 in a
For..Next loop
Call shiftout ‘Call assembly routine
to shift B0 out PortA
Next B0 ‘Do next count
Call shiftin ‘Shift in a byte from
PortA to B0
Serout 0,N2400,(B0) ‘Send the byte out
serially on Pin0
Goto loop ‘Go do it all again
End
asm ‘Assembly language code
follows
_shiftout mov T0,#8 ;Setup temporary variable with
bit count
soloop rr _B0 ;Get low order bit of data
byte to carry
PicBasic Compiler
77
jnc solow ;If no carry then data bit
should be low
setb PortA.0 ;Otherwise set data bit
high
skip ;Skip over next instruction
solow clrb PortA.0 ;Set data bit low
setb PortA.1 ;Toggle clock high
clrb PortA.1 ;Toggle clock back low
djnz T0,soloop ;Loop to do all 8 bits
return ;Go back to main program when
done
_shiftin mov T0,#8 ;Setup temporary variable with
bit count
siloop setb PortA.1 ;Toggle clock high
clrb PortA.1 ;Toggle clock back low
clc ;Preset carry to off
snb PortA.0 ;If data bit is low then
skip over next
instruction
stc ;Else set carry to on
rl _B0 ;Roll bit into result byte B0
djnz T0,siloop ;Loop to do all 8 bits
goto done ;Exit through library
routine Done
endasm ‘End of assembly language code
Don’t forget to put an END or GOTO or some other mechanism at the end
of your PicBasic code to keep the processor from “falling into” your
assembler subroutines upon execution.
Also note that the function terminates by jumping to DONE rather than
simply returning. Returning would be fine, but the DONE function
performs other housecleaning needed by PBC (resetting the RP0 bit and
hitting the Watchdog). W is not affected by done.
If the assembler routine is destined to be used by several PicBasic
programs, it makes sense to put it into its own separate text file and
simply tell the assembler to INCLUDE this file.
‘PicBasic example program with assembler code included
in a separate file
PicBasic Compiler
78
loop: For B0 = 0 To 255 ‘Count up B0 in a For..Next
loop
Call shiftout ‘Call assembly routine to
shift B0 out PortA
Next B0 ‘Do next count
Call shiftin ‘Shift in a byte from PortA to
B0
Serout 0,N2400,(B0) ‘Send the byte out
serially on Pin0
Goto loop ‘Go do it all again
End
asm ‘Assembly language code
follows
include “shift.inc” ;Assembly code
will be inserted
here
endasm
The third option for using assembly code with a PicBasic program is to
add the code right into the PBH.INC or PBL.INC files. These files are
automatically included by the compiler.
This is the avenue most fraught with danger. These files are built in a
particular manner and caution should be exercised before changing
them. Also, as updates to the compiler are released, these files will
change and your routines would need to follow the changes. If this is
the path of choice, be sure to make copies of the original files and only
work from those copies.
7.2.3. Placement of In-line Assembly
PBC statements execute in order of appearance in the source. The first
executable line that appears is where the program starts execution. That
statement literally appears in memory right behind the controller’s
startup code. Similarly, the END implicit at the end of every PBC
program is accomplished by having the code for the END function
appear first and unconditionally in the library. It appears in memory
directly behind the user's last statements. This method saves two
unneeded jumps and everything normally works out all right.
PicBasic Compiler
79
The tendency of programmers is to place their own library functions
written using the inline assembler either before or after their code. In
light of the above explanation, this could create some obvious problems.
If they appear early in the program, the assembly routines execute prior
to any PBC instructions (some programmers will invariably exploit this
feature). If they appear at the tail of the program, execution which "falls
off the end" of the PBC statements may mysteriously find themselves
unintentionally executing assembly routines.
What should you do? Simple. Unlike a hosted system (such as the PC
or the Mac), there is little reason for an embedded system to terminate.
Thus, place your assembly routines after your PBC code. If you need to
terminate your program, explicitly place an END statement at the end of
your code rather then relying on the implicit END.
7.2.4. The PICmicro Macro Assembler
The PICmicro Macro Assembler (PM) included with the PicBasic
Compiler can use “8051 style” mnemonics or the Microchip mnemonics.
The included header files which define the register and bit names,
however, are in the 8051 form. This format includes the register name
and bit name into one symbol. This makes it quicker and easier to write
the code but also makes it somewhat incompatible with Microchip code
that may be scattered through their data books.
It is a fairly simple matter to convert these symbols as they are typed in
or use your text editor’s or word processor’s search and replace function
to change them.
For example, if the Microchip code says:
bsf status,rp0 ;set bit rp0
the equivalent PM code would be:
bsf rp0 ;set bit rp0
The reason behind this change is that the symbol RP0 is defined to
already include the information that it is in the Status register. See the
PM include files, P16F8x.INC for example, for a complete list of these
symbol definitions for each PICmicro.
PicBasic Compiler
80
The assembler instruction set is listed in the appendix of this document.
For complete information on the PICmicro Macro Assembler, see the
PM.TXT file on disk.
7.3. Interrupts
Interrupts can be a scary and useful way to make your program really
difficult to debug.
Interrupts are triggered by hardware events, either an I/O pin changing
state or a timer timing out and so forth. If enabled (which by default they
aren’t), an interrupt causes the processor to stop whatever it is doing
and jump to a specific routine in the PICmicro called an interrupt
handler.
Interrupts are not for the faint of heart. They can be very tricky to
implement properly, but at the same time they can provide very useful
functions. For example, an interrupt could be used to buffer serial input
data behind the scenes while the main PicBasic program is off doing
something else. (This particular usage would require a PICmicro with a
hardware serial port.)
The PicBasic Compiler does not directly support interrupts, but that does
not mean they cannot be used. The PicBasic library routines are not
reentrant. This means that you cannot execute PicBasic statements
from within an interrupt handler - the interrupt handler must be written in
assembly language. This statement alone should be enough to strike
fear into the heart of the BASIC programmer.
However, if you just gotta do it, here are some hints on how to go about
it.
When an interrupt occurs, the PICmicro stores the address of the next
instruction it was supposed to execute on the stack and jumps to
location 4. The first thing this means is that you need an extra location
on the PICmicro stack, which is only 8 deep to begin with.
The PicBasic library routines can use up to 4 stack locations
themselves. The remaining 4 are reserved for CALLs and nested
BASIC GOSUBs. You must make sure that your GOSUBs are only nested
3 deep at most with no CALLs within them in order to have a stack
location available for the return address. If your interrupt handler uses
PicBasic Compiler
81
the stack (by doing a Call itself for example), you’ll need to have
additional stack space available.
Once you have dealt with the stack issues, it gets even trickier. Since
you have no idea of what the processor was doing when it was
interrupted, you have no idea of the state of the W register, the Status
flags, PCLATH or even what register page you are pointing to. If you
need to alter any of these, and you probably will, you must save the
current values so that you can restore them before allowing the
processor to go back to what it was doing before it was so rudely
interrupted. This is called saving and restoring the processor context.
If the processor context is not left exactly the way you found it, all kinds
of subtle bugs and even major system crashes can and will occur.
This of course means that you cannot even safely use the compilers
internal variables for storing the processor context. You cannot tell
which variables are in use by the library routines at any given time.
We have reserved three internal variables strictly for use by an interrupt
handler: I0, I1, and I2 (Only I0 has a real RAM location on a
PIC16C84. Use a PICmicro with more RAM such as a PIC16F84 for
access to the additional locations.) If you require more than these
variables, you can reserve as many of the user variables (B0, B1, ...) as
you like by simply not using them in your PicBasic program. You may
use these locations to store W, the Status register, or any other register
that may need to be altered by the interrupt handler.
The interrupt routine should be as short and fast as you can possibly
make it. If it takes too long to execute, the Watchdog Timer could
timeout and really make a mess of things. Perhaps the most useful
function would be to simply set a PicBasic variable to a particular value
when an interrupt occurs. When the PicBasic program sees this value,
it knows an interrupt has occurred and it can take the appropriate
actions.
The interrupt handler itself may be placed in the file PBH.INC in the INC
subdirectory. Near the end of the file is the label Start. This is where
the PICmicro will start executing code on reset, location 0. A few lines
down is a section of code that has been commented out. If this code is
uncommented, it will enable you to insert your interrupt handler at
location 4. Place your assembly language interrupt handler routine after
PicBasic Compiler
82
the ORG 4. The routine should end with an RETI instruction to return
from the interrupt and allow the processor to pick up where it left off in
your PicBasic program.
From this point you are on your own. If you follow the above
suggestions, your interrupt routine should be able to coexist peacefully
with your PicBasic program.
Definitely, definitely, definitely refer to the Microchip PICmicro data
books for additional information on how to use interrupts. They give
examples of storing processor context as well as all the necessary
information to enable a particular interrupt. This data is invaluable to
your success.
7.4. Life After 2K
When a PicBasic program grows longer than 2K (which is a pretty big
program), problems will occur. PICmicro instructions such as Call and
Goto only have enough bits within them to address 2K of program
space. To get to code outside the 2K boundary, the PCLATH register
must be set before each Call or Goto.
In the interest of minimizing program size, the PicBasic Compiler makes
no effort to address this problem. The 2K boundary presents a problem
to PICmicro programming in any language; assembly, C, or PicBasic.
If it is necessary for a program to be longer than 2K, the .ASM file the
compiler generates can be “fixed-up” and then assembled after setting
PCLATH before and after the appropriate instructions. It would probably
be best to use memory beyond 2K for large table storage to keep “fix-
ups” to a minimum.
See the Microchip PICmicro data books for more information on
PCLATH and address sizes.
PicBasic Compiler
83
8. Compiler / Stamp Differences
Every effort has been made to assure that programs compiled by PBC
execute as they would on a BASIC Stamp I. Most programs will compile
and execute without error.
But, just as with all system which promise "compatibility", there are
always some slight differences. Some are due to improvements in code
executed directly on the PICmicro rather than via the Stamp chip set.
Others are the result of the fact that the BASIC Stamp is a closed
system and its internal operations are unknown. While the results tested
well, we can never be 100% sure.
The following sections discuss the implementation details of PBC
programs that might present problems. It is hoped that if you do
encounter problems, these discussions will help illuminate the
differences and possible solutions.
8.1. Execution Speed
The largest potential problem shared by both library routines and user
code is speed. Without the overhead of reading instructions from the
EEPROM, many PBC instructions (such as GOTO and GOSUB) execute
hundreds of times faster than their BASIC Stamp equivalents. While in
many cases this is a benefit, programs whose timing has been
developed empirically may experience problems.
The solution is simple - good programs don't rely on statement timing.
Whenever possible, a program should use handshaking and other non-
temporal synchronization methods. If delays are needed, statements
specifically generating delays (PAUSE, NAP or SLEEP) should be used.
8.2. Digital I/O
Unlike the BASIC Stamp, PBC programs operate directly on the PORT
and TRIS registers. While this has speed and RAM/ROM size
advantages, there is one potential drawback.
Some of the I/O commands (TOGGLE and PULSOUT) perform read-
modify-write operations directly on the PORT register. If two such
operations are performed too close together and the output is driving an
inductive or capacitive load, it is possible the operation will fail.
PicBasic Compiler
84
Suppose, for example, that a speaker is driven though a 10uF cap (just
as with the SOUND command). Also suppose the pin is initially low and
the programmer is attempting to generate a pulse using TOGGLE
statements. The first command reads the pin's low level and outputs its
complement. The output driver (which is now high) begins to charge the
cap. If the second operation is performed too quickly, it still reads the
pin's level as low, even though the output driver is high. As such, the
second operation will also drive the pin high.
In practice, this is not much of a problem. And those commands
designed for these types of interfacing (SOUND and POT, for example)
have built-in protection. This problem is not specific to PBC programs.
This is a common problem for PICmicro (and other microcontroller)
programs and is one of the realities of programming hardware directly.
8.3. Missing PC Interface
Since PBC generated programs run directly on a PICmicro, there is no
need for the Stamp's PC interface pins (PCO and PCI). The lack of a PC
interface does introduce some differences.
Without a PC, there is no place to send debugging information. Thus,
while PBC parses PBASIC's DEBUG commands, it doesn't generate
code.
Without the PC to wake the PICmicro from the END statement, it
remains in low power mode until /MCLR is lowered or power is cycled.
8.4. BUTTON
PBC's BUTTON command requires the programmer to specify an 8-bit
variable to store the current repeat count. The BASIC Stamp will allow
the use of any type of variable. Word variables work fine, although they
are wasteful. On the Stamp, programs using bit variables for the
BUTTON command will compile and run, but the command will not
behave correctly. PBC's BUTTON command will also work correctly with
word variables. It does, however, generate a compiler error when an
attempt is made to use BUTTON with a bit variable.
The faster execution of PBC programs may be a problem for the
BUTTON command. The BUTTON command samples the input only once
PicBasic Compiler
85
per execution. Debouncing is achieved by the delay introduced by other
Stamp overhead (such as fetching instructions from EEPROM). Thus, a
BUTTON command which is executed too frequently might not provide as
good a "debounce" in PBC programs as it does on the BASIC Stamp.
8.5. EEPROM, READ and WRITE
The BASIC Stamp allows EEPROM not used for program storage to
store non-volatile data. Since PBC programs execute directly from the
PICmicro's ROM space, EEPROM storage must be implemented in
some other manner.
The PIC16C84, 16CF62x, 8x and 87x devices have from 64 to 255
bytes of on-chip data EEPROM. PBC programs may use this for
EEPROM operations and fully supports PBASIC's EEPROM, READ and
WRITE commands. The PIC16F87x devices do not return the device
size when location 255 is read.
To access off-chip non-volatile data storage, the I2CIN and I2COUT
instructions have been added. These instructions allow 2-wire
communications with serial EEPROMs like Microchip Technology’s
24LC01B.
8.6. GOSUB/RETURN
The Stamp implements subroutines via the GOSUB and RETURN
statements. User variable W6 is used by the Stamp as a four nibble
stack. Thus, PBASIC programs may have up to 16 GOSUBs and
subroutines can be nested up to four levels deep.
The 14-bit core PICmicros have Call and Return instructions as well as
eight level stacks. PBC programs make use of these instructions and
use four levels of this stack, with the other four levels being reserved for
library routines. Thus, W6 is still available, subroutines may still be
nested up to four levels deep and the number of GOSUBs is limited only
by the PICmicro's code space.
8.7. RANDOM
PBC's RANDOM statement takes any word variable as its parameter. The
PBC library routine takes the address of the 16-bit word to randomize as
PicBasic Compiler
86
its parameter. Since PBC doesn't implement the PORT register as a true
16-bit memory location, the statement RANDOM PORT will produce a
compilation error.
8.8. SERIN/SEROUT
SERIN and SEROUT have been altered to run up to 9600 baud from the
previous limit of 2400 baud. This has been accomplished by replacing
the little used rate of 600 baud with 9600 baud. Modes of T9600,
N9600, OT9600 and ON9600 may now be used.
600 baud is no longer available and will cause a compilation error if an
attempt is made to use it.
8.9. Low Power Instructions
When the Watchdog Timer time-out wakes a PICmicro from sleep
mode, execution resumes without disturbing the state of the I/O pins.
For unknown reasons, when the BASIC Stamp resumes execution after
a low power instruction (NAP or SLEEP), the I/O pins are disturbed for
approximately 18 mSec. PBC programs make use of the PICmicro's I/O
coherency. The NAP instruction does not disturb the I/O pins.
Similarly, the Stamp's SLEEP instruction disturbs the I/O pins every
WDT time-out period, approximately every 2.3 seconds. PBC's SLEEP
instructions only disturbs the I/O pins once every 10 minutes. This is
done while recalibrating the period of the WDT.
8.10. SLEEP
The Stamp's documentation indicates its SLEEP command is ~99.8%
accurate. This may be overly optimistic. First, the granularity of the
SLEEP command is determined by the Watchdog Timer period, which is
typically 2.3 seconds. This introduces an average error of about 1
second. Even without this granularity, SLEEP is only as accurate as the
PICmicro's system clock. In the BS1, the oscillator is a resonator, whose
accuracy is +/-1%.
Ignoring these effects, there is still the larger problem of variability in the
PICmicro's Watchdog Timer. The WDT is driven by an R/C oscillator
and the period varies greatly with temperature.
PicBasic Compiler
87
To eliminate this error, the WDT is calibrated in terms of the system
clocks. This is done by counting system clocks while waiting for the
WDT to time-out. This calibrated period is then used to decrement the
desired sleep period. This keeps SLEEP to within the accuracy of the
system clock (ignoring the granularity of the WDT).
PBC's SLEEP command performs this recalibration every 257 cycles or
about once every 10 minutes. It recalibrates for a full WDT period (about
2.3 seconds). This results in the PICmicro being active about 0.38% of
the time during the SLEEP command. For the PIC16F84 at 4MHz with
the WDT enabled, Microchip specifies a typical operating current of
1.8mA and a power down current of 40uA. Using these figures, PBC's
SLEEP draws approximately 47uA.
This is more than the current levels claimed by the BASIC Stamp. This
is due to the fact that the PIC16C5x family has a lower power-down
current consumption than members of the PIC16Cxxx family.
With all the above said, it has been determined that a calibrated SLEEP
command may not work properly on all PICmicros. During SLEEP
calibration, the PICmicro is reset. Different devices respond in different
ways to this reset. Upon reset, many registers may be altered. Notably
the TRIS registers set all the PORT pins to inputs. The TRIS state for
PORTB is automatically saved and restored by the SLEEP routine. Any
other PORT directions must be reset by the user program after SLEEP.
Other registers may also be affected. See the data sheets for a
particular part for this information.
To get around potential problems, an uncalibrated version of SLEEP has
been created. This version does not cause a device reset so it has no
effect on any of the internal registers. All the registers, including PORT
direction, remain unchanged during and after a SLEEP instruction.
However, actual SLEEP times will no longer be as accurate and will vary
dependent on device particulars and temperature.
PicBasic Compiler
88
The uncalibrated version of SLEEP is now the default. To enable the
previous, calibrated version of SLEEP add the following lines to a PBC
program:
asm
SLEEPCAL = 1
endasm
PicBasic Compiler
89
Appendix A
Summary of Microchip Assembly Instruction Set
ADDLW k
ADDWF f,d
ANDLW k
ANDWF f,d
BCF f,b
BSF f,b
BTFSC f,b
BTFSS f,b
CALL k
CLRF f
CLRW
CLRWDT
COMF f,d
DECF f,d
DECFSZ f,d
GOTO k
INCF f,d
INCFSZ f,d
IORLW k
IORWF f,d
MOVF f,d
MOVLW k
MOVWF f
NOP
RETFIE
RETLW k
RETURN
RLF f,d
RRF f,d
SLEEP
SUBLW k
SUBWF f,d
SWAPF f,d
XORLW k
XORWF f,d
b - bit address
d - destination; 0 = w, 1 = f
f - register file address
k - literal constant
PicBasic Compiler
90
PicBasic Compiler
91
Appendix B
Contact Information
Technical support and sales may be reached at:
microEngineering Labs, Inc.
Box 7532
Colorado Springs CO 80933-7532
(719) 520-5323
(719) 520-1867 fax
http://www.melabs.com
email:support@melabs.com
PICmicro data sheets, CD-ROMs and literature may be obtained from:
Microchip Technology Inc.
2355 W. Chandler Blvd.
Chandler AZ 85224-6199
(602) 786-7200
(602) 899-9210 fax
http://www.microchip.com
email:literature@microchip.com
READ THE FOLLOWING TERMS AND CONDITIONS CAREFULLY
BEFORE OPENING THIS PACKAGE.
microEngineering Labs, Inc. ("the Company") is willing to license the
enclosed software to the purchaser of the software ("Licensee") only on
the condition that Licensee accepts all of the terms and conditions set
forth below. By opening this sealed package, Licensee is agreeing to
be bound by these terms and conditions.
Disclaimer of Liability
THE COMPANY DISCLAIMS ALL WARRANTIES, EXPRESS OR
IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE AND THE
IMPLIED WARRANTY OF MERCHANTABILITY. IN NO EVENT
SHALL THE COMPANY OR ITS EMPLOYEES, AGENTS, SUPPLIERS
OR CONTRACTORS BE LIABLE FOR ANY INCIDENTAL, INDIRECT,
SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN
CONNECTION WITH LICENSE GRANTED UNDER THIS
AGREEMENT, INCLUDING WITHOUT LIMITATION, LOST PROFITS,
DOWNTIME, GOODWILL, DAMAGE TO OR REPLACEMENT OF
EQUIPMENT OR PROPERTY, OR ANY COSTS FOR RECOVERING,
REPROGRAMMING OR REPRODUCING ANY DATA USED WITH
THE COMPANY'S PRODUCTS.
Software License
In consideration of Licensee's payment of the license fee, which is part
of the price Licensee paid for this product, and Licensee's agreement to
abide by the terms and conditions on this page, the Company grants
Licensee a nonexclusive right to use and display the copy of the
enclosed software on a single computer at a single location. Licensee
owns only the enclosed disk on which the software is recorded or fixed,
and the Company retains all right, title and ownership (including the
copyright) to the software recorded on the original disk copy and all
subsequent copies of the software. Licensee may not network the
software or otherwise use it on more than one computer terminal at the
same time. Copies may only be made for archival or backup purposes.
The enclosed software is licensed only to the Licensee and may not be
transferred to anyone else, nor may copies be given to anyone else.
Any violation of the terms and conditions of this software license shall
result in the immediate termination of the license.

COPYRIGHT NOTICE Copyright ©2000 microEngineering Labs, Inc. All rights reserved. This manual describes the use and operation of the PicBasic Compiler from microEngineering Labs, Inc. Use of the PicBasic Compiler without first obtaining a license is a violation of law. To obtain a license, along with the latest version of the product and documentation, contact microEngineering Labs, Inc. Publication and redistribution of this manual over the Internet or in any other medium without prior written consent is expressly forbidden. In all cases this copyright notice must remain intact and unchanged. microEngineering Labs, Inc. Box 7532 Colorado Springs CO 80933-7532 (719) 520-5323 (719) 520-1867 fax email: support@melabs.com web: www.melabs.com

TRADEMARKS EPIC and PicBasic are trademarks of microEngineering Labs, Inc. BASIC Stamp and PBASIC are trademarks of Parallax, Inc. PICmicro is a registered trademark of Microchip Technology Inc.

11/00

PicBasic Compiler

microEngineering Labs, Inc.

.

. . . . PicBasic Programming . . . .3. . . . 5 2. . . . . . . . Option -S . . . . . . . . . . . Usage . . . . . . . . . . . . . . . . . . . . 3. . . . . .2. . . . . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . . . . .2. 4. . . . . . . .7. . . . . . . . . . . . . . 4. . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . Program That PICmicro . . . . . . . . . . . . . 4. . . . . . . . I’ve Got Troubles .8. . . . . . . . . . . . Compiler Basics . . . . Symbols . . . . . . . . . 4 2. 3 2. . . . . . . . Option -L . . 1 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . The Pins . . . . . . . . . . . . . . .8. . 13 3. . . . . .8. . . . . . . . . .2. . . . . . . . . .2. . .8. . . . . . . . . String Constants . . . . . . GOTO . . . .8. Comments . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . 12 2. . . . . . . . . . . 11 2. . . . Comments . . . . . . . . . . . . . . . . . . . . 3. . . . . . . . . . . . . . . . . . 2 2. . . . . . . It’s Alive . . . . . .3.2. . Numeric Constants . . . . . . . 4. . . . .4.3. . . . . . . . .1. . . 3 2. . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . .2. . . . .PicBasic Compiler TABLE OF CONTENTS 1. .2. . . . . . . . . . . . .8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Option -Q .5. . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . Software Installation . . . . . . . .4. . . . . . . . . . 11 2. . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . 4. . . . . Coding Style . 7 2. . . . . Identifiers . . . . 4. . . Multi-statement Lines . .3. . . . . . . . . . . Options . . . Getting Started . . . . . . . . .2. . . . . . .2. . . . . . . . . . . The PICmicros . . . . . . . . . . . 3. . . . . . Symbols . . Option -D . . . . . 8 2. . . . . . . . . . . . . . . . . . . . . . . . . Option -C . . . . . . . . . . . . . . . . . .7. . . 3.2. . . . . .1. . . . . . . . 3. . . . . Variables . . . . . . . .5. . . 3. . . Option -P## .1. . . . . . . . . . . . . . . .6. . 3. .1. .4. . . . . . 13 2. . . . . . . . . . . Labels . . 3. . . . . 4. . . . . . . . . . . . . . . . . . 15 15 16 16 16 17 17 17 18 18 19 19 19 19 20 20 20 23 23 i .6. . . . . . . . . . . . . . . . . . . . . . 3. . . . . . . . About This Manual . Command Line Options . . . . . . . 5 2. . . . . . . . Line Labels . . . . . 4. . . . . . . . . . . . . . . . . Option -OB . . . . . . . . . . . . . . . . 9 2. . . .2. . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . .13. . . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . IF. . . 5. . . 5. . . . . . . . . . . . . . . . . . . . . . . . .10. . . . . 5. .PicBasic Compiler 5. . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . .28. . . . . . . . RETURN . . . . . . . . . . . . . . .1. . . . . . . . . . . .24. . 5. . . . 25 26 27 28 29 30 31 32 33 34 35 36 39 40 41 42 43 43 44 45 46 47 48 49 49 52 53 54 55 56 57 58 59 60 60 62 65 66 67 68 ii . . . . . . . . . . . 5. . .15. . . . . . .2. . 5. . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6.. . . . . . . . . . . . . . . .11. . . . . . . . LOW . . . . 5. . . . . . . . . . . . . . . 5. . .16. . END . REVERSE . . . . . . . . CALL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36. . . . . . . . . . . .22. . . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . DEBUG . . READ . . . . . . . . . . .21. . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.31. . . . . . . . . . . . . .5. 5. . . . . . . . . . . FOR. . . HIGH . . . . . . . . . . . . PULSIN . . .30. . . . . . . . . . . . . . . . . . . . EEPROM . . . . . . . . 5. . . . . . BUTTON . . . . . . . PWM . . . . . . . .14. . . . . . . . . . . . . . . . .20. . . . . . . WRITE . .37. . . . . . . . . . . . . 5. . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . 5. . . . . . . . . . . . RANDOM . . . . . . . . . . . . . . . . . .23.THEN . . . . . . . . 5. . . . . . . OUTPUT . . . . . . . . {LET} . . . . . . . . . . 5.15.3. . . . . . . . . . .15. . . . . . . . . . . . . . . . . .26. . . . . 5. . .32. . . . . . . . . I2COUT . . . . . . . PAUSE . . . . . . . . . . . . . . Bitwise NOT Operators . . . . . . . . . . . SEROUT . . . . . . . . . . . . . . . . . . . . . BRANCH . 5. . . . . . .19. . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . . . NAP . . . . . . . . . . . . . . . . 5. . . . . . PULSOUT . . . . . . . . . . . . . 5. .18. . . . . . . . . . . . . 5. . . . . SLEEP . . 5. . . . . . . . . . . . SOUND . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I2CIN . . . GOTO . . . . .17. . . . . . . . POT . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . 5. SERIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . 5. . . . . . . . . . . . . . . . . PicBasic Pro Statement Reference . . . . . . . . . . .33. . .27. . . . . . . . . . . . . 5. . . . . . . . . . . PEEK . . . . 5. . . . . . . . . . . 5.8. . . . . . . . . 5.12. . . . . . . . . .NEXT . . . . . . .35. . . . 5. . . . . . . .29.25. . . . . . . . . . . . . . .34. . . . . 5. . . . . . . . . . . . INPUT . . . . . . . 5. . . . . . . . . . . . . . . . . . . POKE . . . Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TOGGLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . GOSUB . . . . . . . . . . . . . . . . . . . . . . LOOKDOWN . . 5. . LOOKUP . . . . . . . 5. . . 5. . . . . . . . . . .

. .2. . . . . . 69 69 70 71 71 73 73 74 74 75 78 79 80 82 83 83 83 84 84 85 85 85 86 86 86 Appendix A Summary of Microchip Assembly Instruction Set .1. . . 8. .INC . . .1. . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . 8. .4. .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . .10. . Placement of In-line Assembly . . . . . . . . .PicBasic Compiler 6. . . . . . . . . . . 8. . . .INC) . . . . . . Life After 2K . . GOSUB/RETURN . . . . . . . . . . . . . 8. . PBC Generated Code . . . 8. . . 7. . PBL. .3. . . . . . . . 7. . . . . 8. . . Interrupts . . . . .2. . . . . . . The PICmicro Macro Assembler . . . . . . . . . .3. . . . . . . . . . . . . EEPROM. . . . . . Programming in Assembly Language 7.INC . . . .4. .4. . . 89 Appendix B Contact Information . . . . . .2. 7. . . . . Compiler / Stamp Differences . . . . . . . . . . . . . . . . . . . . . . . . Digital I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Execution Speed . SLEEP . . 8. . . . .3. BUTTON . . . . . .3. . . . . . . . . . . . . Structure of a Compiled Program . . . . . . . .2. . Missing PC Interface . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . SERIN/SEROUT . . . . . READ and WRITE . . . . . . . . . . . . . . . .2. 8. . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . PBH. . . . . . . . . . . . . . . 7. . . 8. . . . . Other PicBasic Considerations . . . 91 iii . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Assembly Language . . . . . . Low Power Instructions . . . Target (PICmicro) Specific Header (B##. . . . . 7. . .7. . . . . . . 6. How Fast is Fast Enough? . RANDOM . . . . . . . . . 8. . . . . 7. . . . 6. . . . .2. . . . . . . . Assembly Language Examples . . .5. . . 8. . . . . . . . . . . . . . . . . .1. . .8. . . .9. . . . 7. . 6. .

PicBasic Compiler iv .

volt power supply. PBC programs execute much faster than equivalent programs on a BASIC Stamp.7K pull-up resistor tied to the /MCLR pin and a suitable 5. this lower cost could turn what was just a good idea into a viable and competitive product. Only a minimum of other parts are necessary: 2 22pf capacitors for the 4MHz crystal. 1 . per product? PBC allows programs to be compiled directly into PICmicros costing $2 to $10.e. In fact. Introduction The PicBasic Compiler (or PBC) makes it quick and easy for you to program Microchip Technology’s powerful PICmicro microcontrollers. the investment in the PicBasic Compiler and a PICmicro programmer could easily pay for itself after only a few projects. Maximum program length is dependent upon how many different instructions are used (i. Better yet. the number of different library routines that must be loaded) and the code space available in the particular PICmicro. PICmicro Hardware PBC defaults to create files that run on a PIC16F84 (or PIC16F84A) clocked at 4MHz. The English-like BASIC language is much easier to read and write than the quirky Microchip assembly language. With this kind of savings. Program Size There is no fixed limit on the number of statements a program can have. some instructions execute hundreds of times faster! Cost Why pay $34 per project or. a 4. worse yet. PBC also allows programs written for the original BASIC Stamp I to be compiled for direct execution on members of the PICmicro family of microcontrollers. Why would you want to do this? Speed Since PBC programs execute directly from the code space of the PICmicro rather than being fetched from a serial EEPROM.PicBasic Compiler 1.

The next section of this manual covers installing the PicBasic Compiler and writing your first program. BASIC is designed as an easy-to-use language and there are additional example programs on the disk and web site that can help get you started. Curly brackets. Or just jump right in. If you are not familiar with BASIC programming. It describes the PicBasic Compiler instruction set and provides examples on how to use it. Following is a section that describes different options for compiling programs. The 16C5x only provides a two level stack.PicBasic Compiler Many PICmicros other than the 16F84 may be used with the PicBasic Compiler. The PicBasic Compiler requires the 8 level stack provided by the newer PICmicros.1.all the inner workings of the compiler. {}. The remainder of the manual provides information for advanced programmers . a description of the command and some examples. About This Manual This manual cannot be a full treatise on the BASIC language. you should acquire a book on the topic. 1. The reference section shows each command prototype. Programming basics are covered next. 2 . the PicBasic Compiler will not work with the older 16C5x series PICmicros. followed by a reference section listing each PicBasic command in detail. indicate optional parameters. However.

73(AB). 620(A). 84. 66. 716. Compiler Basics 2. 711. There are many. 622(A). 870. 924. some pin compatible with the ‘5x series.ME file for the latest chip support list. 77. the foremost of which being the 8-level stack. the list includes the PIC12C671. These PICmicros are based on the older 12-bit core rather than the more current 14-bit core. 873. 63(A). 771.PicBasic Compiler 2. There are some PICmicros that will not work with the PicBasic Compiler. 558. 774. PIC14C000. See the READ. 620(A). 642. the PIC16C554. 874. the PICmicro can be instantly erased and then reprogrammed again and again. 770. notably the PIC16C5x series including the PIC16C54 and PIC16C58. 923.1. The PicBasic Compiler requires some of the features only available with the 14-bit core. 876 and 877. 712. 872. 558. These 18-pin microcontrollers uses flash technology to allow rapid erasing and reprogramming to speed program debugging. This data area can be accessed simply by using the PicBasic Compiler’s READ 3 . PIC16F627. 74(AB). For direct replacement of a PIC16C54. 84(A). many PICmicros. 621(A) and 622(A) work well with the compiler and are very nearly the same price. 773. Other PICmicros in the 12C67x. that may be used with the PicBasic Compiler. The PICmicros The PicBasic Compiler produces code that may be programmed into a wide variety of PICmicro microcontrollers having from 8 to 40 or more pins and various on-chip features including A/D converters and hardware timers and serial ports. 14C000 and 16Cxxx series are either onetime programmable (OTP) or have a quartz window in the top (JW) to allow erasure by exposure to ultraviolet light for several minutes. 710. 65(AB). 83. 871. 715. the PIC16F84 and PIC16F628 are the current PICmicros of choice. 717. The PIC16F84 also contains 64 bytes (128 bytes for the PIC16F628) of non-volatile data EEPROM memory that can be used to store program data and other parameters even when the power is turned off. 72(A). 56 or 58. 71. 62(AB). 628. 61. With the click of the mouse in the programming software. 67. 621(A). Currently. 64(A).* For general purpose PICmicro development using the PicBasic Compiler. 662. 76. 672. PIC16C554.

PicBasic Compiler

and WRITE commands. (Program code is always permanently stored in the PICmicro’s code space whether the power is on or off.) By using the ‘F84 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. While many PICmicro features will be discussed in this manual, for full PICmicro information it is necessary to obtain the appropriate PICmicro Data Sheets or the CD-ROM from Microchip Technology. Refer to Appendix B for contact information.
*Selling price is dictated by Microchip Technology Inc. and its distributors.

2.2. The Pins
Pins used by PicBasic Compiler commands are numbered 0 - 7 as with the BASIC Stamp I. These pins are mapped onto PICmicro hardware port B such that Pin0 refers to PORTB pin 0 or simply PORTB.0 (or RB0), Pin1 refers to PORTB.1 and so forth up to Pin7 referring PORTB.7. The pin number, 0 - 7, has nothing to do with the physical pin number of a PICmicro. Depending on the particular PICmicro, Pin0 could be physical pin 6, 21 or 33, but in every case it is PORTB.0. PicBasic instructions that reference a pin number such as HIGH or LOW want only the pin number 0 - 7, eg. High 3 (set Pin3 high). If High Pin3 is entered instead, the results are unexpected. Always use only the number or a SYMBOL that equates to a number with pin manipulation instructions. On the other hand, if the current state of a pin is required, to read a switch for example, the whole pin name would be used, eg. If Pin4 = 0 Then loop. In this case the state of Pin4 (PORTB.4) is read and if it is low (0) the program jumps to the label loop:. If Pin4 is high (1), the program continues with the next instruction after the If..Then. All of the pins may be set at the same time using the predefined variable Pins. For example, Pins = 255 sets all of the pins high. The variable Dirs is also predefined to allow setting of the pin’s directions.

4

PicBasic Compiler

There are only 8 pins, Pin0 - Pin7, defined by the BS1 while a PICmicro may have 13, 22, 33 or more actual I/O pins. Some library routines such as I2COUT make use of some of these additional I/O pins automatically. For access to other I/O pins, the PEEK and POKE instructions were created.

2.3. Software Installation
The included software should be copied to your hard drive before use. Create a subdirectory on your hard drive called PBC or another name of your choosing by typing: md c:\pbc at the DOS prompt. Copy all of the files from the included diskette into the newly created subdirectory by typing: xcopy /s a:*.* c:\pbc The /s option will insure that all of the necessary subdirectories will be created within The PBC subdirectory. Please see the READ.ME file on the disk for additional information.

2.4. Getting Started
For operation of the PicBasic Compiler you’ll need a text editor or word processor for creation of your BASIC source file, some sort of PICmicro programmer such as our EPIC Plus Pocket PICmicro Programmer, and the PicBasic Compiler itself. Of course you also need a PC to run it all on. The sequence of events goes something like this: First you 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) may be substituted. The source file name should end with (but isn’t required to) 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

5

PicBasic Compiler

own purposes. You are usually given the option of saving the file as pure DOS or ASCII text by most word processors. The following program provides a good first test of a PICmicro in the real world. You may type it in or you can simply grab it from the SAMPLES subdirectory included on the original PicBasic Compiler distribution disk. The file is named BLINK.BAS. The BASIC source file should be created in or moved to the same directory where the PBC.EXE file is located. ‘Example program to blink an LED connected to PORTB.0 about once a second loop: High 0 Pause 500 Low 0 Pause 500 Goto loop End ‘Turn on LED ‘Delay for .5 seconds ‘Turn off LED ‘Delay for .5 seconds ‘Go back and blink LED forever

Once you are satisfied that the program you have written will work flawlessly, you can execute the PicBasic Compiler by entering PBC followed by the name of your text file at a DOS prompt. For example, if the text file you created is named BLINK.BAS, at the DOS command prompt enter: PBC blink 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 BLINK.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, BLINK.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 to write the entire 100,000 line monolith all at once and then try to debug it from end to end.

6

From Windows. if you intend to run the above program. Plug the AC adapter into the wall and then into the EPIC Programmer (or attach 2 fresh 9-volt batteries to the programmer and connect the “Batt ON” jumper. NT.BAS.5. The following is an example of how a PICmicro may be programmed using our EPIC Programmer.putting your compiled program into the PICmicro microcontroller and testing it. Make sure there are no PICmicros installed in the EPIC Programmer programming socket or any attached adapters. start EPICWin.HEX) files that may be used with any PICmicro programmer including our EPIC Plus Pocket PICmicro Programmer. on a PIC16C74. compile it using the command: PBC -p16C74 blink 2. For example. If you only have DOS or Windows 3. EPICWin is the 32-bit Windows version of the programming software and should be used with Windows 95. The PicBasic Compiler generates standard 8-bit Merged Intel HEX (. Hook the EPIC Programmer to the PC parallel printer port using a DB25 male to DB25 female printer extension cable.) The LED(s) on the EPIC Programmer may be on or off at this point.1. Program That PICmicro There are two steps left .PicBasic Compiler The PicBasic Compiler defaults to creating code for the PIC16F84. BLINK. Do not insert a PICmicro into the programming socket when an LED is on or before the programming software has been started. The EPIC DOS software only supports a limited number of PICmicros. 2000 or ME. use the DOS version of EPIC. 98. simply use the -P command line option described later in the manual to specify a different target processor. PICmicros cannot be programmed with the BASIC Stamp programming cables. The EPIC DOS software should be run from a pure DOS session. Use 7 . To compile code for PICmicros other than the ‘F84.

and some kind of 5-volt power supply.PicBasic Compiler EPICWin for programming the latest PICmicro microcontrollers. You may not be able to erase a windowed PICmicro that has been code protected. In general. the Oscillator should be set to XT for a 4MHz crystal and the Watchdog Timer should be set to ON for PicBasic programs. You can find more information on these configuration fuses in the Microchip data sheet for the device you are using. We have added an LED and resistor to provide the output from the BLINK program. you can simply choose to program over it without erasing first. Code Protect should be OFF when programming any windowed (JW) PICmicros.HEX or another file you would like to program into the PICmicro from the dialog box. it is time to insert a PICmicro into the programming socket and click on Program. a 4MHz crystal with 2 capacitors. Basically all you need is a pull-up resistor on the /MCLR line. If the EPIC Programmer is not found. The file will load and you can look at the Code window to see your PICmicro program code. The PICmicro will first be checked to make sure it is blank and then your code will be programmed into it. Once the programming is complete and the LED is off. it is time to test your program. Once the programming screen is displayed. It’s Alive The sample schematic below gives you an idea of the few things that need to be connected to the PICmicro to make it work. 8 . You should also look at the Configuration window and verify that it is as desired before proceeding. If the PICmicro is not blank and it is a 16F84 or other flash or EEPROM device. use the mouse to click on Open file.6. Most importantly. When it all looks marvelous. See the EPIC readme file for the complete support list. check all of the above connections and verify that there is not a PICmicro or any adapter connected to the programmer. The EPIC software will take a look around to find where the EPIC Programmer is attached and get it ready to program a PICmicro. Select BLINK. 2.

Our line of PICProto prototyping boards is perfect for this kind of thing. you can create your own worldconquering application. its level floats around and sometimes the PICmicro will work but usually it won’t. Connect a power supply.1uf 22pf 22pf 4Mhz PIC16F84 Build and double check this simple circuit on a breadboard and plug in the PICmicro you just programmed. Make sure the /MCLR pin is connected to 5 volts either through some kind of voltage protected reset circuit or simply with a 4. I’ve Got Troubles The most common problems with getting PICmicros running involve making sure the few external components are of the appropriate value and properly connected to the PICmicro. If it does not blink. If you leave the pin unconnected.7K 2 3 4 5 6 7 470 LED 8 9 RA2 RA3 RA4 MCLR Vss RB0 RB1 RB2 RB3 RA1 RA0 OSC1 OSC2 Vdd RB7 RB6 RB5 RB4 18 17 16 15 14 13 12 11 10 . check all of the connections and make sure 5 volts is present at the appropriate pins on the PICmicro.7.7K resistor. Your PICmicro should come to life and start blinking the LED about once a second. From these simple beginnings. 2. Following are some hints to help get things up and running. The PICmicro has an onchip power-on-reset circuit so in general just an external pull-up resistor 9 .PicBasic Compiler +5V +5V 1 4.

will come up in analog mode. See the Microchip PICmicro data books for more information. PORTA is set to analog mode. These PICmicros have analog comparators on PORTA. A 4MHz crystal with two 22pf (picofarad) ceramic disk capacitors is a good start for most PICmicros. 7 near the front of your program. 16F627 and 628) are a good example of this. This makes the pin functions on PORTA work in an unexpected manner. PIC16C7xx and PIC16F87x series devices. the oscillator won’t start and run properly.PicBasic Compiler is adequate. pin 4 exhibits unusual behavior when used as an output. Check the PICmicro data sheets. simply add the lines: Symbol CMCON = $1f Poke CMCON. The PIC16C62x and ‘F62x parts (the 16C620. the power supply must be filtered fairly well. Be sure you have a good crystal with the proper value capacitors connected to it. While the PICmicro itself consumes very little power. such as the PIC12C67x. Capacitor values can be hard to read. 7 Another example of potential disaster is that PORTA. But in some cases the PICmicro may not power up properly and an external circuit may be necessary. To change the pins to digital. You must set the pins to digital if that is how you intend to use them: Symbol ADCON1 = $9f Poke ADCON1. Make sure your power supply is up to the task. This is because the pin has an open collector output rather then the usual bipolar stage of the rest of 10 . 621. If the values are off too much. If the PICmicro is controlling devices that pull a lot of current from your power supply. Any PICmicro with analog inputs. check out the Microchip data books for additional thoughts on the matter. Even an LED display can create enough of an instantaneous drain to momentarily clobber a small power supply (like a 9-volt battery) and cause the PICmicro to lose its place. 622. When these chips start up. Some devices have features that can interfere with expected pin operations. Once again. they can put enough of a glitch on the supply lines to cause the PICmicro to stop working properly.

8. Sometimes what you are trying to do looks like it should work but doesn’t. This pin acts as any other pin when used as an input.1. Once again.PicBasic Compiler the output pins. Once these smaller programs are working properly. instead of going high. Try doing things a different way. A comment like “Set Pin0 to 1" simply explains the syntax of the language but does nothing to tell you why you have the need to do this. Start small. set it to an output. review the PICmicro data sheets to become familiar with the idiosyncrasies of a particular part. Usually there is more than one way to skin a program. This means it can pull to ground when set to 0. Make the comments tell you something useful about what the program is doing.8. add a pull-up resistor between the pin and 5 volts. someone else looking at the program (or even yourself when you are someone else later in life) may not have any idea of what you were trying to achieve. or use a PicBasic command that does it for you. To make this pin act in the expected manner. Coding Style Writing readable and maintainable programs is an art. 11 . 2. Try approaching the problem from a different angle and maybe enlightenment will ensue. they do not take up any additional space in the PICmicro so use them freely. depending on the drive necessary for the connected input. All of the PICmicro pins are set to inputs on power-up. While comments take up space in your BASIC source file. There are a few simple techniques you can follow that may help you become an artist. Something more like “Turn on the Battery Low LED” might be a lot more useful. but it will simply float when set to a 1. 2. you can build on them. no matter how hard you pound on it. The value of the resistor may be between 1K and 33K. Write short programs to test features you are unsure of or might be having trouble with. Comments Use lots of comments. If you need a pin to be an output. Even though it may be perfectly obvious to you what the code is doing as you write it.

If it is intended to be run with a non-standard crystal or special compiler options.2. Even specifying what each pin is connected to can be helpful in remembering what hardware this particular program is designed to run on. It may also be useful to list revision information and dates. But don’t include a comment block instead of individual line comments .use both.8. At the beginning of the program describe what the program is intended to do. Symbols Use SYMBOL to make the name of a pin or variable something more coherent than Pin0 or B1. descriptive pin and variable names can greatly enhance readability. be sure to list those. go indicate it Goto othercode ‘Else go do something else battlow: BattLED = 1 Goto othercode ‘Turn on the Battery Low LED ‘Go about other business 12 . The following code fragment demonstrates: Symbol Symbol BattLED = Pin0 Capacity = B1 ‘Assign Pin0 a more useful name ‘Variable B1 will contain the remaining battery capacity If Capacity < 10 Then battlow ‘If battery capacity is low.PicBasic Compiler A block of comments before a section of code and at the beginning of the program can describe what is about to happen in more detail than just the space remaining after each statement. In addition to the liberal use of comments. who wrote it and when. 2.

Usually the line or routine you are jumping to does something unique.4. try to minimize their use as much as possible. and then follow up with a comment. Try and give at least a hint of its function with the label. 13 . 2. GOTO Finally.8. try not to use too many GOTOs. Labels Labels should also be more meaningful than “label1:" or “here:”.PicBasic Compiler 2.8. Even a label like “loop:” is more descriptive (though only slightly). GOSUBs can be helpful in achieving this. While the language is not as robust as it might be and GOTOs are a necessary evil.3. Try to write your code in logical sections and not jump around too much.

PicBasic Compiler 14 .

The first item not starting with a minus is assumed to be the filename.EXE. If a path is specified. PM is not launched. the default extension . Usage The PicBasic Compiler can be invoked from the DOS command line using the following command format : PBC Options Filename Zero or more options can be used to modify the manner in which PBC compiles the specified file.1. By default. Each Option must be separated by a space though no spaces may occur within an Option. PBC expects to find PM. If PBC is invoked with no parameters or filename. 15 . Regardless of where the source file is found. Command Line Options 3. The character following the minus is a letter which selects the option. that directory is searched for the named file. If no extension is specified and the -Q option is not invoked.EXE in the same directory as PBC. Additional characters may follow if the Option requires more information. files generated by PBC are placed in the current directory.EXE) if the compilation is performed without error. Options begin with a minus ( '-' ). PBC automatically launches the assembler (PM. Any Option not recognized by PBC will generate a fatal error. a brief help screen is displayed.BAS is used. If the compilation has errors or the -S option is used.PicBasic Compiler 3.

Using any of these extensions with -C will generate errors.2. forcing strict compatibility with original PBASIC on the program being compiled. Option -C In order to given the user options in extending the PBASIC language. PIC16F84) Q Forces use of explicit extension for Source Name S Skips execution of Assembler when done † Option is passed directly to PM.2.g.1. 16 .2. 3. Symbol Table. if invoked after compilation. a listing and a map file in addition to the normal executable image. and additional variables (W7 through W39 and B14 through B79) are language extensions. Commands such as PEEK and POKE. Options Option C D L † † † Description Suppress PBC Extensions Generates Listing. 3. The -C option disables these extensions. This option is useful mainly for programs developed on the BASIC Stamp I which may have variable names which conflict with extension keywords. inline assembly. See the PICmicro Macro Assembler's manual on disk for more information on the -D option. and Map File Generates Listing OB Generates Binary rather than Merged Intel HEX P## Specify Target (e. Option -D The -D option causes the assembler to generate a symbol table.2. PBC provides some additional capabilities above and beyond the original specifications for PBASIC.PicBasic Compiler 3. the CALL statement.

Option -P## By default. Unlike PM. See the PICmicro Macro Assembler's manual on disk for more information on the -OB option.4. Check the INC directory for available B*. 17 .2. PBC accomplishes this by adding the following line to the beginning of generated programs: include "B16F84.INC files. Option -L The -L option causes the assembler to generate a listing in addition to the normal executable image. 3.INC" The -P option can be used to select another target from the PICmicro family.3. PBC's -L option doesn't allow the user to select an arbitrary name for the listing file. PBC compiles programs for the PIC16F84. See the PICmicro Macro Assembler's manual on disk for more information on the -L option.5. Option -OB The -OB option forces the assembler to generate the program's executable image as binary rather than the normal Merged Intel HEX.INC" This would allow the generated program to assemble and run on a PIC16F628.2. 3. For example: PBC -p16F628 filename would generate this line at the start of the program: include "B16F628.PicBasic Compiler 3.2.

7.ASM file. The -S option prevents this.2. This is done to convert the assembler output of PBC to an executable image. and -OB) are effectively overridden by -S.6.BAS is used. Since -S prevents the assembler from being invoked. The -Q option prevents this and forces the programmer to explicitly define the extension (if any) of the source filename. Option -S Normally.PicBasic Compiler 3. 3. the default extension . leaving PCB's output in the generated .2. when PBC successfully compiles a program. -L. it automatically launches the assembler. Option -Q Normally. options that are simply passed to the assembler (-D. when no extension is explicitly specified for the source filename. 18 .

Comments All well written programs contain adequate comments."o") Strings are usually treated as a list of individual character values. 19 . they are string constants). single characters are converted to their ASCII equivalents."l". "Hello" ‘ String (Short for "H". Binary values are defined using the prefix '%' and hexadecimal values using the prefix '$'. All following characters on this line are ignored. binary and hexadecimal."e". Character constants must be quoted using double quotes and must contain only one character (otherwise. but strings can be used with some commands. in which case they're contained on three CD-ROMs. String Constants PBC doesn't provide string handling capabilities. unless you're Microsoft. A PBC comment starts with either the REM keyword or the single quote (‘ ).2. Numeric Constants PBC allows numeric constants to be defined in the three bases: decimal. "A" "d" ‘ ASCII Value for Decimal 65 ‘ ASCII Value for Decimal 100 4.3."l". A string contains one or more characters and is delimited by double quotes.1. 4. Decimal values are the default and require no prefix. No escape sequences are supported for non-ASCII characters (although most PBC commands have this handling built-in). PicBasic Programming 4.PicBasic Compiler 4. 100 %100 $100 ‘ Decimal Value 100 ‘ Binary Value for Decimal 4 ‘ Hexadecimal Value for Decimal 256 For ease of programming.

PicBasic Compiler

4.4. Identifiers
An identifier is, quite simply, a name. Identifiers are used in PBC for line labels and symbol names. An identifier is any sequence of letters, digits, and underscores, although it must not start with a digit. Identifiers are not case sensitive, thus label, LABEL and Label are all treated as equivalent. And while labels might be any number of characters in length, PBC only recognizes the first 32.

4.5. Line Labels
In order to mark statements that the program might wish to reference with the GOTO or GOSUB commands, PBC uses line labels. Unlike many older BASICs, PBC doesn't allow line numbers and doesn't require that each line be labeled. Rather, any PBC line may start with a line label, which is simply an identifier followed by a colon ( : ). here: serout 0,N2400,("Hello, World!",13,10) goto here

4.6. Variables
A number of variables have been predefined for temporary data storage in your PicBasic program. Byte-sized variables are named B0, B1, B2 and so forth. Word-sized variables are named W0, W1, W2 and so forth. These word-sized variables are made up of two byte-sized variables. For example, W0 consists of B0 and B1; W1 is made up of B2 and B3 and so forth. Any of these variables can, in effect, be renamed using the SYMBOL command to have more meaning within your program. These variables are actually stored in the PICmicro’s RAM registers. B0 is stored in the first available RAM location, $0C for the PIC16F84 and some of the smaller PICmicros, or $20 for the PIC16C74 and other larger PICmicros. Refer to the Microchip PICmicro data books for the actual location of the start of the RAM registers for a given PICmicro. The variables are assigned to RAM sequentially up to and including B21 at which point variables internal to the compiler library subroutines are assigned. These assignments are done in the file PBH.INC in the INC subdirectory. You may refer to it for additional information.

20

PicBasic Compiler

For a PICmicro with only 36 bytes of RAM, such as the PIC16C84, the 22 user variable bytes and the internal library variables use all of the RAM that is available. For larger PICmicros like the PIC16F84 with 68 bytes of RAM and the PIC16C74 with 192 bytes of RAM, additional user variables may be accessed. These variables continue at B22 and run through B79 (also W11 through W39.) A particular PICmicro may not have actual RAM at all of these additional locations. If you try to use a variable with no RAM location, the compiler will not generate an error, but your program will not do what you expect. This table lists the highest user variable names that should be used with each PICmicro: BASIC Stamp I PIC16C61 PIC16C71 PIC16C710 PIC16C84 PIC16F83 PIC16C711 B51 PIC16F84 PIC16C554 PIC16C620 PIC16C621 All other supported PICmicros B79 W39 B63 W31 W25 B21 W10 B13 W6

The first two bytes, B0 and B1, may also be used as bit variables: Bit0, Bit1, ..., Bit15. Additionally, the variable names Port, Dirs and Pins are predefined. Pins references PICmicro hardware PORTB. Dirs references the data direction register for PICmicro hardware PORTB (TRISB). A Dir of 0
21

PicBasic Compiler

sets its associated Pin to an input and a Dir of 1 sets its associated Pin to an output. Most instructions set the Pin’s direction automatically. Port is a word variable that combines Pins and Dirs. Like W0, these are overlaid and can be referenced as bits (Pin0, Pin1... and Dir0, Dir1...). When powered up or reset, Dirs is set to $00 (all pins input) and all other variables are set to $00. All variable values are unsigned. Thus, bits have the value 0 or 1, bytes 0 to 255, and words 0 to 65535. The following table lists the predefined variables: Word Variables W0 W1 W2 ... W39 Port Byte Variables B0 B1 B2 B3 B4 B5 ... ... B78 B79 Pins Dirs Pin0,Pin1,... Pin7 Dir0,Dir1,... Dir7 Bit Variables Bit0,Bit1,... Bit7 Bit8,Bit9,... Bit15

While the use of fixed names might seem to be limiting and lead to ugly programs, these variables may be given more useful names via the SYMBOL statement.

22

Only one symbol may be defined per SYMBOL statement. PBC supports the use of the colon (:) to separate statements placed on the same line. 23 . They may not be used for line labels.8. Symbols In order to make programs more readable.PicBasic Compiler 4. however. variables or other symbols. Multi-statement Lines In order to allow more compact programs and logical grouping of related commands. change the size of the generated code. Symbol Symbol Symbol Symbol Ten = 10 Count = W3 BitVar = BIT0 Alias = BitVar ‘ ‘ ‘ ‘ Symbolic Constants Named Word Variable Named Bit Variable An Alias for BitVar 4. PBC allows the user to define his own symbols. Thus.7. These symbols may be used to represent constants. the following two examples are equivalent: W2 = W0 W0 = W1 W1 = W2 is the same as: W2 = W0 : W0 = W1 : W1 = W2 This does not.

PicBasic Compiler 24 .

Power down processor for short period of time. Generate pseudo-random number. Read bytes from I2C device.† Read potentiometer on specified pin. Call assembly language subroutine at specified label. Perform math and assign result to variable. Make pin an input. PicBasic Pro Statement Reference BRANCH BUTTON CALL DEBUG EEPROM END FOR.† GOTO if specified condition is true. Debounce and auto-repeat input on specified pin. Generate pulse (10uSec resolution). Make pin output. Write byte to on-chip EEPROM.† Write bytes to I2C device.† Write byte to PICmicro register. Call BASIC subroutine at specified label. Make pin output low.GOTO).THEN INPUT [LET] LOOKDOWN LOOKUP LOW NAP OUTPUT PAUSE PEEK POKE POT PULSIN PULSOUT PWM RANDOM READ RETURN REVERSE SERIN SEROUT SLEEP SOUND TOGGLE WRITE Computed GOTO (equiv.. Asynchronous serial output (8N1). Search table for value.. Continue execution at specified label. † PicBasic language extension not found in PBASIC. Define initial contents of on-chip EEPROM.NEXT GOSUB GOTO HIGH I2CIN I2COUT IF. Delay (1mSec resolution). Read byte from on-chip EEPROM. Continue execution at statement following GOSUB. Make output pin an input or an input pin an output..† Debugging statement (Ignored by PBC). Fetch value from table. Generate tone or white-noise on specified pin. Output pulse width modulated pulse train to pin.PicBasic Compiler 5. Asynchronous serial input (8N1). Make pin output and toggle state. Make pin output high. Measure pulse width (10uSec resolution). Repeatedly execute statement(s). Stop execution and enter low power mode. 25 . Read byte from PICmicro register. to ON. Power down processor.

For example. at the second label. If Offset is one.label3) ‘If B10=0 goto label1. And so on.PicBasic Compiler 5. no action is taken and execution resumes with the following statement. Branch B10. BRANCH BRANCH Offset. if B10=1 goto label2. if B10=2 goto label3 26 .(label1. Label} ) Uses Offset to index into the list of labels.1.( Label{.label2. execution resumes at the first label specified in the list. if Offset is zero. If Offset is equal to or greater than the number of labels. Execution resumes at the indexed label.

Var Byte variable used for delay/repeat countdown.0. Should be initialized to 0 prior to use. Delay. is performed.skip ‘Check for button pressed on Pin2 and goto skip if not 27 .10.1). BUTTON BUTTON Pin.255). Down. 10K I/O 10K I/O Button 2. Action.PicBasic Compiler 5.100. debounce. 1 if pressed).7). ActionState of button to perform GOTO (0 if not pressed. If 255. Down State of pin when button is pressed (0.255). Label Read input.. Rate. If 0. Pin Pin number (0. Delay Cycle count before auto-repeat starts (0.. no debounce or auto-repeat is performed.2.. Var. but no autorepeat.B0. Rate Auto-repeat rate (0.0.. Label Execution resumes at this label if Action is true. perform debounce and auto-repeat on Pin.

PicBasic Compiler 5.3. See the section on assembly language for more information. Call pass ‘Call assembly language subroutine named pass 28 . CALL CALL Label Executes the assembly language subroutine named Label. CALL is a PicBasic Compiler statement and is not supported on the BASIC Stamp.

4. however. PBC will. DEBUG PBC does not support the PBASIC DEBUG statement. 29 . parse DEBUG statements correctly and report syntax errors.PicBasic Compiler 5.

} ( Constant{. not each time the program is run.PicBasic Compiler 5. The data is stored in the EEPROM space at the time the PICmicro is programmed. No length or terminator is added automatically.5. Constant can be a numeric constant or a string constant.30) ‘Store 10. EEPROM only works with PICmicros with on-chip EEPROM such as the PIC16F84 and PIC16F628. 20 and 30 starting at EEPROM location 5 30 . Eeprom 5. EEPROM EEPROM { Location. the first EEPROM statement starts storing at address 0 and subsequent statements store at the following locations. Only the least significant byte of numeric values are stored. If the optional location value is omitted. Strings are stored as consecutive bytes of ASCII values. If the location value is specified.20. Constant} ) Stores constants in consecutive bytes in on-chip EEPROM.(10. it specifies the location where these values are stored.

END END Stops program execution and enters the low power mode by executing continuous NAP commands.6.PicBasic Compiler 5. End 31 .

. FOR.NEXT is best described step by step: 1) 2) 3) 4) The value of Start is assigned to the index variable. The Body is optional and can be omitted (perhaps for a delay loop). Index is incremented by one. The Body is executed. execution resumes at Step 2. All loop calculations are performed using 16-bit arithmetic. Index.N2400.PicBasic Compiler 5.. If Index is still between Start and End (inclusive).} Inc } { Body } NEXT { Index } The FOR.. Due to its complexity and versatility.NEXT loop allows PBC programs to executes a number of statements (the Body) some number of times using a variable as an index.NEXT FOR Index = Start TO End { STEP { .(#B6. FOR.(10) ‘Send a linefeed 32 .7. If no STEP clause is defined.” “) ‘Send each number to Pin0 serially Next B6 ‘Go back to top of For and do next count Serout 0. For B6 = 1 to 10 ‘Count from 1 to 10 Serout 0. Index can be a variable of any type. The value of Inc is added to (or subtracted from) Index.N2400.

GOSUB GOSUB Label Executes the statements at Label. execution resumes with the statement following the GOSUB statement.PicBasic Compiler 5. beep: High 0 ‘Turn on LED connected to Pin0 Sound 1. Unlike GOTO..(80. Subroutines can be nested. when the RETURN statement is reached.10) ‘Beep speaker connected to Pin1 Low 0 ‘Turn off LED connected to Pin0 Return ‘Go back to main routine that called us 33 . Gosub beep ‘Execute subroutine named beep .8. Such nesting should be restricted to no more than four levels deep.. The code between Label and the RETURN statement is called a subroutine. In other words. it is possible for a subroutine to call other subroutines.

9.(“Hi”) ‘Send “Hi” out Pin0 serially 34 . Goto send ‘Jump to statement labeled send .PicBasic Compiler 5..N2400.. GOTO GOTO Label Program execution continues with the statements at Label. send: Serout 0.

is specified (i. 0 to 7. NOT Pin0. HIGH HIGH Pin Makes the specified pin output high.10. The pin is automatically made an output pin.PicBasic Compiler 5. i.) High 0 ‘Make Pin0 an output and set it high (~5 volts) 35 . Only the pin number itself.e.e.

the Address required is 8 bits. These commands operate in the I2C master byte read and write modes and may also be used to talk to other devices with an I2C interface like temperature sensors and A/D converters. For example. The lower 7 bits of the Control byte contain the control code along with chip select or additional address information.11. This allows data to be stored in nonvolatile memory so that it can be maintained even after the power is turned off.PicBasic Compiler 5. Formats of Control bytes for some of the different parts follow: 36 . I2CIN and I2COUT can be used to read and write data to a serial EEPROM with a 2-wire I2C interface such as the Microchip 24LC01B. the control code is %1010 and the chip select is unused so the Control byte would be %01010000 or $50. The control code for a serial EEPROM is %1010. 24LC02B and similar devices. I2CIN I2CIN Control. If this flag is low. depending on the particular device. the Address is sent as 8 bits. The high order bit is a flag indicating whether the following Address is to be sent as an 8 bit or 16 bit address. Address. Var{. Var} Sends Control and Address out the I2C clock and data lines and puts the byte(s) received into Var. when communicating with a 24LC01B.

1 respectively. The I2C data line should be pulled up to Vcc with a 4.PicBasic Compiler Device 24LC01B 24LC02B 24LC04B 24LC08B 24LC16B 24LC32B Capacity 128 bytes 256 bytes 512 bytes 1K bytes 2K bytes 4K bytes Control %01010xxx %01010xxx %01010xxb %01010xbb %01010bbb %11010ddd Address size 8 bits 8 bits 8 bits 8 bits 8 bits 16 bits 24LC65 8K bytes %11010ddd 16 bits bbb = block select (high order address) bits ddd = device select bits xxx = don’t care See the Microchip Non-Volatile Memory Products Data Book for more information on these and other devices that may be used with the I2CIN and I2COUT commands.INC.7K resistor per the following schematic as it is run in a bi-directional open-collector manner. 37 . The I2C data and clock lines are predefined in the main library as PortA. This gets them out of the way of the PortB pins and makes it unnecessary to define them in each I2CIN or I2COUT statement. They may be assigned to different pins by simply changing the equates at the beginning of the I2C routines in the file PBL.0 and PortA.

PicBasic Compiler Symbol Symbol con = %01010000 addr = B5 addr = 17 ‘ Set address to 17 I2Cin con.B2 ‘ Read data at address 17 into B2 38 .addr.

If a subsequent I2CIN or I2COUT is attempted before the write is complete.(B12) ‘ Send the byte in B12 to address 127 Pause 10 ‘ Wait 10ms for write to complete 39 . I2COUT I2COUT Control.(56) ‘ Send the byte 56 to address 17 Pause 10 ‘ Wait 10ms for write to complete addr = 127 ‘ Set address to 127 I2Cout con. Address. Symbol Symbol con = %01010000 addr = B5 addr = 17 ‘ Set address to 17 I2Cout con. When writing to a serial EEPROM it is necessary to wait 10ms (device dependent) for the write to complete before attempting communication with the device again.addr.addr.12. See the I2CIN command above for the rest of the story. Value }) I2COUT sends Control and Address out the I2C clock and data lines followed by Value. While a single I2COUT statement may be used to write multiple bytes at once. the access will be ignored.PicBasic Compiler 5. doing so would violate the above write timing requirement for serial EEPROMs. ( Value{. The multiple byte write feature may be useful with I2C devices other than serial EEPROMs that don’t have to wait between writes.

13.THEN. jump to old 40 .THEN is essentially a GOTO.. A variable must occur on the left. If the condition is true. IF. If Pin0 = 0 Then pushd If B0 >= 40 Then old ‘If button connected to Pin0 is pushed (0). Another statement may not be placed after the THEN. the program will GOTO the label after the THEN.. it must be a label.. If the condition evaluates to false.PicBasic Compiler 5. jump to label pushd ‘If the value in variable B0 is greater than or equal to 40. the program will continue at the next line after the IF. Each Comp term can relate a variable to a constant or other variable and must be in the following form: Var ( < | <= | = | <> | >= | > ) Value All comparisons are unsigned since PBC only supports unsigned types.THEN IF Comp { AND/OR Comp } THEN Label Performs one or more comparisons. The THEN in an IF.

e. INPUT INPUT Pin Makes the specified pin an input. 0 to 7.e. NOT Pin0.14. Only the pin number itself.PicBasic Compiler 5.) Input 1 ‘Make Pin1 an input 41 . i. is specified (i.

The value may be a constant. the value of another variable or the result of one or more binary operations.15.} Value { Op Value } Assigns a value to a variable. The operators supported are: + * ** / // MIN MAX & | ^ &/ |/ ^/ Addition Subtraction Multiplication MSB of Multiplication Division Remainder Minimum Maximum Bitwise AND Bitwise OR Bitwise XOR Bitwise AND NOT Bitwise OR NOT Bitwise XOR NOT Let B0 = 27 ‘Assign variable B0 the value 27 (“Let” is optional) B1 = B0 / 2 ‘Assign variable B1 B0's value shifted right one bit (divided by 2) Pin2 = 0 ‘Make Pin2 low (does not set Pin2 to an output) 42 . Unary negation may only be performed on the first value. {LET} { LET } Var = { . The operations are performed strictly left to right and all operations are performed with 16-bit precision.PicBasic Compiler 5.

2. This is the typical multiplication found in most programming languages.15. Multiplication PBC performs 16x16 multiplication. PBC also supports NOT versions. The '**' operator returns the upper 16 bits of the 32-bit result. B3 = B3 &/ %11110000 ‘Same as B3 = B3 & %00001111 43 . OR. W1 = W0 * 1000 W2 = W1 ** W0 ‘Multiply value in W0 by 1000 and place the result in W1 ‘Multiply W1 by W0 and place the high order 16 bits (which may be 0) in W2 5.1. Bitwise NOT Operators Along with the normal bitwise binary operators (AND. XOR). The '*' operator returns the lower 16 bits of the 32-bit result. These two operators can be used in conjunction to perform 16x16 multiplication to produce 32-bit results.PicBasic Compiler 5.15. These versions perform a bitwise complement on the right-hand value prior to performing the operation.

N2400.(#B1) ‘Send decimal value to Pin0 serially 44 . Constant} ).B1 ‘Convert hexadecimal character in B0 to decimal value B1 Serout 0.16. if the value is found first in the list. Thus. The constant list can be a mixture of numeric and string constants. If not found. LOOKDOWN LOOKDOWN Search. If second in the list.(“0123456789ABCDEF”).B0 ‘Get hexadecimal character from Pin1 serially Lookdown B0. ( Constant{. Var is set to one.PicBasic Compiler 5. Var The LOOKDOWN statement searches a list of Constant values for the presence of the Search value. Var is set to zero. no action is taken and Var remains unchanged.N2400. Serin 1. Each character in a string is treated as a separate constant with the character's ASCII value. And so on. the index of the matching constant is stored in Var. If found.

The constant list can be a mixture of numeric and string constants. LOOKUP LOOKUP Index.17. Each character in a string is treated as a separate constant equal to the character's ASCII value.B1 ‘Get character number B0 from string to variable B1 Serout 0. Var is set to the value of the first Constant. ( Constant{.PicBasic Compiler 5. And so on. If Index is greater than or equal to the number of entries in the constant list. Var The LOOKUP statement can be used to retrieve values from a table of constants. Var is set to the value of the second Constant.(B1) ‘Send character in B1 to Pin0 serially Next B0 ‘Do next character 45 . no action is taken and Var remains unchanged.(“Hello!”). For B0 = 0 to 5 ‘Count from 0 to 5 Lookup B0. Constant} ). If Index is one.N2400. If Index is zero.

i.18. 0 to 7.) Low 0 ‘Make Pin0 an output and set it low (0 volts) 46 . NOT Pin0. is specified (i. Only the pin number itself.e.PicBasic Compiler 5.e. LOW LOW Pin Makes the specified pin output low. The pin is automatically made an output pin.

The listed periods are only approximate because the timing is derived from the Watchdog Timer which is R/C driven and varies greatly from chip to chip and over temperature: Period Delay (Approx.) 0 1 2 3 4 5 6 7 18 mSec 36 mSec 72 mSec 144 mSec 288 mSec 576 mSec 1.152 Sec 2.3 seconds 47 . NAP NAP Period Places PICmicro in low power mode for short periods of time. During this NAP.PicBasic Compiler 5.19.304 Sec Nap 7 ‘Low power pause for about 2. power consumption is reduced to minimum.

NOT Pin0.e. i.e.) Output 0 ‘Make Pin0 an output 48 . is specified (i. OUTPUT OUTPUT Pin Make the specified pin an output. 0 to 7. Only the pin number itself.20.PicBasic Compiler 5.

PAUSE consumes more power but is also more accurate. Thus. PAUSE doesn't put the PICmicro into low power mode.535 milliseconds (a little over a minute). It has the same accuracy as the system clock. so delays can be up to 65. Unlike the other delay functions (NAP and SLEEP). Pause 1000 ‘Delay for 1 second 49 .PicBasic Compiler 5. PAUSE PAUSE Period Pauses the program for Period milliseconds.21. Period is 16-bits.

it is recommended that those I/O functions be assigned to a pin on PORTB and less demanding byte access be left to the other I/O ports. When you POKE data to PORTA. Var Reads the PICmicro register at the specified Address and stores the result in Var. for example. Special PICmicro features such as A/D converters and additional I/O ports may be read using PEEK. not just one individual bit.B0 ‘Make all PortA pins inputs ‘Get current PortA pin states to variable B0 If Bit0 = 1 Then zerohigh ‘Jump to label zerohigh if Bit0 (RA0) is high 50 . PEEK and POKE allow direct access to all of the registers on a PICmicro including PORTA. of the particular register at once. Following are examples of this technique. ‘ Read PortA bits using intermediate variable B0 Symbol Symbol PortA = 5 ‘Define PortA register location TrisA = $85 ‘Define PortA direction register location Poke TrisA. If substantial individual bit manipulation is required. PORTB. PEEK and POKE operate on all of the bits. PORTC. the entire byte.255 loop: Peek PortA. It can first be set up as desired and then POKEd to PORTA. to ease bit manipulation. PORTE and their associated data direction (TRIS) registers.e. PEEK is a PicBasic Compiler statement and is not supported on the BASIC Stamp. i. This technique may be used with any PICmicro register. PEEK PEEK Address.PicBasic Compiler 5. PORTD.22. Alternatively variable B0 allows manipulation of its individual bits. the entire port is updated.

B0 ‘Send the new byte to PortA to complete the change End 51 . 2 and 4 will remain unchanged Poke PortA.B0 ‘Get current PortA pin states to variable B0 Bit1 = 1 ‘Set Bit1 in B0 which will become PortA pin 1 high Bit3 = 0 ‘Set Bit3 in B0 which will become PortA pin 3 low ‘Bit0.PicBasic Compiler If Bit1 = 0 Then onelow ‘Jump to label onelow if Bit1 (RA1) is low Goto loop ‘Go check some more zerohigh: onelow: High 0 Goto loop Low 1 Goto loop End ‘Set Pin0 (RB0) high ‘Go do some more ‘Set Pin1 (RB1) low ‘Go do some more ‘ Set PortA bits using intermediate variable B0 Symbol Symbol PortA = 5 ‘Define PortA register location TrisA = $85 ‘Define PortA direction register location Poke TrisA.0 ‘Make all PortA pins outputs Peek PortA.

) Poke $85. POKE is a PicBasic Compiler statement and is not supported on the BASIC Stamp.0 ‘Write 0 to register hexadecimal 85 (Sets PortA to all outputs) 52 .PicBasic Compiler 5. Value Writes Value to the PICmicro register at the specified Address. POKE POKE Address. (See PEEK for more information. Special PICmicro features such as A/D converters and additional I/O ports may be written using POKE.23.

To do so. Scale. If Scale is set correctly. (NOTE: This is the same type of process performed by the Alt-P option of the PBASIC environment). For larger R/C constants. POT POT Pin. Under these conditions.N2400. Var should be set to zero near minimum resistance and to 255 near maximum resistance. For smaller R/C constants.(#B0) ‘Read potentiometer on Pin3 to determine scale ‘Send pot value serially out Pin0 53 . 5-50K Pin 0.PicBasic Compiler 5. set the device under measure to maximum resistance and read it with Scale set to 255. The resistance is measured by timing the discharge of a capacitor through the resistor (typically 5K to 50K).1uF Pot 3. Scale is used to adjust for varying R/C constants. Pins are numbered 0 to 7.24. Scale should be set to its maximum value (255). Scale must be determined experimentally. Var Reads a potentiometer (or some other resistive device) on Pin.B0 Serout 0.255. Var will produce an appropriate value for Scale. Scale should be set low (a minimum value of one). Unfortunately.

Var is set to zero. which can take measurements from 10 uSec to 655.W3 ‘Measure high pulse on Pin4 and place width * 10uSec in W3 54 . only the LSB of the 16-bit measurement is used. Pulsin 4. Pins are numbered from 0 to 7.1. State. PULSIN PULSIN Pin. If an 8-bit variable is used. the width of a low pulse is measured. If State is one. Var Measures pulse width in 10 uSec units on Pin.25. If State is zero. the width of a high pulse is measured.350 uSec for 16-bit variables. If the pulse edge never happens or the width of the pulse is too great to measure.PicBasic Compiler 5. The measured width is placed in Var.

PULSOUT PULSOUT Pin.350 uSec can be generated. Period Generates a pulse on Pin of specified Period in 10 uSec units. Pulsout 5. The pin is automatically made an output pin.26. Pins are number 0 to 7. thus the initial state of the pin determines the polarity of the pulse. The pulse is generated by toggling the pin twice.PicBasic Compiler 5. pulses of up to 655. Since Period is 16-bits.100 ‘Send a pulse 1mSec long to Pin5 55 .

100 ‘Send a 50% duty cycle PWM signal out Pin7 for 100 cycles 56 . Pins are numbered from 0 to 7.27. The pin is made an output just prior to pulse generation and reverts to an input after generation stops.127. This allows a simple R/C circuit to be used as a simple D/A converter: 10K Pin Analog Out 1uF Pwm 7. Each cycle of PWM consists of 256 steps. This PWM cycle is repeated Cycle times. Cycle Outputs PWM pulse train on Pin.PicBasic Compiler 5. The Duty cycle for each PWM cycle ranges from 0 (0%) to 255 (100%). PWM PWM Pin. Duty.

Var must be a 16-bit variable. The pseudo-random algorithm used has a walking length of 65535 (only zero is not produced). RANDOM RANDOM Var Performs one iteration of pseudo-randomization on Var. Random W4 ‘Get a random number to W4 57 .28. (NOTE: PBC does not support the use of the PORT variable with the RANDOM statement).PicBasic Compiler 5.

Var Reads the EEPROM byte at the specified Address and stores the result in Var. This instruction may only be used with a PICmicro that has an on-chip EEPROM data area such as the PIC16C84.29. 8x and 87x. If Address is 255 and the device is a PIC16C84. 628. READ READ Address. Read 5.PicBasic Compiler 5. 16F627. 16F62x.B2 ‘Put the value at EEPROM location 5 into B2 58 . Address 255 is not valid for 16F87x devices. Var is assigned the number of EEPROM bytes available. 83 or 84.

RETURN resumes execution at the statement following the GOSUB which called the subroutine.N2400.(“Lunch”) ‘Send “Lunch” out Pin0 serially Return ‘Return to main program after Gosub 59 . RETURN RETURN Returns from subroutine.30.. Gosub sub1 ‘Go to subroutine labeled sub1 .PicBasic Compiler 5.. sub1: Serout 0.

If the pin is an output.PicBasic Compiler 5. it is made an input. Output 4 Reverse 4 ‘Make Pin4 an output ‘Change Pin4 to an input 60 .31. REVERSE REVERSE Pin If the pin is an input. it is made an output. Pins are numbered 0 to 7.

the next received byte is compared to the first item in the qualifier list). the qualification process resets (i. A Qualifier can be a constant.Qual}). no parity and one stop bit. SERIN begins storing data in the variables associated with each Item. DB9 RS-232 TX RS-232 GND Pin 3 Pin 5 DB25 Pin 2 Pin 7 Pin 22K The list of data items to be received may be preceded by one or more qualifiers enclosed within parenthesizes.32. Mode. 61 . variable or a string constant.e. SERIN must receive these bytes in exact order before receiving the data items.Item} Receives one or more items on Pin in standard asynchronous format using 8 data bits.PicBasic Compiler 5.{ (Qual{. If the variable name is used alone. SERIN SERIN Pin. Once the qualifiers are satisfied. If any byte received does not match the next byte in the qualifier sequence. Each character of a string is treated as an individual qualifier. Mode is one of the following: Symbol Value Baud Rate T2400 T1200 T9600 T300 N2400 N1200 N9600 N300 0 1 2 3 4 5 6 7 2400 1200 9600† 300 2400 1200 9600† 300 TTL Inverted TTL True Mode † 9600 baud is an addition to the PicBasic Compiler and is not available on the BASIC Stamp I. } Item{.

N2400. then SERIN converts a decimal value in ASCII and stores the result in that variable. the excellent I/O specifications of the PICmicro allow most applications to run without level converters. inverted input (N9600.PicBasic Compiler the value of the received ASCII character is stored in the variable. While single-chip RS-232 level converters are common and inexpensive. The non-digit character which terminates the decimal value is also discarded. Rather.. If variable is preceded by a pound sign ( # ). All nondigits received prior to the first digit of the decimal value are ignored and discarded.B0 ‘Wait until the character “A” is received serially on Pin1 and put next character into B0 62 .N300) can be used is conjunction with a current limiting resistor. Serin 1.(“A”).

PicBasic Compiler 5. no parity and one stop. SEROUT supports three different data types which may be mixed and matched freely within a single SEROUT statement. 1) 2) A string constant is output as a literal string of characters. Mode. Item{. A numeric value preceded by a pound sign ( # ) will send the 63 3) . 13 is carriage return and 10 is line feed. Most notably. Mode is one of the following: Symbol Value Baud Rate T2400 T1200 T9600 T300 N2400 N1200 N9600 N300 OT2400 OT1200 OT9600 OT300 ON2400 ON1200 ON9600 ON300 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 2400 1200 9600† 300 2400 1200 9600† 300 2400 1200 9600† 300 2400 1200 9600† 300 Open Source Open Drain TTL Inverted TTL True Mode † 9600 baud is an addition to the PicBasic Compiler and is not available on the BASIC Stamp I. SEROUT SEROUT Pin.33.Item} Sends one or more items to Pin is standard asynchronous format using 8 data bits. A numeric value (either a variable or a constant) will send the corresponding ASCII character.

most applications don't require level converters.10) ‘Send the ASCII value of B0 followed by a linefeed out Pin0 serially 64 .N2400. '2'. '3'. inverted TTL (N300. For example.N9600) can be used. then #W0 (or #123) will send '1'. Rather. 1K DB9 RS-232 RX RS-232 GND Pin 2 Pin 5 DB25 Pin 3 Pin 7 Pin Serout 0.PicBasic Compiler ASCII representation of its decimal value. thanks to current RS-232 implementation and the excellent I/O specifications of the PICmicro.. While single-chip RS-232 level converters are common and inexpensive.(#B0. if W0 = 123. A current limiting resistor is suggested (RS-232 is suppose to be short-tolerant).

PicBasic Compiler 5. Sleep 60 ‘Sleep for 1 minute 65 . SLEEP SLEEP Period Places PICmicro in low power mode for Period seconds.535 seconds (just over 18 hours). Period is 16-bits. so delays can be up to 65.3 seconds.34. 2. SLEEP uses the Watchdog Timer to periodically wake up to see if the Period has expired so its resolution is the maximum timeout for the Watchdog Timer.

Duration is 0-255 and determines how long the Note is played.( Note. Tones and white noises are in ascending order (i. a speaker can be driven through a capacitor. Duration} ) Generates tone and/or white noise on the specified Pin.10.50.PicBasic Compiler 5.35. Pins are numbered 0 to 7. SOUND outputs TTL-level square waves.10) ‘Send 2 sounds consecutively to Pin7 66 .e. Note and Duration needn't be constants. 127 and 255 are the highest).(100. Note. Note 0 is silence. SOUND SOUND Pin. Thanks to the excellent I/O characteristics of the PICmicro. Duration{. Notes 128-255 are white noise. 1 and 128 are the lowest frequencies. Piezo speakers can be driven directly. Notes 1-127 are tones. 10uF Pin Sound 7.

Low 0 Toggle 0 ‘Start Pin0 as low ‘Change state of Pin0 to high 67 .36. Pins are numbered 0 to 7. TOGGLE TOGGLE Pin Inverts the state of the specified pin. The pin is automatically made an output pin.PicBasic Compiler 5.

WRITE WRITE Address.PicBasic Compiler 5. This instruction may only be used with a PICmicro that has an on-chip EEPROM data area such as the PIC16C84.B0 ‘Send value of B0 to EEPROM location 5 68 . Value Writes byte Value to the EEPROM at the specified Address. 8x and 87x.37. 16F62x. Write 5.

Structure of a Compiled Program PBC is designed to be easy to use. For NAP and SLEEP to work. This allows the library to selectively define additional variables and functions needed for PBC extensions. The B##. or 0 if PBC extensions are disabled (-C option). In the case of a PIC16Cxxx. the Watchdog Timer must be enabled. Target (PICmicro) Specific Header (B##. although this can be changed using the -P option. The DATA pseudo-op is next used to select the data segment as the current segment. Some people. 6. The PM header. Next. This header is.1.INC) The first thing a PBC generated program does is define the symbol PBCX to be 1 if PBC extensions are enabled. It describes the output generated by PBC and gives some idea of exactly what is going on. this will either be 0Ch or 20h. uninteresting and unchanging implementation details in PBH. this file is B16F84. This section is for them.INC. only have confidence in a product when they understand its internal workings. however. in turn. Others are just plain curious.INC header then uses the DEVICE pseudo-op to set the processor's fuses. The oscillator must also be set appropriately. The header should then execute NLIST to disable listing. a target specific header file is included. By default. Selecting one of these addresses is important because PBC's internal bit numbering scheme relies on selecting one of these two addresses. It should also place the load pointer at the base of usable RAM in the target processor. 69 . Other fuse positions can be set at the user's discretion. See the Microchip data sheet for the particular device for information about the configuration fuses.INC. in turn. This hides tedious. responsible for including (via MACLIB) the processor specific header supplied with PM. defines all the processor specific information needed to assemble programs for that PICmicro.PicBasic Compiler 6. Programs can be compiled and run with little thought to PBC's internal workings.

PBH. Since normal PICmicro numbering requires 11 bits. And some macros access the PINS and DIRS registers. A number of macros are defined.INC is done. This is followed by the definition of working and temporary registers used by PBC's libraries. User variables can occupy up to 80 bytes of memory unless the -C option is used.INC can be overridden by being defined here. listing is enabled and the code segment is selected.INC first defines user variables in the data segment.2.INC PBH. a custom system was developed.INC. This is followed by a set mandatory library routines. DIRx. PINx. such target specific routines should be as brief as possible. 6. The FW@Pin and FW@Mask functions are responsible for the run time mapping of PBC bit numbers onto the FSR and W registers. Its details are uninteresting. any target specific library routines should be added. These are particularly interesting since they can be overridden by definitions in B##. The last thing left to do is define the main label.INC is included. Since these routines must be assembled before the user's code is assembled. At this point. 6. Working variables and temporary registers occupy another 13-16 bytes. and the bits of W0) need to be spanned by an 8-bit value in order to take best advantage of the W register. Some are simple utility macros. If desired. The code segment is then selected and startup code is generated. which is where the user's code will start execution. they must assemble unconditionally (unlike the normal library routines). but it is important to understand that PBC bit numbers need to be converted before use and cannot be used verbatim in an assembly language subroutine. in which case only 14 bytes are used. Hence.PicBasic Compiler Then PBH. Some perform the bit mapping mentioned earlier. and other bit locations are numbered. When PBH. PBC Generated Code 70 . macro and bit addresses defined in PBH.3. TRIS. All bits of interest (PORT.

In this way.PicBasic Compiler B##. 71 . end@ is always assembled. The code segment is the current segment and the load pointer is set to main. the place where the user's code begins execution. After the user's code is assembled.INC have now laid all the ground work for the compiled code.INC and PBH.4.INC PBL. only needed library routines are actually assembled. The first module in PBL. This simulates the END statement implicitly at the end of each PBC program. Most of the routines corresponding to PBC statements end in the '@' character. 6. Each routine is conditionally assembled only if it is explicitly referenced (via the REF operator). PBC's library PBL.INC contains library support routines. Routines are ordered such that every routine in the library is only dependent on routines which occur later in the library. PBL.INC is end@. Block comments indicate each routine's functionality.INC is included. Unlike other modules in the library.

PicBasic Compiler 72 .

If a 20MHz crystal is used. including the SERIN and SEROUT commands. With a 2 microsecond resolution. If you tell SERIN or SEROUT to run at 9600 baud. How Fast is Fast Enough? The PicBasic Compiler generates programs intended to be run on a PICmicro with a 4MHz crystal or ceramic resonator. The SERIN and SEROUT commands will be unusable and the Watchdog Timer may 73 . This allows a Pause 1000.070 microseconds. however. However. for example. when it would be useful to run the PICmicro at a frequency other than 4MHz. PicBasic Compiler programs may be run at clock frequencies other than 4MHz if you pay attention to what happens to the time dependent instructions. it might be nice to run them even faster. you would simply clock the PICmicro with an 8MHz crystal rather than a 4MHz crystal. the doubling of the crystal speed will double the actual baud rate to 19. Going the other direction and running with a 32. All of the time sensitive instructions assume a 1 microsecond instruction time for their delays. Or maybe it is desirable to do serial input or output at 19. Other PicBasic Considerations 7. This technique may also be used to enhance the resolution of the PULSIN and PULSOUT instructions.1. The Pause 1000 mentioned above would only wait half a second with an 8MHz crystal before allowing program execution to continue. keep in mind commands such as PAUSE and SOUND will also run twice as fast. to wait 1 second and the SERIN and SEROUT command’s baud rates to be accurate. At 4MHz these instructions operate with a 10 microsecond resolution. makes everything run twice as fast.200 as described above. There are times. the maximum measurable pulse width would be 131.768Khz oscillator is problematic.200 baud. It may be desirable to attempt this for reduced power consumption reasons and it will work to some extent. There is a tradeoff however. the resolution is increased 5 times to 2 microseconds. If you wish to run the serial bus at 19.200 baud rather than the current top speed of 9600 baud. This. in effect. Even though the compiled programs move along at a pretty good clip. The pulse width is still measured to a 16-bit word variable.PicBasic Compiler 7.

It is possible to modify the actual library routines to maintain proper instruction timing at clock speeds other than 4MHz. SLEEP. The time dependent instructions are I2CIN. SERIN. and SOUND. PWM. All symbol names defined in a PBC program are similarly defined in assembly. PULSOUT. but with the name preceded with an underscore ( _ ). 7. however. Assembly Language Assembly language routines can be a useful adjunct to a PicBasic Compiler program. and even labeled locations. Experiment to find out if your particular application is possible at this clock speed. This allows the PBC program to use all of the facilities of PM. or included as another file. one or more lines of assembly code preceded by the ASM keyword and ended by the ENDASM keyword. The lines of assembly are copied verbatim to the assembly output file.1. constants.2. PULSIN. there are times when it might be necessary to do a particular task faster. 7. or just differently than the compiler does it. POT. While in general most tasks can be done completely in PicBasic. SEROUT. It can be beneficial to write most of a program quickly using the PicBasic language and then sprinkle in a few lines of assembly code to increase the functionality. or using a smaller amount of code space. requires that the programmer have some familiarity with the PBC libraries. Programming in Assembly Language PBC programs may contain in-line assembly. It doesn’t hurt to try. PBC’s notational conventions are similar to other commercial compilers and should come as no shock to programmers experienced enough to attempt in-line assembly. This allows access to user variables. added to the main library. 74 .2. PAUSE. the PICmicro Macro Assembler. This also. This additional code may be inserted directly into the PicBasic program.PicBasic Compiler cause the program to restart periodically. I2COUT. At those times it is useful to have the capabilities of an in-line assembler. although with some functions a fair bit of effort may be required. Both keywords appear on their lines alone.

If you should have a name collision. Since inline assembly is copied directly to the output file and not processed by the compiler. either use predefined system variables or define the variables in PBC. the compiler will report the duplicate definitions as an error. so do symbols not starting with underscores. The compiler 75 ‘The following code is written in assembler RP0 . most library variables contain an '@' or make reference to one of the working registers (such as R0).PicBasic Compiler in assembly. can these underscored assembly values be accessed from PBC? No. it is completely unaware that they exist. If conflict is avoided. The problem is internal library variables. 7.B0 ‘Send whatever is in variable B0 to PortA (register 5) But for code speed and size reasons you might write: asm clrb mov endasm This code takes 3 words of code space and runs in 3 microseconds (with a 4MHz oscillator) as opposed to the PicBasic statement which takes up a little more code space but takes several microseconds longer to execute. Luckily. (The clrb RP0 isn’t strictly necessary. Assembly Language Examples To write a byte to PORTA in PicBasic you could simply: Poke 5.Make sure we’re pointing to the proper register page 5.2. the underscored names generated by PBC are only shadows of the actual information defined in the compiler.2.Send whatever is in variable B0 to PortA (register 5) . the compiler not only lacks any type or value information about assembly symbols._B0 . Remember. system variable (such as W0) names are also preceded by underscores (such as _W0). Similarly. Just as underscored symbols have possible conflicts. Thus. any name defined in assembly starting with an underscore has the possibility of conflicting with a PBC generated symbol. Avoiding such names should be reduce problems. If variables are to be shared between assembly and PBC.

) after the ASM command. This routine can then be accessed using the CALL command.Next loop ‘Call assembly routine to shift B0 out PortA ‘Do next count ‘Shift in a byte from PortA to B0 Serout 0.. By convention.Get low order bit of data byte to carry 76 ..) Note that in the assembly example above the variable B0 was preceded by an underscore ( _ ). You might also note that the comment delimiter changed from the single quote (‘) in PicBasic to the semi-colon (. This is to keep lower level label assignments from interfering with PicBasic labels and variables. Unfortunately.PicBasic Compiler normally clears that bit before returning from a library routine. PicBasic labels and variables that are accessed in assembler must be preceded by an underscore. it would make sense to include the assembler code within the PicBasic file. each language’s syntax has a different requirement for this character. But better safe. ‘PicBasic example program with embedded assembly language subroutines loop: For B0 = 0 To 255 Call shiftout Next B0 Call shiftin ‘Count up B0 in a For.N2400.(B0) ‘Send the byte out serially on Pin0 Goto loop End asm _shiftout soloop mov rr ‘Go do it all again ‘Assembly language code follows T0.#8 . If a routine is used by only one particular PicBasic program..Setup temporary variable with bit count _B0 . Larger assembly language routines may be included in your program or in a separate file.

Toggle clock back low djnz T0. ‘PicBasic example program with assembler code included in a separate file 77 .Skip over next instruction PortA. If the assembler routine is destined to be used by several PicBasic programs.1 .Toggle clock high clrb PortA.Setup temporary variable with bit count PortA.PicBasic Compiler jnc solow clrb solow .siloop . but the DONE function performs other housecleaning needed by PBC (resetting the RP0 bit and hitting the Watchdog).Roll bit into result byte B0 T0.1 . Also note that the function terminates by jumping to DONE rather than simply returning. W is not affected by done.Otherwise set data bit high skip .0 .Loop to do all 8 bits done .If data bit is low then skip over next instruction .Loop to do all 8 bits return .Toggle clock high PortA.Go back to main program when done mov setb clrb clc snb stc rl djnz goto T0.1 .Else set carry to on _B0 . Returning would be fine.Toggle clock back low .Set data bit low setb PortA. it makes sense to put it into its own separate text file and simply tell the assembler to INCLUDE this file.0 .soloop .Preset carry to off PortA.Exit through library routine Done ‘End of assembly language code _shiftin siloop endasm Don’t forget to put an END or GOTO or some other mechanism at the end of your PicBasic code to keep the processor from “falling into” your assembler subroutines upon execution.#8 .1 .If no carry then data bit should be low setb PortA.0 .

these files will change and your routines would need to follow the changes.2. These files are automatically included by the compiler. That statement literally appears in memory right behind the controller’s startup code. 7. Placement of In-line Assembly PBC statements execute in order of appearance in the source..3.Next loop Call shiftout ‘Call assembly routine to shift B0 out PortA Next B0 ‘Do next count Call shiftin ‘Shift in a byte from PortA to B0 Serout 0. It appears in memory directly behind the user's last statements.Assembly code will be inserted here endasm The third option for using assembly code with a PicBasic program is to add the code right into the PBH. This is the avenue most fraught with danger. If this is the path of choice.inc” . 78 . This method saves two unneeded jumps and everything normally works out all right.PicBasic Compiler loop: For B0 = 0 To 255 ‘Count up B0 in a For. The first executable line that appears is where the program starts execution.N2400. the END implicit at the end of every PBC program is accomplished by having the code for the END function appear first and unconditionally in the library.INC files.INC or PBL. Also. Similarly. These files are built in a particular manner and caution should be exercised before changing them. be sure to make copies of the original files and only work from those copies. as updates to the compiler are released.(B0) ‘Send the byte out serially on Pin0 Goto loop End asm ‘Go do it all again ‘Assembly language code follows include “shift.

In light of the above explanation.INC for example. If they appear at the tail of the program. are in the 8051 form. This makes it quicker and easier to write the code but also makes it somewhat incompatible with Microchip code that may be scattered through their data books. however. 79 .rp0 . For example. The PICmicro Macro Assembler The PICmicro Macro Assembler (PM) included with the PicBasic Compiler can use “8051 style” mnemonics or the Microchip mnemonics. If you need to terminate your program. execution which "falls off the end" of the PBC statements may mysteriously find themselves unintentionally executing assembly routines. If they appear early in the program. See the PM include files. What should you do? Simple. Unlike a hosted system (such as the PC or the Mac). It is a fairly simple matter to convert these symbols as they are typed in or use your text editor’s or word processor’s search and replace function to change them. there is little reason for an embedded system to terminate. This format includes the register name and bit name into one symbol.4.PicBasic Compiler The tendency of programmers is to place their own library functions written using the inline assembler either before or after their code. for a complete list of these symbol definitions for each PICmicro. 7. place your assembly routines after your PBC code. Thus. this could create some obvious problems. The included header files which define the register and bit names. if the Microchip code says: bsf status. P16F8x.set bit rp0 the equivalent PM code would be: bsf rp0 .2. the assembly routines execute prior to any PBC instructions (some programmers will invariably exploit this feature).set bit rp0 The reason behind this change is that the symbol RP0 is defined to already include the information that it is in the Status register. explicitly place an END statement at the end of your code rather then relying on the implicit END.

Interrupts are not for the faint of heart. They can be very tricky to implement properly. an interrupt could be used to buffer serial input data behind the scenes while the main PicBasic program is off doing something else.PicBasic Compiler The assembler instruction set is listed in the appendix of this document. When an interrupt occurs. The remaining 4 are reserved for CALLs and nested BASIC GOSUBs. For example. You must make sure that your GOSUBs are only nested 3 deep at most with no CALLs within them in order to have a stack location available for the return address. either an I/O pin changing state or a timer timing out and so forth.) The PicBasic Compiler does not directly support interrupts. The first thing this means is that you need an extra location on the PICmicro stack. but that does not mean they cannot be used. (This particular usage would require a PICmicro with a hardware serial port. If enabled (which by default they aren’t).TXT file on disk. Interrupts Interrupts can be a scary and useful way to make your program really difficult to debug. see the PM. Interrupts are triggered by hardware events. but at the same time they can provide very useful functions. an interrupt causes the processor to stop whatever it is doing and jump to a specific routine in the PICmicro called an interrupt handler. 7. which is only 8 deep to begin with. However. This statement alone should be enough to strike fear into the heart of the BASIC programmer. if you just gotta do it. here are some hints on how to go about it. The PicBasic library routines are not reentrant.the interrupt handler must be written in assembly language. The PicBasic library routines can use up to 4 stack locations themselves. If your interrupt handler uses 80 . This means that you cannot execute PicBasic statements from within an interrupt handler . For complete information on the PICmicro Macro Assembler.3. the PICmicro stores the address of the next instruction it was supposed to execute on the stack and jumps to location 4.

If you need to alter any of these. If the processor context is not left exactly the way you found it. location 0.. it knows an interrupt has occurred and it can take the appropriate actions. and you probably will.) as you like by simply not using them in your PicBasic program. the Watchdog Timer could timeout and really make a mess of things. If this code is uncommented.INC in the INC subdirectory. it gets even trickier. The interrupt routine should be as short and fast as you can possibly make it. you must save the current values so that you can restore them before allowing the processor to go back to what it was doing before it was so rudely interrupted. Once you have dealt with the stack issues. . You may use these locations to store W. I1. We have reserved three internal variables strictly for use by an interrupt handler: I0. When the PicBasic program sees this value. If it takes too long to execute.PicBasic Compiler the stack (by doing a Call itself for example). Since you have no idea of what the processor was doing when it was interrupted. the Status flags. it will enable you to insert your interrupt handler at location 4. You cannot tell which variables are in use by the library routines at any given time. you have no idea of the state of the W register. Perhaps the most useful function would be to simply set a PicBasic variable to a particular value when an interrupt occurs. Use a PICmicro with more RAM such as a PIC16F84 for access to the additional locations. A few lines down is a section of code that has been commented out..) If you require more than these variables. B1. Place your assembly language interrupt handler routine after 81 . This of course means that you cannot even safely use the compilers internal variables for storing the processor context. This is where the PICmicro will start executing code on reset. and I2 (Only I0 has a real RAM location on a PIC16C84. PCLATH or even what register page you are pointing to. Near the end of the file is the label Start. you can reserve as many of the user variables (B0. you’ll need to have additional stack space available. or any other register that may need to be altered by the interrupt handler. The interrupt handler itself may be placed in the file PBH. all kinds of subtle bugs and even major system crashes can and will occur. the Status register. This is called saving and restoring the processor context.

Life After 2K When a PicBasic program grows longer than 2K (which is a pretty big program). If it is necessary for a program to be longer than 2K. From this point you are on your own. the PCLATH register must be set before each Call or Goto. 7. the PicBasic Compiler makes no effort to address this problem. See the Microchip PICmicro data books for more information on PCLATH and address sizes. The 2K boundary presents a problem to PICmicro programming in any language. Definitely. your interrupt routine should be able to coexist peacefully with your PicBasic program. definitely refer to the Microchip PICmicro data books for additional information on how to use interrupts. This data is invaluable to your success. problems will occur.PicBasic Compiler the ORG 4. assembly. To get to code outside the 2K boundary. definitely. the . C. or PicBasic. The routine should end with an RETI instruction to return from the interrupt and allow the processor to pick up where it left off in your PicBasic program. PICmicro instructions such as Call and Goto only have enough bits within them to address 2K of program space.ASM file the compiler generates can be “fixed-up” and then assembled after setting PCLATH before and after the appropriate instructions.4. It would probably be best to use memory beyond 2K for large table storage to keep “fixups” to a minimum. In the interest of minimizing program size. They give examples of storing processor context as well as all the necessary information to enable a particular interrupt. If you follow the above suggestions. 82 .

these discussions will help illuminate the differences and possible solutions. It is hoped that if you do encounter problems. Whenever possible. But.good programs don't rely on statement timing. While the results tested well. 8. many PBC instructions (such as GOTO and GOSUB) execute hundreds of times faster than their BASIC Stamp equivalents. The solution is simple .1. Some are due to improvements in code executed directly on the PICmicro rather than via the Stamp chip set. there are always some slight differences. Most programs will compile and execute without error. The following sections discuss the implementation details of PBC programs that might present problems. Some of the I/O commands (TOGGLE and PULSOUT) perform readmodify-write operations directly on the PORT register. 8.2.PicBasic Compiler 8. programs whose timing has been developed empirically may experience problems. it is possible the operation will fail. Digital I/O Unlike the BASIC Stamp. a program should use handshaking and other nontemporal synchronization methods. Execution Speed The largest potential problem shared by both library routines and user code is speed. Without the overhead of reading instructions from the EEPROM. we can never be 100% sure. PBC programs operate directly on the PORT and TRIS registers. statements specifically generating delays (PAUSE. If delays are needed. While this has speed and RAM/ROM size advantages. NAP or SLEEP) should be used. If two such operations are performed too close together and the output is driving an inductive or capacitive load. Compiler / Stamp Differences Every effort has been made to assure that programs compiled by PBC execute as they would on a BASIC Stamp I. 83 . While in many cases this is a benefit. there is one potential drawback. Others are the result of the fact that the BASIC Stamp is a closed system and its internal operations are unknown. just as with all system which promise "compatibility".

BUTTON PBC's BUTTON command requires the programmer to specify an 8-bit variable to store the current repeat count.3. Missing PC Interface Since PBC generated programs run directly on a PICmicro.PicBasic Compiler Suppose. 8. This is a common problem for PICmicro (and other microcontroller) programs and is one of the realities of programming hardware directly. Without the PC to wake the PICmicro from the END statement. And those commands designed for these types of interfacing (SOUND and POT. The lack of a PC interface does introduce some differences. programs using bit variables for the BUTTON command will compile and run. The BUTTON command samples the input only once 84 . but the command will not behave correctly. The faster execution of PBC programs may be a problem for the BUTTON command. It does. it still reads the pin's level as low. The output driver (which is now high) begins to charge the cap. for example. Word variables work fine. Without a PC. however. 8. If the second operation is performed too quickly. The BASIC Stamp will allow the use of any type of variable. although they are wasteful. even though the output driver is high. generate a compiler error when an attempt is made to use BUTTON with a bit variable.4. while PBC parses PBASIC's DEBUG commands. for example) have built-in protection. there is no place to send debugging information. that a speaker is driven though a 10uF cap (just as with the SOUND command). The first command reads the pin's low level and outputs its complement. there is no need for the Stamp's PC interface pins (PCO and PCI). it doesn't generate code. PBC's BUTTON command will also work correctly with word variables. Also suppose the pin is initially low and the programmer is attempting to generate a pulse using TOGGLE statements. In practice. Thus. the second operation will also drive the pin high. it remains in low power mode until /MCLR is lowered or power is cycled. On the Stamp. This problem is not specific to PBC programs. As such. this is not much of a problem.

W6 is still available. PBC programs make use of these instructions and use four levels of this stack. EEPROM storage must be implemented in some other manner. subroutines may still be nested up to four levels deep and the number of GOSUBs is limited only by the PICmicro's code space. 8. To access off-chip non-volatile data storage.7. READ and WRITE The BASIC Stamp allows EEPROM not used for program storage to store non-volatile data. GOSUB/RETURN The Stamp implements subroutines via the GOSUB and RETURN statements. User variable W6 is used by the Stamp as a four nibble stack.6. The PIC16C84. The 14-bit core PICmicros have Call and Return instructions as well as eight level stacks. READ and WRITE commands. with the other four levels being reserved for library routines. 8x and 87x devices have from 64 to 255 bytes of on-chip data EEPROM. Debouncing is achieved by the delay introduced by other Stamp overhead (such as fetching instructions from EEPROM). a BUTTON command which is executed too frequently might not provide as good a "debounce" in PBC programs as it does on the BASIC Stamp. 8.PicBasic Compiler per execution. Thus. Since PBC programs execute directly from the PICmicro's ROM space. PBC programs may use this for EEPROM operations and fully supports PBASIC's EEPROM. RANDOM PBC's RANDOM statement takes any word variable as its parameter. The PIC16F87x devices do not return the device size when location 255 is read. the I2CIN and I2COUT instructions have been added.5. EEPROM. These instructions allow 2-wire communications with serial EEPROMs like Microchip Technology’s 24LC01B. PBASIC programs may have up to 16 GOSUBs and subroutines can be nested up to four levels deep. Thus. The PBC library routine takes the address of the 16-bit word to randomize as 85 . 16CF62x. 8. Thus.

Since PBC doesn't implement the PORT register as a true 16-bit memory location. 8. In the BS1. Ignoring these effects. approximately every 2. 8. Low Power Instructions When the Watchdog Timer time-out wakes a PICmicro from sleep mode. This has been accomplished by replacing the little used rate of 600 baud with 9600 baud. This introduces an average error of about 1 second. This is done while recalibrating the period of the WDT.3 seconds. the granularity of the SLEEP command is determined by the Watchdog Timer period. Similarly. the statement RANDOM PORT will produce a compilation error. For unknown reasons. which is typically 2. The NAP instruction does not disturb the I/O pins. This may be overly optimistic.8. Even without this granularity. execution resumes without disturbing the state of the I/O pins. The WDT is driven by an R/C oscillator and the period varies greatly with temperature.9. Modes of T9600.3 seconds. OT9600 and ON9600 may now be used. N9600. the oscillator is a resonator. 8. when the BASIC Stamp resumes execution after a low power instruction (NAP or SLEEP).10. the Stamp's SLEEP instruction disturbs the I/O pins every WDT time-out period. PBC's SLEEP instructions only disturbs the I/O pins once every 10 minutes. the I/O pins are disturbed for approximately 18 mSec.PicBasic Compiler its parameter. 86 . whose accuracy is +/-1%. SLEEP is only as accurate as the PICmicro's system clock. there is still the larger problem of variability in the PICmicro's Watchdog Timer. 600 baud is no longer available and will cause a compilation error if an attempt is made to use it. SERIN/SEROUT SERIN and SEROUT have been altered to run up to 9600 baud from the previous limit of 2400 baud. First.8% accurate. PBC programs make use of the PICmicro's I/O coherency. SLEEP The Stamp's documentation indicates its SLEEP command is ~99.

an uncalibrated version of SLEEP has been created. To get around potential problems. remain unchanged during and after a SLEEP instruction. All the registers. With all the above said. For the PIC16F84 at 4MHz with the WDT enabled. This is due to the fact that the PIC16C5x family has a lower power-down current consumption than members of the PIC16Cxxx family. PBC's SLEEP draws approximately 47uA. PBC's SLEEP command performs this recalibration every 257 cycles or about once every 10 minutes.38% of the time during the SLEEP command. However. During SLEEP calibration.3 seconds). it has been determined that a calibrated SLEEP command may not work properly on all PICmicros. Microchip specifies a typical operating current of 1. This is done by counting system clocks while waiting for the WDT to time-out. Different devices respond in different ways to this reset. This is more than the current levels claimed by the BASIC Stamp. including PORT direction. Notably the TRIS registers set all the PORT pins to inputs. This results in the PICmicro being active about 0. This version does not cause a device reset so it has no effect on any of the internal registers. Any other PORT directions must be reset by the user program after SLEEP. the PICmicro is reset.PicBasic Compiler To eliminate this error. Using these figures. 87 . actual SLEEP times will no longer be as accurate and will vary dependent on device particulars and temperature.8mA and a power down current of 40uA. Upon reset. This calibrated period is then used to decrement the desired sleep period. It recalibrates for a full WDT period (about 2. the WDT is calibrated in terms of the system clocks. See the data sheets for a particular part for this information. The TRIS state for PORTB is automatically saved and restored by the SLEEP routine. Other registers may also be affected. This keeps SLEEP to within the accuracy of the system clock (ignoring the granularity of the WDT). many registers may be altered.

To enable the previous. calibrated version of SLEEP add the following lines to a PBC program: asm SLEEPCAL = 1 endasm 88 .PicBasic Compiler The uncalibrated version of SLEEP is now the default.

d k f.b f. 0 = w.d f.d k f.literal constant 89 .bit address d .d f. 1 = f f .d k f.d k f.d f.d f.d k f.d f.PicBasic Compiler Appendix A Summary of Microchip Assembly Instruction Set ADDLW ADDWF ANDLW ANDWF BCF BSF BTFSC BTFSS CALL CLRF CLRW CLRWDT COMF DECF DECFSZ GOTO INCF INCFSZ IORLW IORWF MOVF MOVLW MOVWF NOP RETFIE RETLW RETURN RLF RRF SLEEP SUBLW SUBWF SWAPF XORLW XORWF k f.d f.register file address k .b f.d b .b k f f.d k f k f.d f.b f.destination.

PicBasic Compiler 90 .

Box 7532 Colorado Springs CO 80933-7532 (719) 520-5323 (719) 520-1867 fax http://www. Chandler AZ 85224-6199 (602) 786-7200 (602) 899-9210 fax http://www. Chandler Blvd.melabs.com PICmicro data sheets. CD-ROMs and literature may be obtained from: Microchip Technology Inc.com email:support@melabs.microchip. 2355 W. Inc.com 91 .com email:literature@microchip.PicBasic Compiler Appendix B Contact Information Technical support and sales may be reached at: microEngineering Labs.

GOODWILL. REPROGRAMMING OR REPRODUCING ANY DATA USED WITH THE COMPANY'S PRODUCTS.READ THE FOLLOWING TERMS AND CONDITIONS CAREFULLY BEFORE OPENING THIS PACKAGE. INDIRECT. and the Company retains all right. Licensee owns only the enclosed disk on which the software is recorded or fixed. EXPRESS OR IMPLIED. which is part of the price Licensee paid for this product. INCLUDING WITHOUT LIMITATION. microEngineering Labs. DOWNTIME. the Company grants Licensee a nonexclusive right to use and display the copy of the enclosed software on a single computer at a single location. Licensee is agreeing to be bound by these terms and conditions. Software License In consideration of Licensee's payment of the license fee. Disclaimer of Liability THE COMPANY DISCLAIMS ALL WARRANTIES. SUPPLIERS OR CONTRACTORS BE LIABLE FOR ANY INCIDENTAL. SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN CONNECTION WITH LICENSE GRANTED UNDER THIS AGREEMENT. Copies may only be made for archival or backup purposes. LOST PROFITS. AGENTS. nor may copies be given to anyone else. Licensee may not network the software or otherwise use it on more than one computer terminal at the same time. ("the Company") is willing to license the enclosed software to the purchaser of the software ("Licensee") only on the condition that Licensee accepts all of the terms and conditions set forth below. DAMAGE TO OR REPLACEMENT OF EQUIPMENT OR PROPERTY. The enclosed software is licensed only to the Licensee and may not be transferred to anyone else. INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE AND THE IMPLIED WARRANTY OF MERCHANTABILITY. IN NO EVENT SHALL THE COMPANY OR ITS EMPLOYEES. Any violation of the terms and conditions of this software license shall result in the immediate termination of the license. Inc. . title and ownership (including the copyright) to the software recorded on the original disk copy and all subsequent copies of the software. By opening this sealed package. and Licensee's agreement to abide by the terms and conditions on this page. OR ANY COSTS FOR RECOVERING.

Sign up to vote on this title
UsefulNot useful