Pic Basic Pro Manual
Pic Basic Pro Manual
Pic Basic Pro Manual
COPYRIGHT NOTICE
This manual describes the use and operation of the PICBASIC PRO™
Compiler from microEngineering Labs, Inc. Use of the PICBASIC PRO
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.
TRADEMARKS
1/08
PICBASIC PRO Compiler
TABLE OF CONTENTS
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. The PIC® MCUs . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2. About This Manual . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3. Sample Programs . . . . . . . . . . . . . . . . . . . . . . . . . 3
2. Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1. Software Installation . . . . . . . . . . . . . . . . . . . . . . . 5
2.2. Your First Program . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3. Program That MCU . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4. It’s Alive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5. I’ve Got Troubles . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.5.1. PIC® MCU Specific Issues . . . . . . . . . . . . . . . . 10
2.5.2. PICBASIC and BASIC Stamp Compatiblity . . . 13
2.5.3. Code Crosses Page Boundary Messages . . . . 13
2.5.4. Out of Memory Errors . . . . . . . . . . . . . . . . . . . . 13
2.6. Coding Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.6.1. Comments . . . . . . . . . . . . . . . . . . . . . . 13
2.6.2. Pin and Variable Names . . . . . . . . . . . 14
2.6.3. Labels . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.6.4. GOTO . . . . . . . . . . . . . . . . . . . . . . . . . 15
i
PICBASIC PRO Compiler
4.6. Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.7. Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.8. Numeric Constants . . . . . . . . . . . . . . . . . . . . . . . 26
4.9. String Constants . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.10. Ports and Other Registers . . . . . . . . . . . . . . . . . 27
4.11. Pins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.12. Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.13. Multi-statement Lines . . . . . . . . . . . . . . . . . . . . 30
4.14. Line-extension Character . . . . . . . . . . . . . . . . . 30
4.15. INCLUDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.16. DEFINE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.17. Math Operators . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.17.1. Multiplication . . . . . . . . . . . . . . . . . . . 34
4.17.2. Division . . . . . . . . . . . . . . . . . . . . . . . 35
4.17.3. Shift . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.17.4. ABS . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.17.5. COS . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.17.6. DCD . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.17.7. DIG . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.17.8. DIV32 . . . . . . . . . . . . . . . . . . . . . . . . 37
4.17.9. MAX and MIN . . . . . . . . . . . . . . . . . . 38
4.17.10. NCD . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.17.11. REV . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.17.12. SIN . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.17.13. SQR . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.17.14. Bitwise Operators . . . . . . . . . . . . . . 39
4.18. Comparison Operators . . . . . . . . . . . . . . . . . . . 40
4.19. Logical Operators . . . . . . . . . . . . . . . . . . . . . . . 40
ii
PICBASIC PRO Compiler
5.14. DISABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.15. DISABLE DEBUG . . . . . . . . . . . . . . . . . . . . . . . 61
5.16. DISABLE INTERRUPT . . . . . . . . . . . . . . . . . . . 62
5.17. DTMFOUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.18. EEPROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.19. ENABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.20. ENABLE DEBUG . . . . . . . . . . . . . . . . . . . . . . . 66
5.21. ENABLE INTERRUPT . . . . . . . . . . . . . . . . . . . . 67
5.22. END . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.23. ERASECODE . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.24. FOR..NEXT . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.25. FREQOUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.26. GOSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.27. GOTO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.28. HIGH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.29. HPWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.30. HSERIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.31. HSERIN2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.32. HSEROUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.33. HSEROUT2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.34. I2CREAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.35. I2CWRITE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.36. IF..THEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
5.37. INPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
5.38. LCDIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.39. LCDOUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
5.40. {LET} . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
5.41. LOOKDOWN . . . . . . . . . . . . . . . . . . . . . . . . . . 100
5.42. LOOKDOWN2 . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.43. LOOKUP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
5.44. LOOKUP2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
5.45. LOW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
5.46. NAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.47. ON DEBUG . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
5.48. ON INTERRUPT . . . . . . . . . . . . . . . . . . . . . . . 107
5.49. OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.50. OWIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
5.51. OWOUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
5.52. PAUSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
5.53. PAUSEUS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
5.54. PEEK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
5.55. PEEKCODE . . . . . . . . . . . . . . . . . . . . . . . . . . 115
5.56. POKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
iii
PICBASIC PRO Compiler
iv
PICBASIC PRO Compiler
9. Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
9.1. Interrupts in General . . . . . . . . . . . . . . . . . . . . . 183
9.2. Interrupts in BASIC . . . . . . . . . . . . . . . . . . . . . . 184
9.3. Interrupts in Assembler . . . . . . . . . . . . . . . . . . . 186
v
PICBASIC PRO Compiler
Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Serin2/Serout2 Mode Examples . . . . . . . . . . . . . . . . 199
Appendix B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Appendix D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
ASCII Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Appendix E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Contact Information . . . . . . . . . . . . . . . . . . . . . . . . . . 209
vi
PICBASIC PRO Compiler
1. Introduction
The PICBASIC PRO™ Compiler (or PBP) makes it even quicker and
easier for you to program Microchip Technology’s powerful PIC®
microcontrollers (MCUs). The English-like BASIC language is much
easier to read and write than assembly language.
The PICBASIC PRO Compiler is “BASIC Stamp II like” and has most of
the libraries and functions of both the BASIC Stamp I and II. Being a true
compiler, programs execute much faster and may be longer than their
Stamp equivalents.
PBP is not quite as compatible with the BASIC Stamps as our original
PICBASIC™ Compiler is with the BS1. Decisions were made that we
hope improve the language overall. One of these was to add a real
IF..THEN..ELSE..ENDIF instead of the IF..THEN(GOTO) of the
Stamps. These differences are spelled out later in this manual.
The current version of the PICBASIC PRO Compiler supports most of the
Microchip Technology PIC MCUs, including the 12-bit core, 14-bit core
and both 16-bit core series, the PIC17Cxxx and PIC18Xxxxx devices, as
well as the Micromint PicStics. Limited support has been added for PIC
MCUs based on the original 12-bit core. Support is limited as the 12-bit
core PIC MCUs have a limited set of resources including a smaller stack
and smaller code page size. See the README.TXT file for the very latest
PIC MCU support list.
For general purpose PIC MCU development using the PICBASIC PRO
Compiler, the PIC12F683, 16F690, 16F88, 16F876A, 16F877A, 18F2620
1
PICBASIC PRO Compiler
By using a flash PIC MCU for initial program testing, the debugging
process may be sped along. Once the main routines of a program are
operating satisfactorily, a PIC MCU with more capabilities or expanded
features of the compiler may be utilized.
While many PIC MCU features will be discussed in this manual, for full
PIC MCU information it is necessary to obtain the appropriate PIC MCU
data sheets or the CD-ROM from Microchip Technology. Refer to
Appendix F for contact information.
The next section of this manual covers installing the PICBASIC PRO
Compiler and writing your first program. Following is a section that
describes different options for compiling programs.
2
PICBASIC PRO Compiler
Example programs to help get you started can be found in the SAMPLES
subdirectory. Additional example programs can be found in the sample
programs section of the microEngineering Labs, Inc. web site.
3
PICBASIC PRO Compiler
4
PICBASIC PRO Compiler
2. Getting Started
The PICBASIC PRO Compiler files are compressed into a setup file on
the included disk. They must be installed before use.
To install the software, execute SETUP.EXE on the disk and follow the
setup instructions presented.
For operation of the PICBASIC PRO Compiler you will use the included
IDE or a text editor or word processor for creation of your program source
file, some sort of PIC MCU programmer such as our EPIC
Programmer™, melabs Serial Programmer or melabs U2 Programmer,
and the PICBASIC PRO Compiler itself. Of course you also need a PC
to run it all on.
First, start the included or one of the other available IDEs/editors. Select
the PIC MCU you intend to use from the IDE’s drop-down list. Next,
create the BASIC source file for the program or open one of the BASIC
source files included with PBP. The source file name usually (but isn’t
required to) ends with the extension .BAS.
The text file that is created must be pure ASCII text. It must not contain
any special codes that might be inserted by word processors for their own
purposes. You are usually given the option of saving the file as pure
DOS or ASCII text by most word processors.
The following program provides a good first test of a PIC MCU in the real
world. You may type it in or you can simply copy it from the SAMPLES
subdirectory included with the PICBASIC PRO Compiler. The file is
named BLINK.BAS. The BASIC source file should be created in or
moved to the same directory where the PBP.EXE file is located.
5
PICBASIC PRO Compiler
Once you are satisfied that the program you have written will work
flawlessly, you can execute the PICBASIC PRO Compiler by clicking on
the IDE’s build or compile button. If you are using DOS, enter PBP
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:
PBP blink
6
PICBASIC PRO Compiler
There are two steps left - putting your compiled program into the PIC
microcontroller and testing it.
If you are using the EPIC Programmer, hook it to the PC parallel printer
port using a DB25 male to DB25 female printer extension cable.
If you are using the melabs Serial Programmer, hook it to the PC serial
port using a DB9 male to DB9 female serial cable or hook it to the USB
port using a USB to serial adapter.
If you are using the melabs U2 Programmer, plug it into the PC USB port
using a USB cable.
Plug the AC adapter into the wall and then into the programmer (or attach
2 fresh 9-volt batteries to the EPIC Programmer and connect the “Batt
ON” jumper. Using an AC adapter instead of batteries is highly
recommended.) A separate power supply is not required for the melabs
U2 Programmer.
7
PICBASIC PRO Compiler
Once the file has been loaded, you can look at the Code or Memory
window to see your PIC MCU 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 PRO programs.
Most importantly, Code Protect must be OFF when programming any
windowed (JW) PIC MCUs. You may not be able to erase a windowed
PIC MCU 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 PIC MCU into the
programming socket and click on Program. The PIC MCU will first be
checked to make sure it is blank and then your code will be programmed
into it.
The sample schematic below gives you an idea of the few things that
need to be connected to the PIC MCU 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.
8
PICBASIC PRO Compiler
Build and double check this simple circuit on a protoboard and plug in the
PIC MCU you just programmed. Our line of PICPROTO™ prototyping
boards is perfect for this kind of thing.
Connect a power supply. Your PIC MCU 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 PIC MCU.
From these simple beginnings, you can create your own world-
conquering application.
The most common problems with getting PIC MCUs running involve
making sure the few external components are of the appropriate value
and properly connected to the PIC MCU. 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
PIC MCU will work but usually it won’t. The PIC MCU has an on-chip
power-on-reset circuit so in general just an external pull-up resistor is
adequate. But in some cases the PIC MCU may not power up properly
and an external circuit may be necessary. See the Microchip 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 by 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 PIC MCUs. 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 PIC MCU itself
consumes very little power, the power supply must be filtered fairly well.
If the PIC MCU is controlling devices that pull a lot of current from your
power supply, as they turn on and off they can put enough of a glitch on
the supply lines to cause the PIC MCU 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 PIC
MCU to lose its mind.
9
PICBASIC PRO Compiler
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.
It is imperative that you read the Microchip data sheet for the PIC
MCU device you are using. Some devices have features that can
interfere with expected pin operations. Many PIC MCUs have analog
comparators on PORTA or another port. 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 line:
CMCON = 7
The register names of some PIC MCUs may be different than the
examples above (or below). Be sure to check the Microchip data sheet
for the device you are using so that you can choose the appropriate
register name.
Any PIC MCU with analog inputs, such as the PIC16C7xx, PIC16F87x
and PIC12C67x series devices, will come up in analog mode. You must
set them to digital if that is how you intend to use them:
ADCON1 = 7
For many of the PIC MCUs, including the PIC12F675 and 16F676, a
different register must be set instead:
ANSEL = 0
While these settings work for many devices, you will need to check the
data sheet for the specific device to verify the exact settings.
10
PICBASIC PRO Compiler
All of the PIC MCU pins are set to inputs on power-up. If you need a pin
to be an output, set it to an output before you use it, or use a PICBASIC
PRO command that does it for you. Once again, review the PIC MCU
data sheets to become familiar with the idiosyncrasies of a particular part.
The name of the port pins on most 8-pin PIC12X devices is GPIO. The
name for the TRIS register is TRISIO.
GPIO.0 = 1
TRISIO = %101010
OPTION_REG.5 = 0
11
PICBASIC PRO Compiler
devices with on-chip I2C interfaced serial EEPROM like the PIC12CE51x,
12CE67x and 16CE62x parts. Use the I2CREAD and I2CWRITE
instructions instead.
Add one of these 2 DEFINEs near the beginning of the PICBASIC PRO
program to perform the setting of OSCCAL.
The $a0 is merely an example. The part would need to be read before it
is erased to obtain the actual OSCCAL value for that particular device.
PICBASIC PRO will automatically load the OSCCAL value for the 12-bit
core devices, if it is available. It is unnecessary to use the above
DEFINEs with these devices.
Some PIC MCUs with internal oscillators, like the PIC16F88, include an
oscillator control register that allows the selection of the oscillator
frequency. On power-up or reset, this register may default to a slow
oscillator setting like 32kHz. This slow speed may make it look as if the
program is not running at all. To set the oscillator to a faster frequency
such as 4MHz, set:
Please see the Microchip data sheets for more information on OSCCON
and any of the other PIC MCU registers.
12
PICBASIC PRO Compiler
Many PIC MCUs contain code space memory that is segmented into 512,
2K or 8K word pages. As large files are compiled and then assembled,
they may start to use more than the first page. As each page is used,
PM, the assembler, will issue a message that the code is crossing a
particular boundary. This is normal and no cause for alarm. PBP will
make sure to take care of most of the issues for you.
The only thing that you must be aware of is the BRANCH instruction. If a
BRANCH tries to access a label on the other side of a boundary, it will not
work properly. BRANCHL should be used instead. It can address labels
in any code page.
Compiling large PICBASIC PRO source code files can tax the memory of
the PC running the compiler. If an Out of Memory error is issued and the
FILES and BUFFERS are set as recommended, an alternate version of
PBP can be used. PBPW.EXE has been compiled to make use of all of
the memory available to Windows 95, 98, ME, NT, 2000, XP and Vista.
You must, of course, be running in a DOS shell from one of these 32-bit
Windows environments or be within Microchip's MPLAB or another
Windows IDE. To execute the Windows version from the DOS command
line, simply substitute PBPW for PBP.
PBPW blink
2.6.1. Comments
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 PIC MCU 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 like “Turn on the Battery Low LED” might be a lot more useful.
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:
2.6.3. Labels
14
PICBASIC PRO Compiler
least a hint of its function with the label, and then follow up with a
comment.
2.6.4. GOTO
Try not to use too many GOTOs. While GOTOs may be 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.
15
PICBASIC PRO Compiler
16
PICBASIC PRO Compiler
3.1. Usage
The PICBASIC PRO Compiler can be invoked from the DOS command
line using one of the following command formats:
PBP is the DOS version of the compiler. PBPW is the Windows version
of the compiler and can take advantage of all the PC’s memory. PBPL is
the long version of the compiler and can use 32-bit variables, as well as
all of the PC’s memory under Windows. PBPL can only be used with the
PIC18 devices.
Zero or more Options can be used to modify the manner in which PBP
compiles the specified file. Options begin with either a minus ( - ) or a
forward slash ( / ). The character following the minus or slash 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 and no spaces may occur within an Option.
Multiple Options may be used at the same time. For example the
command line:
The first item not starting with a minus is assumed to be the Filename.
If no extension is specified, 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 PBP are placed in the
current directory.
17
PICBASIC PRO Compiler
3.2. Options
Option Description
A Use a different Assembler
C Insert source lines as Comments into assembler file
E Output errors to a file
H(?) Display Help screen
L Use a different Library file
O Pass Option to assembler
P Specify target Processor
S Skip execution of assembler when done
V Verbose mode
Z Add source level debugging information
3.2.1. Option -A
PBP has the capability to use either PM, which is included with PBP, or
Microchip’s MPASMWIN as its assembler. When using MPASMWIN,
PBPW or PBPL must be specified instead of PBP. PBPW is the
Windows executable version of PBP. To specify MPASMWIN as the
assembler, use -ampasmwin on the command line:
3.2.2. Option -C
The -C option causes PBP to insert the PICBASIC PRO source file lines
as comments into the assembly language source file. This can be useful
18
PICBASIC PRO Compiler
PBP -c filename
3.2.3. Option -E
The -E option causes PBP to send all the errors to a file, filename.er.
PBP -e filename
3.2.4. Option -H or -?
The -H or -?option causes PBP to display a brief help screen. This help
screen is also displayed if no option and filename is specified on the
command line.
3.2.5. Option -L
The -L option lets you select the library used by PICBASIC PRO. This
option is generally unnecessary as the default library file is set in a
configuration file for each microcontroller. For more information on
PICBASIC PRO libraries, see the advanced sections later in this manual.
This example tells PBP to compile filename using the PicStic2 library.
3.2.6. Option -O
19
PICBASIC PRO Compiler
3.2.7. Option -P
If not told otherwise, PBP compiles programs for the PIC16F84. If the
program requires a different processor as its target, its name must be
specified on the command line use the -P option.
For example, if the desired target processor for the PBP program is a
PIC16F877, the command line should look something like the following:
3.2.8. Option -S
Since -S prevents the assembler from being invoked, options that are
simply passed to the assembler using the -O command line switch are
effectively ignored.
PBP -s filename
3.2.9. Option -V
PBP -v filename
3.2.10. Option -Z
The -Z option tells PBPW to add source level simulation and debugging
information to the files that are generated during compilation. For an
example of how to use this within MPLAB, see the MPLAB.TXT file.
PBPW -z filename
20
PICBASIC PRO Compiler
4.1. Identifiers
An identifier is, quite simply, a name. Identifiers are used in PBP for line
labels and variable 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, PBP only
recognizes the first 31.
4.3. Variables
21
PICBASIC PRO Compiler
The size and range of each variable type is detailed in the following table:
As the table shows, bit-, byte- and word-sized variables are always
unsigned, i.e. positive numbers. Long-sized variables, which are only
available in PBPL, are always signed, twos-complement numbers,
including positive and negative values.
Include “bs1defs.bas”
or
Include “bs2defs.bas”
near the top of the PICBASIC PRO program. These files contain
numerous VAR statements that create all of the BASIC Stamp variables
and pin definitions.
22
PICBASIC PRO Compiler
4.4. Aliases
VAR can also be used to create an alias (another name) for a variable.
This is most useful for accessing the innards of a variable.
b = w0.BYTE0
OPTION_REG.7 = 0
Modifier Description
BIT0 or 0 Create alias to bit 0 of byte or word
BIT1 or 1 Create alias to bit 1 of byte or word
BIT2 or 2 Create alias to bit 2 of byte or word
BIT3 or 3 Create alias to bit 3 of byte or word
BIT4 or 4 Create alias to bit 4 of byte or word
BIT5 or 5 Create alias to bit 5 of byte or word
BIT6 or 6 Create alias to bit 6 of byte or word
BIT7 or 7 Create alias to bit 7 of byte or word
BIT8 or 8 Create alias to bit 8 of word or long
BIT9 or 9 Create alias to bit 9 of word or long
23
PICBASIC PRO Compiler
24
PICBASIC PRO Compiler
4.5. Arrays
The first array location is element 0. In the fish array defined above,
the elements are numbered fish[0] to fish[7] yielding 8 elements in
total.
Because of the way arrays are allocated in memory, there are size limits
for each type:
Arrays must fit entirely within one RAM bank on 12-bit, 14-bit or
PIC17Cxxx devices. Arrays may span banks on PIC18Xxxxx devices.
On PIC18Xxxxx devices, byte, word and long-sized arrays are only
limited in length by the amount of available memory. The compiler will
assure that arrays, as well as simple variables, will fit in memory before
successfully compiling.
25
PICBASIC PRO Compiler
4.6. Symbols
4.7. Constants
mice CON 3
traps CON mice * 1000
26
PICBASIC PRO Compiler
PBP 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 PBP commands have this handling
built-in).
All of the PIC MCU registers, including the ports, can be accessed just
like any other byte-sized variable in PICBASIC PRO. This means that
they can be read from, written to or used in equations directly:
For compatibility with the BASIC Stamp, pins used in PICBASIC PRO
Compiler commands may also be referred to by a number, 0 - 15. This
number references different physical pins on the PIC MCU hardware
ports dependent on how many pins the microcontroller has.
27
PICBASIC PRO Compiler
If a port does not have 8 pins, such as PORTA, only the pin numbers that
exist may be used, i.e. 8 - 12. Using pin numbers 13 - 15 will have no
discernable effect.
This pin number, 0 - 15, has nothing to do with the physical pin number of
a PIC MCU. Depending on the particular PIC MCU, pin number 0 could
be physical pin 6, 21 or 33, but in each case it maps to PORTB.0 (or
GPIO.0 for 8-pin devices, or PORTA.0 for 14 and 20-pin devices, or
PORTC.0 for a PIC14000).
The pin names (i.e. Pin0) are not automatically included in your
program. In most cases, you would define pin names as you see fit using
the VAR command:
Include “bs1defs.bas”
or
28
PICBASIC PRO Compiler
Include “bs2defs.bas”
BS1DEFS.BAS defines Pins, B0-B13, W0-W6 and most of the other BS1
pin and variable names.
PORTL and PORTH are also defined in PBP. PORTL encompasses Pin0
- Pin7 and PORTH encompasses Pin8 - Pin15.
When a PIC MCU powers-up, all of the pins are set to input. To use a
pin as an output, the pin or port must be set to an output or a command
must be used that automatically sets a pin to an output.
To set a pin or port to an output (or input), set its TRIS register. Setting a
TRIS bit to 0 makes its corresponding port pin an output. Setting a TRIS
bit to 1 makes its corresponding port pin an input. For example:
TRISC = %10101010
Sets all the even pins on PORTC to outputs, and the odd pins to inputs.
Individual bit directions may be set in the same manner.
TRISA.0 = 0
sets PORTA, pin 0 to an output. All of the other pin directions on PORTA
are unchanged.
The BASIC Stamp variable names Dirs, Dirh, Dirl and Dir0-Dir15
are not defined and must not be used with the PICBASIC PRO Compiler.
TRIS must be used instead, but has the opposite state of Dirs.
29
PICBASIC PRO Compiler
Do this instead:
4.12. Comments
A PBP comment starts with either the REM keyword, the single quote (‘)
or the semi-colon (;). All following characters on this line are ignored.
W2 = W0
W0 = W1
W1 = W2
W2 = W0 : W0 = W1 : W1 = W2
This does not, however, change the size of the generated code.
The maximum number of characters that may appear on one PBP line is
256. Longer statements may be extended to the next line using the line-
extension character ( _ ) at the end of each line to be continued.
Branch B0,[label0,label1,label2,_
label3,label4]
30
PICBASIC PRO Compiler
4.15. INCLUDE
The included file’s source code lines are inserted into the program
exactly where the INCLUDE is placed.
INCLUDE “modedefs.bas”
4.16. DEFINE
Some elements, like the clock oscillator frequency and the LCD pin
locations, are predefined in PBP. DEFINE allows a PBP program to
change these definitions, if desired.
These definitions must be in all upper case, exactly as shown. If not, the
compiler may not recognize them. No error message will be produced for
DEFINEs the compiler does not recognize.
Unlike the BASIC Stamp, the PICBASIC PRO Compiler performs all
math and comparison operations in full hierarchal order. This means that
there is precedence to the operators. Multiplies and divides are
performed before adds and subtracts, for example. To ensure the
31
PICBASIC PRO Compiler
operations are carried out in the order you would like, use parenthesis to
group the operations:
A = (B + C) * (D - E)
All math operations when compiling with PBP and PBPW are unsigned
and performed with 16-bit precision. Math operations for PBPL use 32-
bit precision.
32
PICBASIC PRO Compiler
33
PICBASIC PRO Compiler
4.17.1. Multiplication
B0 = 4
L0 = B0 * -1 ‘ Result is -4 in L0
W0 = B0 * -1 ‘ Result is 65,532 in W0
There are two special multiplication operators that allow large result
values to be handled in a special way. These operators ignore some of
the least-significant bytes of the result and return higher order bytes
instead. With PBP and PBPW, this allows you to work (in a limited way)
with 32-bit multiplication results. With PBPL, the top 32 bits of a 48-bit
result are available.
The '*/' operator discards the least-significant byte of the result (byte0),
and returns the 4 higher bytes to the result variable. If the result variable
is a word or byte, the value will be truncated to fit.
A simple way to think about '*/' is that it shifts the result 8 places to the
right, resulting in an automatic division by 256. (This does not hold true if
34
PICBASIC PRO Compiler
If you wished to convert miles to kilometers, for example, you would need
to multiply by a constant 1.6. PBP's integer math won't allow you to write
"1.6" in an equation, but you can use '*/' to accomplish the same result:
The '**' operator is similar, but ignores two bytes instead of one. When
using PBPL with long variable types, it returns byte2 through byte5 of the
48-bit result value. This gives a result that is shifted 16 places to the
right, an inherent divide by 65536.
4.17.2. Division
PBP and PBPW perform unsigned 16-bit x 16-bit division. The '/'
operator returns the 16-bit result.
PBPL performs signed 32-bit x 32-bit division. The '/' operator returns
the 32-bit result.
35
PICBASIC PRO Compiler
B0 = 4
L0 = B0 * -1 ‘ Result is -4 in L0
W0 = B0 * -1 ‘ Result is 65,532 in W0
B0 = 23
L0 = B0 // -4 ‘ Result is -3 in L0
W0 = B0 // -4 ‘ Result is 65,533 in W0
4.17.3. Shift
The '<<' and '>>' operators shift a value left or right, respectively, 0 to 31
times. The newly shifted-in bits are set to 0.
4.17.4. ABS
ABS returns the absolute value of a number. If a byte is greater than 127
(high bit set), ABS will return 256 - value. If a word is greater than 32767
(high bit set), ABS will return 65536 - value. If a long is negative, ABS will
return 4294967296 - value.
B1 = ABS B0
4.17.5. COS
COS returns the 8-bit cosine of a value. The result is in two’s complement
form (i.e. -127 to 127). It uses a quarter-wave lookup table to find the
result. Cosine starts with a value in binary radians, 0 to 255, as opposed
to the usual 0 to 359 degrees.
B1 = COS B0
36
PICBASIC PRO Compiler
4.17.6. DCD
DCD returns the decoded value of a bit number. It changes a bit number
(0 - 31) into a binary number with only that bit set to 1. All other bits are
set to 0.
4.17.7. DIG
DIG returns the value of a decimal digit. Simply tell it the digit number (0
- 9 with 0 being the rightmost digit) you would like the value of, and voila.
4.17.8. DIV32
37
PICBASIC PRO Compiler
a Var Word
b Var Word
c Var Word
dummy Var Word
b = 500
c = 1000
This program assigns b the value 500 and c the value 1000. When
multiplied together, the result would be 500000. This number exceeds
the 16-bit word size of a variable (65535). So the dummy variable
contains only the lower 16 bits of the result. In any case, it is not used by
the DIV32 function. DIV32 uses variables internal to the compiler as the
operands.
MAX and MIN returns the maximum and minimum, respectively, of two
numbers. It is usually used to limit numbers to a value.
38
PICBASIC PRO Compiler
4.17.10. NCD
NCD returns the priority encoded bit number (1 - 32) of a value. It is used
to find the highest bit set in a value. It returns 0 if no bit is set.
4.17.11. REV
REV reverses the order of the lowest bits in a value. The number of bits
to be reversed is from 1 to 32.
4.17.12. SIN
SIN returns the 8-bit sine of a value. The result is in two’s complement
form (i.e. -127 to 127). It uses a quarter-wave lookup table to find the
result. Sine starts with a value in binary radians, 0 to 255, as opposed to
the usual 0 to 359 degrees.
B1 = SIN B0
4.17.13. SQR
SQR returns the square root of a value. Since PICBASIC PRO only works
with integers, the result will always be an 8-bit integer (16-bits for PBPL)
no larger than the actual result.
Bitwise operators act on each bit of a value in boolean fashion. They can
be used to isolate bits or add bits into a value.
39
PICBASIC PRO Compiler
40
PICBASIC PRO Compiler
41
PICBASIC PRO Compiler
42
PICBASIC PRO Compiler
43
PICBASIC PRO Compiler
5.1. @
@ Statement
i Var Byte
rollme Var Byte
For i = 1 To 4
@ rlf _rollme, F ; Rotate byte left once
Next i
@ Include “fp.asm”
44
PICBASIC PRO Compiler
5.2. ADCIN
ADCIN Channel,Var
Read the on-chip analog to digital converter Channel and store the
result in Var. While the ADC registers can be accessed directly, ADCIN
makes the process a little easier.
Before ADCIN can be used, the appropriate TRIS register must be set to
make the desired pins inputs. The ADCON, ANCON and/or ANSEL
registers must also be set to assign the desired pins to analog inputs and
in some cases to set the result format and clock source (set the clock
source the same as the DEFINE specified for it, below). See the
Microchip data sheets for more information on these registers and things
like the clock source and how to set them for the specific device. Note:
The PIC14000 ADC is not compatible with the ADCIN instruction.
Depending on the device, it may have an 8-, 10- or 12-bit ADC. For
many PIC MCUs, the high bit of ADCON0 or ADCON1 controls whether
the result is left or right justified. In most cases, 8-bit results should be
left justified (ADCON1.7 = 0) and 10- and 12-bit results should be right
justified (ADCON1.7 = 1).
Several DEFINEs may also be used. The defaults are shown below:
45
PICBASIC PRO Compiler
5.3. ASM..ENDASM
ASM
ENDASM
The ASM and ENDASM instructions tells PBP that the code between these
two lines is in assembly language and should not be interpreted as
PICBASIC PRO statements. You can use these two instructions to mix
assembly language code with PICBASIC PRO statements.
ASM resets the register page to 0. You must ensure that the register
page is reset to 0 before ENDASM, if the assembly language code has
altered it.
ASM
bsf PORTA, 0 ; Set bit 0 on PORTA
bcf PORTB, 0 ; Clear bit 0 on PORTB
ENDASM
46
PICBASIC PRO Compiler
5.4. BRANCH
BRANCH Index,[Label{,Label...}]
For 12- and 14-bit core and PIC17Cxxx devices, Label must be in the
same code page as the BRANCH instruction. If you cannot be sure they
will be in the same code page, use BRANCHL below.
BRANCH B4,[dog,cat,fish]
‘ Same as:
‘ If B4=0 Then dog (goto dog)
‘ If B4=1 Then cat (goto cat)
‘ If B4=2 Then fish (goto fish)
47
PICBASIC PRO Compiler
5.5. BRANCHL
BRANCHL Index,[Label{,Label...}]
BRANCHL B4,[dog,cat,fish]
‘ Same as:
‘ If B4=0 Then dog (goto dog)
‘ If B4=1 Then cat (goto cat)
‘ If B4=2 Then fish (goto fish)
48
PICBASIC PRO Compiler
5.6. BUTTON
BUTTON Pin,Down,Delay,Rate,BVar,Action,Label
10K
I/O I/O
10K
49
PICBASIC PRO Compiler
Example program:
50
PICBASIC PRO Compiler
5.7. CALL
CALL Label
51
PICBASIC PRO Compiler
5.8. CLEAR
CLEAR
CLEAR zeroes all the RAM registers in each bank. This will set all
variables, including the internal system variables (but not PIC MCU
hardware registers) to zero. This is not automatically done when a PBP
program starts as it is on a BASIC Stamp. In general, the variables
should be initialized in the program to an appropriate state rather than
using CLEAR.
52
PICBASIC PRO Compiler
5.9. CLEARWDT
CLEARWDT
The Watchdog Timer is used in conjunction with the SLEEP and NAP
instructions to wake the PIC MCU after a certain period of time.
Assembler instructions (clrwdt) to keep the Watchdog Timer from timing
out under normal circumstances and resetting the PIC MCU are
automatically inserted at appropriate places throughout the program.
53
PICBASIC PRO Compiler
5.10. COUNT
COUNT Pin,Period,Var
Count the number of pulses that occur on Pin during the Period and
stores the result in Var. Pin is automatically made an input. Pin may
be a constant, 0-15, or a variable that contains a number 0-15 (e.g. B0)
or a pin name (e.g. PORTA.0).
COUNT checks the state of Pin in a tight loop and counts the low to high
transitions. With a 4MHz oscillator it checks the pin state every 20us.
With a 20MHz oscillator it checks the pin state every 4us. From this, it
can be determined that the highest frequency of pulses that can be
counted is 25KHz with a 4MHz oscillator and 125KHz with a 20MHz
oscillator, if the frequency has a 50% duty cycle (the high time is the
same as the low time).
54
PICBASIC PRO Compiler
5.11. DATA
DATA only works with microcontrollers with on-chip EEPROM such as the
PIC12F683, PIC16F84 and the PIC16F87x series. It will not work on
devices with on-chip I2C interfaced serial EEPROM like the 12CE67x and
16CE62x parts. Since EEPROM is non-volatile memory, the data will
remain intact even if the power is turned off.
The data is stored in the EEPROM space only once at the time the
microcontroller is programmed, not each time the program is run. WRITE
can be used to set the values of the on-chip EEPROM at runtime. READ
is used to retrieve these stored DATA values at runtime.
55
PICBASIC PRO Compiler
5.12. DEBUG
DEBUG Item{,Item...}
If a pound sign (#) precedes an Item, the ASCII representation for each
digit is sent serially. DEBUG (on all devices except 12-bit core) also
supports the same data modifiers as SEROUT2. Refer to the section on
SEROUT2 for this information.
Modifier Operation
{I}{S}BIN{1..32} Send binary digits
{I}{S}DEC{1..10} Send decimal digits
{I}{S}HEX{1..8} Send hexadecimal digits
REP c\n Send character c repeated n times
STR ArrayVar{\n} Send string of n characters
The serial pin and baud rate are specified using DEFINEs:
56
PICBASIC PRO Compiler
DB9 DB25
1K
Pin RS-232 RX Pin 2 Pin 3
RS-232 GND Pin 5 Pin 7
57
PICBASIC PRO Compiler
5.13. DEBUGIN
DEBUGIN {Timeout,Label,}[Item{,Item...}]
DEBUGIN (on all devices except 12-bit core) supports the same data
modifiers as SERIN2. Refer to the section on SERIN2 for this
information.
Modifier Operation
BIN{1..32} Receive binary digits
DEC{1..10} Receive decimal digits
HEX{1..8} Receive upper case hexadecimal digits
SKIP n Skip n received characters
STR ArrayVar\n{\c} Receive string of n characters
optionally ended in character c
WAIT ( ) Wait for sequence of characters
WAITSTR ArrayVar{\n} Wait for character string
The serial pin and baud rate are specified using DEFINEs:
58
PICBASIC PRO Compiler
DB9 DB25
22K
Pin RS-232 TX Pin 3 Pin 2
RS-232 GND Pin 5 Pin 7
59
PICBASIC PRO Compiler
5.14. DISABLE
DISABLE
DISABLE and ENABLE are pseudo-ops in that they give the compiler
directions, rather than actually generate code. See ON DEBUG and ON
INTERRUPT for more information.
60
PICBASIC PRO Compiler
DISABLE DEBUG and ENABLE DEBUG are pseudo-ops in that they give
the compiler directions, rather than actually generate code. See ON
DEBUG for more information.
61
PICBASIC PRO Compiler
62
PICBASIC PRO Compiler
5.17. DTMFOUT
DTMFOUT Pin,{Onms,Offms,}[Tone{,Tone...}]
Onms is the number of milliseconds to sound each tone and Offms is the
number of milliseconds to pause between each tone. If they are not
specified, Onms defaults to 200ms and Offms defaults to 50ms.
Tones are numbered 0-15. Tones 0-9 are the same as on a telephone
keypad. Tone 10 is the * key, Tone 11 is the # key and Tones 12-15
correspond to the extended keys A-D.
DTMFOUT works best with a 20MHz or 40MHz oscillator. It can also work
with a 10MHz or 8MHz oscillator and even at 4MHz, although it will start
to get very hard to filter and be of fairly low amplitude. Any other
frequency may not be used with DTMFOUT.
DTMFOUT is not supported on 12-bit core PIC MCUs due to RAM and
stack constraints.
63
PICBASIC PRO Compiler
5.18. EEPROM
EEPROM {Location,}[Constant{,Constant...}]
The data is stored in the EEPROM space only once at the time the
microcontroller is programmed, not each time the program is run. WRITE
can be used to set the values of the on-chip EEPROM at runtime. READ
is used to retrieve these stored DATA values at runtime.
64
PICBASIC PRO Compiler
5.19. ENABLE
ENABLE
DISABLE and ENABLE are pseudo-ops in that they give the compiler
directions, rather than actually generate code. See ON DEBUG and ON
INTERRUPT for more information.
65
PICBASIC PRO Compiler
DISABLE DEBUG and ENABLE DEBUG are pseudo-ops in that they give
the compiler directions, rather than actually generate code. See ON
DEBUG for more information.
66
PICBASIC PRO Compiler
67
PICBASIC PRO Compiler
5.22. END
END
Stop program execution and enter low power mode. All of the I/O pins
remain in their current state. END works by executing a Sleep instruction
continuously in a loop.
END
68
PICBASIC PRO Compiler
5.23. ERASECODE
ERASECODE Block
Some flash PIC MCUs, like the PIC18Fxxxx series, require a portion of
the code space to be erased before it can be rewritten with WRITECODE.
On these devices, an erase is performed a block at a time. An erase
block may be 32 words (64 bytes) or another size, depending on the
device. This size is usually larger than the write block size. See the
Microchip data sheet for information on the size of the erase block for the
particular PIC MCU you are using.
Flash program writes must be enabled in the configuration for the PIC
MCU at device programming time for ERASECODE to be able to erase.
Using this instruction on devices that do not support block erase may
cause a compilation error.
69
PICBASIC PRO Compiler
5.24. FOR..NEXT
70
PICBASIC PRO Compiler
5.25. FREQOUT
FREQOUT Pin,Onms,Frequency1{,Frequency2}
FREQOUT works best with a 20MHz or 40MHz oscillator. It can also work
with a 10MHz or 8MHz oscillator and even at 4MHz, although it will start
to get very hard to filter and be of fairly low amplitude. Any other
frequency will cause FREQOUT to generate a frequency that is a ratio of
the actual oscillator used and 20MHz.
FREQOUT is not supported on 12-bit core PIC MCUs due to RAM and
stack constraints.
71
PICBASIC PRO Compiler
5.26. GOSUB
GOSUB Label
Jump to the subroutine at Label saving its return address on the stack.
Unlike GOTO, when a RETURN statement is reached after executing a
GOSUB, execution resumes with the statement following that last
executed GOSUB statement.
72
PICBASIC PRO Compiler
5.27. GOTO
GOTO Label
73
PICBASIC PRO Compiler
5.28. HIGH
HIGH Pin
Make the specified Pin high. Pin is automatically made an output. Pin
may be a constant, 0-15, or a variable that contains a number 0-15 (e.g.
B0) or a pin name (e.g. PORTA.0).
74
PICBASIC PRO Compiler
5.29. HPWM
HPWM Channel,Dutycycle,Frequency
Some devices, such as the PIC18F452, have alternate pins that may be
used for HPWM. The following DEFINEs allow using these pins:
75
PICBASIC PRO Compiler
After an HPWM command, the CCP control register is left in PWM mode.
If the CCP pin is to be used as a normal I/O pin after an HPWM command,
the CCP control register will need to be set to PWM off. See the
Microchip data sheet for the particular device for more information.
76
PICBASIC PRO Compiler
5.30. HSERIN
HSERIN {ParityLabel,}{Timeout,Label,}[Item{,...}]
Receive one or more Items from the hardware serial port on devices
that support asynchronous serial communications in hardware.
The TXSTA register BRGH bit (bit 2) controls the high speed mode for
the baud rate generator. Certain baud rates at certain oscillator speeds
require this bit to be set to operate properly. To do this, set HSER_TXSTA
to 24h instead of 20h. All baud rates at all oscillator speeds may not be
supported by the device. See the Microchip data sheet for the hardware
serial port baud rate tables and additional information.
77
PICBASIC PRO Compiler
The serial data format defaults to 8N1, 8 data bits, no parity bit and 1 stop
bit. 7E1 (7 data bits, even parity, 1 stop bit) or 7O1 (7data bits, odd parity,
1 stop bit) can be enabled using one of the following DEFINEs:
The parity setting, along with all of the other HSER DEFINEs, affect both
HSERIN and HSEROUT.
As the hardware serial port only has a 2 byte input buffer, it can easily
overflow if characters are not read from it often enough. When this
happens, the USART stops accepting new characters and needs to be
reset. This overflow error can be reset by toggling the CREN bit in the
RCSTA register. A DEFINE can be used to automatically clear this error.
However, you will not know that an error has occurred and characters
may have been lost.
DEFINE HSER_CLROERR 1
RCSTA.4 = 0
RCSTA.4 = 1
Since the serial reception is done in hardware, it is not possible to set the
levels to an inverted state to eliminate an RS-232 driver. Therefore a
suitable driver should be used with HSERIN.
78
PICBASIC PRO Compiler
On devices with 2 hardware serial ports, HSERIN will only use the first
port. The second port may read using HSERIN2.
HSERIN supports the same data modifiers that SERIN2 does. Refer to
the section on SERIN2 for this information.
Modifier Operation
BIN{1..32} Receive binary digits
DEC{1..10} Receive decimal digits
HEX{1..8} Receive upper case hexadecimal digits
SKIP n Skip n received characters
STR ArrayVar\n{\c} Receive string of n characters
optionally ended in character c
WAIT ( ) Wait for sequence of characters
WAITSTR ArrayVar{\n} Wait for character string
79
PICBASIC PRO Compiler
5.31. HSERIN2
HSERIN2 {ParityLabel,}{Timeout,Label,}[Item{,...}]
Receive one or more Items from the second hardware serial port on
devices that support asynchronous serial communications in hardware.
HSERIN2 works the same as HSERIN with the exception that is uses the
second hardware serial port on devices that have 2 ports such as the
PIC18F8720 It can only be used with devices that have 2 hardware
USARTs. See the device data sheet for information on the serial output
pin and other parameters and the above section on HSERIN for more
command details. The serial parameters and baud rate are specified
using DEFINEs:
80
PICBASIC PRO Compiler
5.32. HSEROUT
HSEROUT [Item{,Item...}]
Send one or more Items to the hardware serial port on devices that
support asynchronous serial communications in hardware.
The TXSTA register BRGH bit (bit 2) controls the high speed mode for
the baud rate generator. Certain baud rates at certain oscillator speeds
require this bit to be set to operate properly. To do this, set HSER_TXSTA
to 24h instead of 20h. All baud rates at all oscillator speeds may not be
supported by the device. See the Microchip data sheet for the hardware
serial port baud rate tables and additional information.
81
PICBASIC PRO Compiler
The serial data format defaults to 8N1, 8 data bits, no parity bit and 1 stop
bit. 7E1 (7 data bits, even parity, 1 stop bit) or 7O1 (7data bits, odd parity,
1 stop bit) can be enabled using one of the following DEFINEs:
The parity setting, along with all of the other HSER DEFINEs, affect both
HSERIN and HSEROUT.
On devices with 2 hardware serial ports, HSEROUT will only use the first
port. The second port may be accessed using HSEROUT2.
HSEROUT supports the same data modifiers that SEROUT2 does. Refer
to the section on SEROUT2 for this information.
Modifier Operation
{I}{S}BIN{1..32} Send binary digits
{I}{S}DEC{1..10} Send decimal digits
{I}{S}HEX{1..8} Send hexadecimal digits
REP c\n Send character c repeated n times
STR ArrayVar{\n} Send string of n characters
82
PICBASIC PRO Compiler
5.33. HSEROUT2
HSEROUT2 [Item{,Item...}]
Send one or more Items to the second hardware serial port on devices
that support asynchronous serial communications in hardware.
HSEROUT2 works the same as HSEROUT with the exception that is uses
the second hardware serial port on devices that have 2 ports such as the
PIC18F8720. It can only be used with devices that have 2 hardware
USARTs. See the device data sheet for information on the serial output
pin and other parameters and the above section on HSEROUT for more
command details. The serial parameters and baud rate are specified
using DEFINEs:
83
PICBASIC PRO Compiler
5.34. I2CREAD
I2CREAD DataPin,ClockPin,Control,{Address,}
[Var{,Var...}]{,Label}
Send Control and optional Address bytes out the ClockPin and
DataPin and store the byte(s) received into Var. ClockPin and
DataPin may be a constant, 0-15, or a variable that contains a number
0-15 (e.g. B0) or a pin name (e.g. PORTA.0).
I2CREAD and I2CWRITE can be used to read and write data to a serial
EEPROM with a 2-wire I2C interface such as the Microchip 24LC01B and
similar devices. This allows data to be stored in external non-volatile
memory so that it can be maintained even after the power is turned off.
These commands operate in the I2C master mode and may also be used
to talk to other devices with an I2C interface like temperature sensors and
A/D converters.
For 12-bit core PIC MCUs only, the I2C clock and data pins are fixed at
compile time by DEFINEs. They still must be specified in the I2CREAD
statements, though this information is ignored by the compiler.
The upper 7 bits of the Control byte contain the control code along with
chip select or additional address information, depending on the particular
device. The low order bit is an internal flag indicating whether it is a read
or write command and should be kept clear.
This format for the Control byte is different than the format used by the
original PICBASIC Compiler. Be sure to use this format with PBP I2C
operations.
84
PICBASIC PRO Compiler
The Address size sent (byte or word) is determined by the size of the
variable that is used. If a byte-sized variable is used for the Address, an
8-bit address is sent. If a word-sized variable is used, a 16-bit address is
sent. Be sure to use the proper sized variable for the device you wish to
communicate with. Constants should not be used for the Address as
the size can vary dependent on the size of the constant. Also,
expressions should not be used as they can cause an improper Address
size to be sent.
Once Control and/or Address has been sent to the device, the data
specified between the square brackets is read from the device. If a word-
or long-sized Var is specified, the bytes are read and stored into the Var
highest byte first, followed by the lower byte(s). This order is different
than the way variables are normally stored, low byte first.
A modifier, STR, may be included before the variable name. This can
load an entire array (string) at once. If STR is specified, the following
variable must be the name of a word or byte array, followed by a
backslash (\) and a count:
a Var Byte[8]
addr Var Byte
addr = 0
I2CREAD PORTC.4,PORTC.3,$a0,addr,[STR a\8]
85
PICBASIC PRO Compiler
words and longs are read and is consistent with the way the compiler
normally stores word- and long-sized variables.
The I2C instructions can be used to access the on-chip serial EEPROM
on the 12CExxx and 16CExxx devices. Simply specify the pin names for
the appropriate internal lines as part of the I2C command and place the
following DEFINE at the top of the program:
DEFINE I2C_INTERNAL 1
For the 12CE67x devices, the data line is GPIO.6 and the clock line is
GPIO.7. For the 16CE62x devices, the data line is EEINTF.1 and the
clock line is EEINTF.2. See the Microchip data sheets for these devices
for more information.
The timing of the I2C instructions is set so that standard speed devices
(100kHz) will be accessible at clock speeds up to 8MHz. Fast mode
devices (400kHz) may be used up to 20MHz. If it is desired to access a
standard speed device at above 8MHz, the following DEFINE should be
added to the program:
DEFINE I2C_SLOW 1
Because of memory and stack constraints, this DEFINE for 12-bit core
PIC MCUs does not do anything. Low-speed (100 kHz) I2C devices may
be used up to 4MHz. Above 4MHz, high-speed (400kHz) devices should
be used.
Transfer on the I2C bus can be paused by the receiving device by its
holding the clock line low (not supported on 12-bit core PIC MCUs). To
enable this the following DEFINE should be added to the program:
DEFINE I2C_HOLD 1
The I2C clock and data lines should be pulled up to Vcc with a 4.7K
resistor per the following schematic as they are both run in a bi-
directional open-collector manner.
86
PICBASIC PRO Compiler
To make the I2C clock line bipolar instead of open-collector the following
DEFINE may be added to the program:
DEFINE I2C_SCLOUT 1
See the Microchip “Non-Volatile Memory Products Data Book” for more
information on these and other devices that may be used with the
I2CREAD and I2CWRITE commands.
87
PICBASIC PRO Compiler
5.35. I2CWRITE
I2CWRITE DataPin,ClockPin,Control,{Address,}
[Value{,Value...}]{,Label}
I2CWRITE sends Control and optional Address out the I2C ClockPin
and DataPin followed by Value. ClockPin and DataPin may be a
constant, 0-15, or a variable that contains a number 0-15 (e.g. B0) or a
pin name (e.g. PORTA.0).
For 12-bit core PIC MCUs only, the I2C clock and data pins are fixed at
compile time by DEFINEs. They still must be specified in the I2CWRITE
statements, though this information is ignored by the compiler.
The Address size sent (byte or word) is determined by the size of the
variable that is used. If a byte-sized variable is used for the Address, an
8-bit address is sent. If a word-sized variable is used, a 16-bit address is
sent. Be sure to use the proper sized variable for the device you wish to
communicate with. Constants should not be used for the Address as
the size can vary dependent on the size of the constant. Also,
expressions should not be used as they can cause an improper Address
size to be sent.
88
PICBASIC PRO Compiler
A modifier, STR, may be included before the variable name. This can be
used to write an entire array (string) at once and take advantage of a
serial EEPROM’s page mode. The data must fit into a single SEEPROM
page. The page size is dependent on the particular SEEPROM device.
If STR is specified, the following variable must be the name of a word or
byte array, followed by a backslash (\) and a count:
a Var Byte[8]
addr Var Byte
addr = 0
I2CWRITE PORTC.4,PORTC.3,$a0,addr,[STR a\8]
The I2C instructions can be used to access the on-chip serial EEPROM
on the 12CExxx and 16CExxx devices. Simply specify the pin names for
the appropriate internal lines as part of the I2C command and place the
following DEFINE at the top of the program:
DEFINE I2C_INTERNAL 1
For the 12CE67x devices, the data line is GPIO.6 and the clock line is
GPIO.7. For the 16CE62x devices, the data line is EEINTF.1 and the
clock line is EEINTF.2. See the Microchip data sheets for these devices
for more information.
The timing of the I2C instructions is set so that standard speed devices
(100kHz) will be accessible at clock speeds up to 8MHz. Fast mode
devices (400kHz) may be used up to 20MHz. If it is desired to access a
standard speed device at above 8MHz, the following DEFINE should be
added to the program:
DEFINE I2C_SLOW 1
Because of memory and stack constraints, this DEFINE for 12-bit core
PIC MCUs does not do anything. Low-speed (100 kHz) I2C devices may
89
PICBASIC PRO Compiler
Transfer on the I2C bus can be paused by the receiving device by its
holding the clock line low (not supported on 12-bit core PIC MCUs). To
enable this the following DEFINE should be added to the program:
DEFINE I2C_HOLD 1
To make the I2C clock line bipolar instead of open-collector the following
DEFINE may be added to the program:
DEFINE I2C_SCLOUT 1
See the I2CREAD command above for the rest of the story.
90
PICBASIC PRO Compiler
5.36. IF..THEN
For PBP and PBPW, all comparisons are unsigned since they only
supports unsigned types. IF..THEN cannot be used to check if a
number is less than 0. Using PBPL, signed comparisons may be
performed.
91
PICBASIC PRO Compiler
If B0 <> 10 Then B0 = B0 + 1: B1 = B1 - 1
If B0 <> 10 Then
B0 = B0 + 1
B1 = B1 - 1
Endif
If B0 = 20 Then
led = 1
Else
led = 0
Endif
92
PICBASIC PRO Compiler
5.37. INPUT
INPUT Pin
Alternatively, the pin may be set to an input in a much quicker and shorter
way (from a generated code standpoint):
All of the pins on a port may be set to inputs by setting the entire TRIS
register at once:
93
PICBASIC PRO Compiler
5.38. LCDIN
LCDIN {Address,}[Var{,Var...}]
LCDs have RAM onboard that is used for character memory. Most LCDs
have more RAM available that is necessary for the displayable area.
This RAM can be written using the LCDOUT instruction. The LCDIN
instruction allows this RAM to be read.
LCDIN [B0]
94
PICBASIC PRO Compiler
5.39. LCDOUT
LCDOUT Item{,Item...}
If a pound sign (#) precedes an Item, the ASCII representation for each
digit is sent to the LCD. LCDOUT (on all devices except 12-bit core) can
also use any of the modifiers used with SEROUT2. See the section on
SEROUT2 for this information.
Modifier Operation
{I}{S}BIN{1..32} Send binary digits
{I}{S}DEC{1..10} Send decimal digits
{I}{S}HEX{1..8} Send hexadecimal digits
REP c\n Send character c repeated n times
STR ArrayVar{\n} Send string of n characters
A program should wait for up to half a second before sending the first
command to an LCD. It can take quite a while for an LCD to start up.
The LCD is initialized the first time any character or command is sent to it
using LCDOUT. If it is powered down and then powered back up for some
reason during operation, an internal flag can be reset to tell the program
to reinitialize it the next time it uses LCDOUT:
FLAGS = 0
95
PICBASIC PRO Compiler
Command Operation
$FE, 1 Clear display
$FE, 2 Return home
$FE, $0C Cursor off
$FE, $0E Underline cursor on
$FE, $0F Blinking cursor on
$FE, $10 Move cursor left one position
$FE, $14 Move cursor right one position
$FE, $80 Move cursor to beginning of first line
$FE, $C0 Move cursor to beginning of second line
$FE, $94 Move cursor to beginning of third line
$FE, $D4 Move cursor to beginning of fourth line
Note that there are commands to move the cursor to the beginning of the
different lines of a multi-line display. For most LCDs, the displayed
characters and lines are not consecutive in display memory - there can
be a break in between locations. For most 16x2 displays, the first line
starts at $80 and the second line starts at $C0. The command:
sets the display to start writing characters at the forth position of the first
line. 16x1 displays are usually formatted as 8x2 displays with a break
between the memory locations for the first and second 8 characters. 4-
line displays also have a mixed up memory map, as shown in the table
above.
See the data sheet for the particular LCD device for the character
memory locations and additional commands..
The LCD may be connected to the PIC MCU using either a 4-bit bus or
an 8-bit bus. If an 8-bit bus is used, all 8 bits must be on one port. If a 4-
96
PICBASIC PRO Compiler
bit bus is used, the top 4 LCD data bits must be connected to either the
bottom 4 or top 4 bits of one port. Enable and Register Select may be
connected to any port pin. R/W may be tied to ground if the LCDIN
command is not used.
To change this setup, place one or more of the following DEFINEs, all in
upper-case, at the top of your PICBASIC PRO program:
97
PICBASIC PRO Compiler
98
PICBASIC PRO Compiler
5.40. {LET}
LET B0 = B1 * B2 + B3
B0 = Sqr W1
99
PICBASIC PRO Compiler
5.41. LOOKDOWN
LOOKDOWN Search,[Constant{,Constant...}],Var
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. Array variables with a variable index may not be used in
LOOKDOWN although array variables with a constant index are allowed.
Up to 255 (256 for PIC18Xxxxx) constants are allowed in the list.
100
PICBASIC PRO Compiler
5.42. LOOKDOWN2
LOOKDOWN2 Search,{Test}[Value{,Value...}],Var
The optional parameter Test can be used to perform a test for other
than equal to (“=”) while searching the list. For example, the list could be
searched for the first instance where the Search parameter is greater
than the Value by using “>” as the Test parameter. If Test is left out,
“=” is assumed.
The Value list can be a mixture of 8- and 16-bit (and 32-bit for PBPL)
numeric and string constants and variables. Each character in a string is
treated as a separate constant equal to the character's ASCII value.
Expressions may not be used in the Value list, although they may be
used as the Search value.
LOOKDOWN2 W0,[512,W1,1024],B0
LOOKDOWN2 W0,>[1000,100,10],B0
101
PICBASIC PRO Compiler
5.43. LOOKUP
LOOKUP Index,[Constant{,Constant...}],Var
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. Array variables with a variable index may not be
used in LOOKUP although array variables with a constant index are
allowed. Up to 255 (1024 for PIC18Xxxxx) constants are allowed in the
list.
102
PICBASIC PRO Compiler
5.44. LOOKUP2
LOOKUP2 Index,[Value{,Value...}],Var
The Value list can be a mixture of 8-bit and 16-bit (and 32-bit for PBPL)
numeric and string constants and variables. Each character in a string is
treated as a separate constant equal to the character's ASCII value.
Expressions may not be used in the Value list, although they may be
used as the Index value.
LOOKUP2 B0,[256,512,1024],W1
103
PICBASIC PRO Compiler
5.45. LOW
LOW Pin
Make the specified Pin low. Pin is automatically made an output. Pin
may be a constant, 0 - 15, or a variable that contains a number 0 - 15
(e.g. B0) or a pin name (e.g. PORTA.0).
104
PICBASIC PRO Compiler
5.46. NAP
NAP Period
Places the microcontroller into low power mode for short periods of time.
During this NAP, power consumption is reduced to minimum.
NAP puts the processor to sleep for one Watchdog Timer period. If the
Watchdog Timer is not enabled, the processor will sleep forever or until
an enabled interrupt or reset is received.
The Period is used to set the Watchdog timer prescaler for devices that
have a prescaler including the 12- and 14-bit core devices. The 16-bit
core devices, including the 17Cxxx and 18Xxxxx parts use a postscaler
set at programming time to configure the Watchdog timeout period. The
compiler will disregard the Period set in the NAP instruction for the 16-
bit core devices.
The listed Periods for the 12- and 14-bit core devices are only
approximate because the timing derived from the Watchdog Timer is R/C
driven and can vary greatly from chip to chip and over temperature.
Since NAP uses the Watchdog Timer, its timing is independent of the
oscillator frequency.
105
PICBASIC PRO Compiler
5.47. ON DEBUG
Another byte-sized variable may be used to return the level of the current
program stack:
This level should never be greater than 4 for 12- and 14-bit core PIC
MCUs, 12 for PIC17Cxxx devices or 27 for PIC18Xxxxx devices in a
PICBASIC PRO program. The supplied variable will be incremented at
each GOSUB and decremented at each RETURN. This variable should be
set to 0 at the beginning of the program.
Adding this variable to a program does add overhead in that the value of
the variable must be incremented and decremented at each GOSUB and
RETURN.
106
PICBASIC PRO Compiler
5.48. ON INTERRUPT
Latency is the time it takes from the time of the actual interrupt to the
time the interrupt handler is entered. Since PICBASIC PRO statements
are not re-entrant (i.e. you cannot execute another PICBASIC PRO
statement while one is being executed), there can be considerable
latency before the interrupt routine is entered.
PBP will not enter the BASIC interrupt handler until it has finished
executing the current statement. If the statement is a PAUSE or SERIN, it
could be quite a while before the interrupt is acknowledged. The
program must be designed with this latency in mind. If it is unacceptable
and the interrupts must be handled more quickly, an assembly language
interrupt routine must be used.
107
PICBASIC PRO Compiler
. . .
INTCON = $80
108
PICBASIC PRO Compiler
5.49. OUTPUT
OUTPUT Pin
All of the pins on a port may be set to outputs by setting the entire TRIS
register at once:
109
PICBASIC PRO Compiler
5.50. OWIN
OWIN Pin,Mode,[Item...]
Optionally send a reset pulse to a one-wire device and then read one or
more bits or bytes of data from it, optionally ending with another reset
pulse.
Mode specifies whether a reset is sent before and/or after the operation
and the size of the data items, either bit or byte.
The SKIP and STR modifiers are not supported for the 12-bit core PIC
MCUs because of RAM and stack size limits.
110
PICBASIC PRO Compiler
5.51. OWOUT
OWOUT Pin,Mode,[Item...]
Optionally send a reset pulse to a one-wire device and then writes one or
more bits or bytes of data to it, optionally ending with another reset pulse.
Mode specifies whether a reset is sent before and/or after the operation
and the size of the data items, either bit or byte.
The REP and STR modifiers are not supported for the 12-bit core PIC
MCUs because of RAM and stack size limits.
OWOUT PORTC.0,%001,[$cc,$be]
111
PICBASIC PRO Compiler
5.52. PAUSE
PAUSE Period
Unlike the other delay functions (NAP and SLEEP), PAUSE doesn't put the
microcontroller into low power mode. Thus, PAUSE consumes more
power but is also much more accurate. It has the same accuracy as the
system clock.
112
PICBASIC PRO Compiler
5.53. PAUSEUS
PAUSEUS Period
113
PICBASIC PRO Compiler
5.54. PEEK
PEEK Address,Var
However, all of the PIC MCU registers can be and should be accessed
without using PEEK and POKE. All of the PIC MCU registers are
considered 8-bit variables by PICBASIC PRO and may be used as you
would any other byte-sized variable. They can be read directly or used
directly in equations.
114
PICBASIC PRO Compiler
5.55. PEEKCODE
PEEKCODE Address,Var
Read a value from the code space at the specified Address and store
the result in Var.
PEEKCODE can be used to read data stored in the code space of a PIC
MCU. It executes a call to the specified Address and places the
returned value in Var. The specified location should contain a retlw
and the data value. POKECODE may be used to store this value at the
time the device is programmed.
115
PICBASIC PRO Compiler
5.56. POKE
POKE Address,Value
However, all of the PIC MCU registers can be and should be accessed
without using PEEK and POKE. All of the PIC MCU registers are
considered 8-bit variables by PICBASIC PRO and may be used as you
would any other byte-sized variable. They can be written directly or used
directly in equations.
116
PICBASIC PRO Compiler
5.57. POKECODE
POKECODE {@Address,}Value{,Value...}
POKECODE can be used to generate tables in the code space of the PIC
MCU. It generates a return with the data in W. This data can be
accessed using the PEEKCODE instruction.
117
PICBASIC PRO Compiler
5.58. POT
POT Pin,Scale,Var
Use the following code to automate the process. Make sure that you set
the pot to maximum resistance.
B0 Var Byte
scale Var Byte
calibrated:
Serout 2,0,["Scale= ",#scale,10,13]
118
PICBASIC PRO Compiler
Pin 5-50K
0.1uF
119
PICBASIC PRO Compiler
5.59. PULSIN
PULSIN Pin,State,Var
Measures pulse width 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. If the pulse edge never happens
or the width of the pulse is too great to measure, Var is set to zero.
120
PICBASIC PRO Compiler
5.60. PULSOUT
PULSOUT Pin,Period
121
PICBASIC PRO Compiler
5.61. PWM
PWM Pin,Duty,Cycle
Outputs a pulse width modulated 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. Pin
may be a constant, 0 - 15, or a variable that contains a number 0 - 15
(e.g. B0) or a pin name (e.g. PORTA.0).
If you want continuous PWM output and the PIC MCU has PWM
hardware, HPWM may be used instead of PWM. See the section on for
HPWM more information about it.
10K
Pin Analog Out
1uF
122
PICBASIC PRO Compiler
5.62. RANDOM
RANDOM Var
123
PICBASIC PRO Compiler
5.63. RCTIME
RCTIME Pin,State,Var
124
PICBASIC PRO Compiler
5.64. READ
READ Address,Var
Read a byte from the on-chip EEPROM at the specified Address and
stores the result in Var. This instruction may only be used with a PIC
MCU that has an on-chip EEPROM data area such as the PIC12F683,
16F84 and the 16F87x series.
READ will not work on devices with on-chip I2C interfaced serial EEPROM
like the PIC12CE67x and 16CE62x parts. Use the I2CREAD instruction
instead.
To read a word, each of the 2 bytes that make up the word must be read
separately:
w Var Word
READ 0,w.Byte0
READ 1,w.Byte1
125
PICBASIC PRO Compiler
5.65. READCODE
READCODE Address,Var
For PIC16Fxxx devices, 14-bit-sized data can be read from word code
space Addresses.
For PIC18Xxxxx devices, byte or word-sized data can be read from byte
(rather than word) code space Addresses.
126
PICBASIC PRO Compiler
5.66. REPEAT..UNTIL
REPEAT
Statement...
UNTIL Condition
i = 0
REPEAT
PORTB.0[i] = 0
i = i + 1
UNTIL i > 7
127
PICBASIC PRO Compiler
5.67. RESUME
RESUME {Label}
128
PICBASIC PRO Compiler
5.68. RETURN
RETURN
129
PICBASIC PRO Compiler
5.69. REVERSE
REVERSE Pin
130
PICBASIC PRO Compiler
SELECT CASE x
CASE 1
y = 10
CASE 2, 3
y = 20
CASE IS > 5
y = 100
CASE ELSE
y = 0
END SELECT
131
PICBASIC PRO Compiler
5.71. SERIN
SERIN
Pin,Mode,{Timeout,Label,}{[Qual...],}{Item...}
The Mode names (e.g. T2400) are defined in the file MODEDEFS.BAS.
To use them, add the line:
Include “modedefs.bas”
132
PICBASIC PRO Compiler
Once the qualifiers are satisfied, SERIN begins storing data in the
variables associated with each Item. If the variable name is used alone,
the value of the received ASCII character is stored in the variable. If
variable is preceded by a pound sign ( # ), 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. The decimal value received may not be greater than
65535, even when a long variable is specified.
DB9 DB25
22K
Pin RS-232 TX Pin 3 Pin 2
RS-232 GND Pin 5 Pin 7
133
PICBASIC PRO Compiler
5.72. SERIN2
SERIN2 DataPin{\FlowPin},Mode,{ParityLabel,}
{Timeout,Label,}[Item...]
The optional flow control pin, FlowPin, may be included to help keep
data from overrunning the receiver. If it is used, FlowPin is
automatically set to the enabled state to allow transmission of each
character. This enabled state is determined by the polarity of the data
specified by Mode.
Mode is used to specify the baud rate and operating parameters of the
serial transfer. The low order 13 bits select the baud rate. Bit 13 selects
parity or no parity. Bit 14 selects inverted or true level. Bit 15 is not used.
The baud rate bits specify the bit time in microseconds - 20. To find the
value for a given baud rate, use the equation:
(1000000 / baud) - 20
134
PICBASIC PRO Compiler
DEFINE SER2_ODD 1
Bit 14 selects the level of the data and flow control pins. If bit 14 = 0, the
data is received in true form for use with RS-232 drivers. If bit14 = 1, the
data is received inverted. This mode can be used to avoid installing RS-
232 drivers.
A DEFINE allows the use of data bits other than 8 (or 7 with parity).
SER2_BITS data bits may range from 4 bits to 8 (the default if no
DEFINE is specified). Enabling parity uses one of the number of bits
specified.
135
PICBASIC PRO Compiler
SERIN2 supports many different data modifiers which may be mixed and
matched freely within a single SERIN2 statement to provide various input
formatting.
Modifier Operation
BIN{1..32} Receive binary digits
DEC{1..10} Receive decimal digits
HEX{1..8} Receive upper case hexadecimal digits
SKIP n Skip n received characters
STR ArrayVar\n{\c} Receive string of n characters
optionally ended in character c
WAIT ( ) Wait for sequence of characters
WAITSTR ArrayVar{\n} Wait for character string
136
PICBASIC PRO Compiler
137
PICBASIC PRO Compiler
DB9 DB25
22K
Pin RS-232 TX Pin 3 Pin 2
RS-232 GND Pin 5 Pin 7
SERIN2 is not supported on 12-bit core PIC MCUs due to RAM and stack
constraints.
SERIN2 PORTA.1\PORTA.0,84,100,tlabel,[WAIT(“x”,
b0),STR ar]
138
PICBASIC PRO Compiler
5.73. SEROUT
SEROUT Pin,Mode,[Item{,Item...}]
The Mode names (e.g. T2400) are defined in the file MODEDEFS.BAS.
To use them, add the line:
Include “modedefs.bas”
139
PICBASIC PRO Compiler
SEROUT supports three different data types which may be mixed and
matched freely within a single SEROUT statement.
140
PICBASIC PRO Compiler
DB9 DB25
1K
Pin RS-232 RX Pin 2 Pin 3
RS-232 GND Pin 5 Pin 7
141
PICBASIC PRO Compiler
5.74. SEROUT2
SEROUT2 DataPin{\FlowPin},Mode,{Pace,}
{Timeout,Label,}[Item...]
The optional flow control pin, FlowPin, may be included to help keep
data from overrunning the receiver. If it is used, the serial data will not be
sent until FlowPin is in the proper state. This state is determined by the
polarity of the data specified by Mode.
Mode is used to specify the baud rate and operating parameters of the
serial transfer. The low order 13 bits select the baud rate. Bit 13 selects
parity or no parity. Bit 14 selects inverted or true level. Bit 15 selects
whether it is driven or open.
The baud rate bits specify the bit time in microseconds - 20. To find the
value for a given baud rate, use the equation:
(1000000 / baud) - 20
142
PICBASIC PRO Compiler
DEFINE SER2_ODD 1
Bit 14 selects the level of the data and flow control pins. If bit 14 = 0, the
data is sent in true form for use with RS-232 drivers. If bit14 = 1, the data
is sent inverted. This mode can be used to avoid installing RS-232
drivers.
Bit 15 selects whether the data pin is always driven (bit 15 = 0), or is open
in one of the states (bit 15 = 1). The open mode can be used to chain
several devices together on the same serial bus.
A DEFINE allows the use of data bits other than 8 (or 7 with parity).
SER2_BITS data bits may range from 4 bits to 8 (the default if no
DEFINE is specified). Enabling parity uses one of the number of bits
specified. Defining SER2_BITS to 9 allows 8 bits to be read and written
along with a 9th parity bit.
143
PICBASIC PRO Compiler
Modifier Operation
{I}{S}BIN{1..32} Send binary digits
{I}{S}DEC{1..10} Send decimal digits
{I}{S}HEX{1..8} Send hexadecimal digits
REP c\n Send character c repeated n times
STR ArrayVar{\n} Send string of n characters
144
PICBASIC PRO Compiler
If any are preceded by an S (for signed), the output will be sent preceded
by a “-“ if the high order bit of the data is set. This allows the
transmission of negative numbers. Keep in mind that all of the math and
comparisons in PBP are unsigned. However, unsigned math can yield
signed results. For example, take the case of B0 = 9 - 10. The
result of DEC B0 would be “255". Sending SDEC B0 would give “-1"
since the high order bit is sent. So with a little trickery, the unsigned math
of PBP can yield signed results.
BIN, DEC and HEX may also be followed by a number. Normally, these
modifiers display exactly as many digits as are necessary, zero blanked
(leading zeros are not sent). However, if a number follows the modifier,
SEROUT2 will always send that number of digits, adding leading zeros as
necessary. It will also trim of any extra high order digits. For example,
BIN6 8 would send “001000" and BIN2 8 would send “00".
145
PICBASIC PRO Compiler
DB9 DB25
1K
Pin RS-232 RX Pin 2 Pin 3
RS-232 GND Pin 5 Pin 7
SEROUT2 is not supported on 12-bit core PIC MCUs due to RAM and
stack constraints.
146
PICBASIC PRO Compiler
5.75. SHIFTIN
SHIFTIN DataPin,ClockPin,Mode,[Var{\Bits}...]
The Mode names (e.g. MSBPRE) are defined in the file MODEDEFS.BAS.
To use them, add the line:
Include “modedefs.bas”
For Modes 0-3, the clock idles low, toggles high to clock in a bit, and
then returns low. For Modes 4-7, the clock idles high, toggles low to
clock in a bit, and then returns high.
147
PICBASIC PRO Compiler
The shift clock runs at about 50kHz, dependent on the oscillator. The
active state is held to a minimum of 2 microseconds. A DEFINE allows
the active state of the clock to be extended by an additional number of
microseconds up to 65,535 (65.535 milliseconds) to slow the clock rate.
The minimum additional delay is defined by the PAUSEUS timing. See its
section for the minimum for any given oscillator. This DEFINE is not
available on 12-bit core PIC MCUs.
148
PICBASIC PRO Compiler
The following diagram shows the relationship of the clock to the data for
the various modes:
SHIFTIN 0,1,MSBPRE,[B0,B1\4]
149
PICBASIC PRO Compiler
5.76. SHIFTOUT
SHIFTOUT DataPin,ClockPin,Mode,[Var{\Bits}...]
Include “modedefs.bas”
For Modes 0-1, the clock idles low, toggles high to clock in a bit, and
then returns low. For Modes 4-5, the clock idles high, toggles low to
clock in a bit, and then returns high.
The shift clock runs at about 50kHz, dependent on the oscillator. The
active state is held to a minimum of 2 microseconds. A DEFINE allows
150
PICBASIC PRO Compiler
The following diagram shows the relationship of the clock to the data for
the various modes:
SHIFTOUT 0,1,MSBFIRST,[B0,B1]
SHIFTOUT PORTA.1,PORTA.2,1,[wordvar\4]
SHIFTOUT PORTC.1,PORTB.1,4,[$1234\16, $56]
151
PICBASIC PRO Compiler
5.77. SLEEP
SLEEP Period
152
PICBASIC PRO Compiler
5.78. SOUND
SOUND Pin,[Note,Duration{,Note,Duration...}]
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). Note 1 is about
78.74Hz and Note 127 is about 10,000Hz.
Duration is 0-255 and determines how long the Note is played in about
12 millisecond increments. Note and Duration needn't be constants.
10uF
Pin
153
PICBASIC PRO Compiler
5.79. STOP
STOP
154
PICBASIC PRO Compiler
5.80. SWAP
SWAP Variable,Variable
155
PICBASIC PRO Compiler
5.81. TOGGLE
TOGGLE Pin
156
PICBASIC PRO Compiler
5.82. USBIN
USBIN Endpoint,Buffer,Countvar,Label
Get any available USB data for the Endpoint and place it in the
Buffer. Buffer must be a byte array of suitable length to contain the
data. Countvar should be set to the size of the buffer before USBIN is
executed. It will contain the number of bytes transferred to the buffer.
Label will be jumped to if no data is available.
This instruction may only be used with a PIC MCU that has an on-chip
USB port such as the low-speed PIC16C745 and 765, and the full-speed
PIC18F2450, 2455, 2550, 4450, 4455 and 4550.
The USB and USB18 subdirectories contain the modified Microchip USB
libraries as well as example programs. USB programs require several
additional files to operate (which are in the USB or USB18 subdirectory),
some of which will require modification for your particular application.
See the text file in the subdirectory for more information on the USB
commands. The USB subdirectory is for the low-speed PIC16C devices
and the USB18 subdirectory is for the full-speed PIC18F devices.
cnt = 8
USBIN 1, buffer, cnt, idleloop
157
PICBASIC PRO Compiler
5.83. USBINIT
USBINIT
This instruction may only be used with a PIC MCU that has an on-chip
USB port such as the low-speed PIC16C745 and 765, and the full-speed
PIC18F2450, 2455, 2550, 4450, 4455 and 4550.
The USB and USB18 subdirectories contain the modified Microchip USB
libraries as well as example programs. USB programs require several
additional files to operate (which are in the USB or USB18 subdirectory),
some of which will require modification for your particular application.
See the text file in the subdirectory for more information on the USB
commands. The USB subdirectory is for the low-speed PIC16C devices
and the USB18 subdirectory is for the full-speed PIC18F devices.
USBINIT
158
PICBASIC PRO Compiler
5.84. USBOUT
USBOUT Endpoint,Buffer,Count,Label
Take Count number of bytes from the array variable Buffer and send
them to the USB Endpoint. If the USB buffer does not have room for
the data because of a pending transmission, no data will be transferred
and program execution will continue at Label.
This instruction may only be used with a PIC MCU that has an on-chip
USB port such as the low-speed PIC16C745 and 765, and the full-speed
PIC18F2450, 2455, 2550, 4450, 4455 and 4550.
The USB and USB18 subdirectories contain the modified Microchip USB
libraries as well as example programs. USB programs require several
additional files to operate (which are in the USB or USB18 subdirectory),
some of which will require modification for your particular application.
See the text file in the subdirectory for more information on the USB
commands. The USB subdirectory is for the low-speed PIC16C devices
and the USB18 subdirectory is for the full-speed PIC18F devices.
USBOUT 1, buffer,4,outloop
159
PICBASIC PRO Compiler
5.85. USBSERVICE
USBSERVICE
This instruction may only be used with a PIC MCU that has an on-chip
full-speed USB port such as the PIC18F2450, 2455, 2550, 4450, 4455
and 4550.
USBSERVICE
160
PICBASIC PRO Compiler
5.86. WHILE..WEND
WHILE Condition
Statement...
WEND
i = 1
WHILE i <= 10
Serout 0,N2400,[”No:”,#i,13,10]
i = i + 1
WEND
161
PICBASIC PRO Compiler
5.87. WRITE
WRITE Address,Value
If interrupts are used in a program, they must be turned off (masked, not
DISABLEd) before executing a WRITE, and turned back on (if desired)
after the write instruction is complete. An interrupt occurring during a
WRITE may cause it to fail. The following DEFINE turns interrupts off and
then back on within a WRITE command. Do not use this DEFINE if
interrupts are not used in the program.
DEFINE WRITE_INT 1
WRITE will not work on devices with on-chip I2C interfaced serial
EEPROM like the PIC12CE67x and 16CE62x parts. Use the I2CWRITE
instruction instead.
To write a word, each of the 2 bytes that make up the word must be
written separately:
w Var Word
WRITE 0,w.Byte0
WRITE 1,w.Byte1
162
PICBASIC PRO Compiler
5.88. WRITECODE
WRITECODE Address,Value
Additionally, some flash PIC MCUs, like the PIC18Fxxxx series, require a
portion of the code space to be erased before it can be rewritten with
WRITECODE. See the section on ERASECODE for more information.
If interrupts are used in a program, they must be turned off (masked, not
DISABLEd) before executing a WRITECODE, and turned back on (if
desired) after the write instruction is complete. An interrupt occurring
during a WRITECODE may cause it to fail.
Flash program writes must be enabled in the configuration for the PIC
MCU at device programming time for WRITECODE to be able to write.
163
PICBASIC PRO Compiler
5.89. XIN
XIN DataPin,ZeroPin,{Timeout,Label,}[Var{,...}]
Receive X-10 data and store the House Code and Key Code in Var.
XIN is used to receive information from X-10 devices that can send such
information. X-10 modules are available from a wide variety of sources
under several trade names. An interface is required to connect the
microcontroller to the AC power line. The TW-523 for two-way X-10
communications is required by XIN. This device contains the power line
interface and isolates the microcontroller from the AC line. Since the X-
10 format is patented, this interface also covers the license fees.
XIN only processes data at each zero crossing of the AC power line as
received on ZeroPin. If there are no transitions on this line, XIN will
effectively wait forever.
The Key Code can be either the number of a specific X-10 module or the
function that is to be performed by a module. In normal practice, first a
command specifying the X-10 module number is sent, followed by a
command specifying the function desired. Some functions operate on all
modules at once so the module number is unnecessary. Hopefully, later
164
PICBASIC PRO Compiler
These Key Code numbers are different from the actual numbers sent and
received by the X10 modules. This difference is to match the Key Codes
in the BS2. To remove this Stamp translation, the following DEFINE may
be used:
DEFINE XINXLAT_OFF 1
XIN is not supported on 12-bit core PIC MCUs due to RAM and stack
constraints.
165
PICBASIC PRO Compiler
5.90. XOUT
XOUT DataPin,ZeroPin,
[HouseCode\KeyCode{\Repeat}{,...}]
XOUT only processes data at each zero crossing of the AC power line as
received on ZeroPin. If there are no transitions on this line, XOUT will
effectively wait forever.
The KeyCode can be either the number of a specific X-10 module or the
function that is to be performed by a module. In normal practice, first a
command specifying the X-10 module number is sent, followed by a
command specifying the function desired. Some functions operate on all
modules at once so the module number is unnecessary. Hopefully, later
examples will clarify things. KeyCode numbers 0-15 correspond to
module numbers 1-16.
The KeyCode (function) names (e.g. unitOn) are defined in the file
MODEDEFS.BAS. To use them, add the line:
166
PICBASIC PRO Compiler
Include “modedefs.bas”
These Keycode numbers are different from the actual numbers sent and
received by the X10 modules. This difference is to match the Keycodes
in the BS2. To remove this Stamp translation, the following DEFINE may
be used:
DEFINE XOUTXLAT_OFF 1
XOUT is not supported on 12-bit core PIC MCUs due to RAM and stack
constraints.
167
PICBASIC PRO Compiler
PL-513 Wiring
Wire No. Wire Color Connection
1 Black Zero crossing output
2 Red Zero crossing common
3 Green X-10 transmit common
4 Yellow X-10 transmit input
TW-523 Wiring
Wire No. Wire Color Connection
1 Black Zero crossing output
2 Red Common
3 Green X-10 receive output
4 Yellow X-10 transmit input
Include “modedefs.bas”
XOUT PORTA.1,PORTA.0,[house\unitOff]
Pause 10000 ‘ Wait 10 seconds
Goto loop
168
PICBASIC PRO Compiler
This section is for them. It describes the files used and output generated
by PBP and gives some idea of what is going on.
Three target (PIC MCU) specific header files are used when a program is
compiled. One is used by PBP, the other two are included for use by the
assembler.
A file with the name of the microcontroller followed by the extension .BAS
contains chip specific information needed by PBP. This includes the
memory profile of the chip, which library it uses, and includes for the
definition of the variables it needs. For the PIC16F84, the default
microcontroller, the file is named 16F84.BAS.
A file with the name of the microcontroller followed by the extension .INC
is included in the generated .ASM file to give the assembler information
about the chip, including the default configuration parameters (oscillator
mode, Watchdog Timer setting, etc.). For the PIC16F84, for example,
the file is named 16F84.INC.
Finally, the assembler has its own include file that defines the addresses
of the microcontroller registers. This file is usually named something on
the order of M16F8x.INC and is in the INC subdirectory.
PBP includes a set of library files that contain all of the code and
definition files for a particular group of microcontrollers. In the case of
14-bit core PIC MCUs, for example, these files start with the name
PBPPIC14.
PIC14EXT.BAS contains the external definitions that tells PBP all of the
14-bit core PIC MCU register names.
The assembler generates its own set of files. These include the .HEX
final output file and possibly listing and debugging files.
The .ASM file has a very specific structure. Things must be done in a
particular order for everything to work out properly.
The first item placed in the file is an equate defining which assembler is
to be used, followed by an INCLUDE to tell the assembler which
microprocessor is the target and give it some basic information, such as
the configuration data.
An INCLUDE for the macro file is then placed in the file, followed by an
INCLUDE for the library subroutines.
170
PICBASIC PRO Compiler
There are times, however, when it would be useful to run the PIC MCU 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 or higher.
If you wish to run the serial bus at 19,200 as described above, you would
simply clock the microcontroller 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 .5
seconds with an 8MHz crystal before allowing program execution to
continue.
DEFINE OSC 8
171
PICBASIC PRO Compiler
near the beginning of the PICBASIC PRO program tells PBP an 8MHz
oscillator will be used instead. The acceptable oscillator definitions are:
172
PICBASIC PRO Compiler
The oscillator defaults to XT on most devices. This is the setting for the
default 4MHz oscillator. If a faster oscillator is used, this setting must be
changed to HS.
The Watchdog Timer is enabled by PBP. It is used, along with the TMR0
prescaler, to support the NAP and SLEEP instructions. If neither of the
instructions are used in a program, the Watchdog Timer may be disabled
and the prescaler used for something else.
Code Protect defaults to off but may be set to on when the device is
physically programmed. Do not code protect a windowed device.
See the Microchip data sheet for the particular device for the
configuration data specific to that part.
Variables are stored in the PIC MCU’s RAM registers. The first available
RAM location is $0C for the PIC16F84 and some of the smaller PIC
MCUs, and $20 for the PIC16C74 and other larger PIC MCUs. Refer to
the Microchip PIC MCU data books for the actual location of the start of
the RAM registers for a given microcontroller.
173
PICBASIC PRO Compiler
the best use of available RAM. (For PIC18Xxxxx devices, arrays are
allocated last.)
Arrays must fit entirely within one RAM bank on 12-bit, 14-bit or
PIC17Cxxx devices. Arrays may span banks on PIC18Xxxxx devices.
Byte-, word- and long-sized arrays are only limited in length by the
amount of available memory on PIC18Xxxxx devices. The compiler will
assure that arrays, as well as simple variables, will fit in memory before
successfully compiling.
You can suggest to PBP a particular bank to place the variable in:
If specific bank requests are made, those are handled first. If there is not
enough room in a requested bank, the first available space is used and a
warning is issued.
You can even set specific addresses for variables. In most cases, it is
better to let PBP handle the memory mapping for you. But in some
cases, such as storage of the W register in an interrupt handler, it is
necessary to define a fixed address. This may be done in a similar
manner to bank selection:
174
PICBASIC PRO Compiler
space separate and apart from any other variables you may later create.
This is different than the BS2 where using the canned variables and user
created variables can get you into hot water.
If there is not enough RAM memory available for the variables, an unable
to fit variable in memory error message will be issued.
Reserved words are simply that - words that are reserved for use by the
compiler and may not be defined as either variable names or labels.
These reserved words may be the names of commands, pseudo-ops,
variable types, variables that the compiler uses internally or the names of
the PIC MCU registers. An error will be generated if an attempt is made
to re-declare any of these reserved words.
PIC MCUs have a segmented code space. PIC MCU instructions in 14-
bit core parts 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.
PBP automatically sets these PCLATH bits for you. There are a few
restrictions imposed, however. The PICBASIC PRO library must fit
entirely into page 0 of code space (the first half of page 0 for 12-bit core
devices). Normally this is not an issue as the library is the first thing in a
PICBASIC PRO program and the entire library is smaller than 2K.
175
PICBASIC PRO Compiler
Assembly language interrupt handlers must also fit into page 0 of code
space. Putting them at the beginning of the PICBASIC PRO program
should make this work. See the upcoming section on assembly language
for more information.
The addition of instructions to set the PCLATH bits does add overhead to
the produced code. PBP will set the PCLATH bits before any Call or
Goto instruction on 12-bit core PIC MCUs with more than 512 words of
code space, 14-bit core devices with more than 2K of code space and
PIC17Cxxx devices with more than 8K of code space.
The assembler may issue a warning that a page boundary has been
crossed. This is normal and is there to suggest that you check for any
BRANCHes that may cross a page boundary.
The two main programming limitations that will most likely occur are
running out of RAM memory for variables and running past the first 256
word limit for the library routines. These limitations have made it
necessary to eliminate some compiler commands and modify the
operation of some others.
176
PICBASIC PRO Compiler
The compiler for 12-bit core PIC MCUs uses between 20 and 22 bytes of
RAM for its internal variables, with additional RAM used for any
necessary temporary variables. This RAM allocation includes a 4 level
software stack so that the BASIC program can still nest GOSUBs up to 4
levels deep. Some PIC MCU devices only have 24 or 25 bytes of RAM
so there is very little space for user variables on those devices. If the
Unable to Fit Variable error message occurs during compilation, choose
another PIC MCU with more general purpose RAM.
12-bit core PIC MCUs can call only into the first half (256 words) of a
code page. Since the compiler's library routines are all accessed by
calls, they must reside entirely in the first 256 words of the PIC MCU
code space. Many library routines, such as I2CREAD, are fairly large. It
may only take a few routines to overrun the first 256 words of code
space. If it is necessary to use more library routines that will fit into the
first half of the first code page, it will be necessary to move to a 14- or
16-bit core PIC MCU instead of the 12-bit core device.
177
PICBASIC PRO Compiler
178
PICBASIC PRO Compiler
Upon execution, PBP first compiles the program into assembly language
and then automatically launches an assembler. This converts the
assembler output into the final .HEX file which can be programmed into a
microcontroller.
Two different assemblers may be used with PBP: PM, our assembler,
and MPASM, Microchip’s assembler. There are benefits and drawbacks
to using each assembler. PM is handy because it can be faster than
MPASM and can assemble much larger programs in DOS. PM includes
an 8051-style instruction set that is more intuitive than the Microchip
mnemonics. For complete information on the PM Assembler, see the
PM.TXT file on disk.
MPASM, on the other hand, has the capability of creating a .COD file.
This file contains additional information that can be very useful with
simulators and emulators. MPASM is also more compatible with the wide
variety of assembly language examples found on the web and in
Microchip’s data books.
PBP defaults to using PM. To use MPASM with PBP, install all of the
MPASM files into their own subdirectory. This subdirectory must also be
in the DOS PATH. See the file MPLAB.TXT on the disk and the
microEngineering Labs, Inc. web site for more details.
179
PICBASIC PRO Compiler
@ bsf PORTA,0
Asm
bsf STATUS,RP0
bcf TRISA,0
bcf STATUS,RP0
Endasm
The lines of assembly are copied verbatim into the assembly output file.
This allows the PBP program to use all of the facilities of the assembler.
This also, however, requires that the programmer have some familiarity
with the PBP libraries. PBP’s notational conventions are similar to other
commercial compilers and should come as no shock to programmers
experienced enough to attempt in-line assembly.
B0 Var Byte
Asm
movlw 10
movwf _B0
Endasm
Thus, any name defined in assembly starting with an underscore has the
possibility of conflicting with a PBP generated symbol. If conflict is
avoided, can these underscored assembly values be accessed from
PBP? No. Remember, the underscored names generated by PBP 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
180
PICBASIC PRO Compiler
are to be shared between assembly and PBP, you must define the
variables in PBP.
The first executable line that appears in the PICBASIC PRO source is
where the program starts execution. That statement literally appears in
memory right behind the controller’s startup and library code, right after
the MAIN label.
181
PICBASIC PRO Compiler
If the program is longer than one code page, it could make more sense to
put the assembly language routines at the beginning of the PBP program.
This should ensure them of being in the first code page so that you know
where to find them. This is the way assembly language interrupt routines
should be handled.
If the routines are placed at the front, you must include a GOTO (or JMP)
around the code to the first executable PBP statement. See the section
on interrupts for an example of this.
The actual code for the assembly language routines may be included in
your program or in a separate file. If a routine is used by only one
particular PICBASIC PRO program, it would make sense to include the
assembler code within the PBP source file. This routine can then be
accessed using the CALL command.
Asm
Include “myasm.inc”
Endasm
PIC MCU registers are banked. PBP keeps track of which register bank it
is pointing to at all times. It knows if it is pointing to a TRIS register, for
example, it needs to change the bank select bits before it can access a
PORT.
It also knows to reset the bank select bits to 0 before making a Call or a
Goto. It does this because it can’t know the state of the bank select bits
at the new location. So anytime there is a change of locale or a label that
can be called or jumped to, the bank select bits are zeroed.
It also resets the bank select bits before each ASM and the @ assembler
shortcut. Once again, the assembler routine won’t know the current state
of the bits so they are set to a known state. The assembler code must be
sure to reset the bank select bits before it exits, if it has altered them.
182
PICBASIC PRO Compiler
9. Interrupts
Interrupts can be a scary and useful way to make your program really
difficult to debug.
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 PRO program is off
doing something else. (This particular usage would require a
microcontroller with a hardware serial port.)
There are many ways to avoid using interrupts. Quickly polling a pin or
register bit instead is usually fast enough to get the job done. Or you can
check the value of an interrupt flag without actually enabling interrupts.
However, if you just gotta do it, here are some hints on how to go about
it.
When an interrupt occurs, the PIC MCU 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
hardware stack, which is only 8 deep on the 14-bit core devices to begin
with.
183
PICBASIC PRO Compiler
Once you have dealt with the stack issues, you need to enable the
appropriate interrupts. This usually means setting the INTCON register.
Set the necessary enable bits along with Global Interrupt Enable. For
example:
INTCON = %10010000
Refer to the Microchip PIC MCU 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.
Finally, select the best technique with which to handle your particular
interrupts.
As an example, lets say that the PICBASIC PRO program just started
execution of a Pause 10000 when an interrupt occurs. PBP will flag the
interrupt and continue with the PAUSE. It could be up to 10 seconds later
before the interrupt handler is executed. If it is buffering characters from
a serial port, many characters will be missed.
184
PICBASIC PRO Compiler
To minimize the problem, use only statements that don’t take very long to
execute. For example, instead of Pause 10000, use Pause 1 in a long
FOR..NEXT loop. This will allow PBP to complete each statement more
quickly and handle any pending interrupts.
DISABLE stops PBP from inserting the Call to the interrupt checker after
each statement. This allows sections of code to execute without the
possibility of being interrupted. ENABLE allows the insertion to continue.
INTCON = $80
185
PICBASIC PRO Compiler
This disables all the individual interrupts but leaves the Global Interrupt
Enable bit set.
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, upon return from the interrupt, 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 compiler’s
internal variables for storing the processor context. You cannot tell which
variables are in use by the library routines at any given time.
You should create variables in the PICBASIC PRO program for the
express purpose of saving W, the STATUS register and any other
register that may need to be altered by the interrupt handler. These
variables should not be otherwise used in the BASIC program.
186
PICBASIC PRO Compiler
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.
The routine should end with an Retfie instruction to return from the
interrupt and allow the processor to pick up where it left off in your
PICBASIC PRO program.
If a 14-bit core PIC MCU has more than 2K of code space, an interrupt
stub is automatically added that saves the W, STATUS and PCLATH
registers into the variables wsave, ssave and psave, before going to your
interrupt handler. Storage for these variables must be allocated in the
BASIC program:
In any case, you must restore these registers at the end of your
assembler interrupt handler. If the 14-bit core PIC MCU has 2K or less of
code space, or it is an PIC18Xxxxx device, the registers are not saved.
Your interrupt handler must save and restore any used registers.
Finally, you need to tell PBP that you are using an assembly language
interrupt handler and where to find it. This is accomplished with a
DEFINE:
187
PICBASIC PRO Compiler
Label is the beginning of your interrupt routine. PBP will place a jump to
this Label at location 4 in the PIC MCU.
188
PICBASIC PRO Compiler
retfie
Endasm
189
PICBASIC PRO Compiler
190
PICBASIC PRO Compiler
Unlike the BASIC Stamp, PBP 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 (e.g. 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.
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
191
PICBASIC PRO Compiler
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.
When the Watchdog Timer time-out wakes a PIC MCU 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. PBP programs make use of the PIC's I/O
coherency. The NAP and SLEEP instructions do not disturb the I/O pins.
Without the PC to wake the PIC MCU from an END or STOP statement, it
remains idle until /MCLR is lowered, an interrupt occurs or power is
cycled.
192
PICBASIC PRO Compiler
The BS2's nibble variable type is not implemented in the PICBASIC PRO
Compiler. As PBP allows many more variables than a BS2, simply
changing nibble variable types to bytes will work in many cases.
10.7. No DIRS
The BASIC Stamp variable names Dirs, Dirh, Dirl and Dir0-Dir15
are not defined and should not be used with the PICBASIC PRO
Compiler. TRIS should be used instead, but has the opposite state of
Dirs.
Do this instead:
The BASIC Stamp sets all the variables and registers to 0 when a
program starts. This is not automatically done when a PBP program
starts. In general, the variables should be initialized in the program to an
appropriate state. Alternatively, CLEAR can be used to zero all the
variables when a program starts.
193
PICBASIC PRO Compiler
Highest Precedence
( )
NOT
~
-
ABS COS DCD NCD SIN SQR
*
**
*/
/
//
+
-
<<
>>
MIN
MAX
DIG
REV
&
^
|
&/
/|
^/
&& AND
^^ XOR
|| OR
Lowest Precedence
194
PICBASIC PRO Compiler
10.10. [ ] Versus ( )
Serout 0,T2400,(B0)
Serout 0,T2400,[B0]
10.11. ABS
ABS works slightly differently than on the Stamp in that it will take the
absolute value of a byte as well as a word and long.
The BASIC Stamp allows serial EEPROM space not used for program
storage to store non-volatile data. Since PBP programs execute directly
from the PIC MCU's ROM space, EEPROM storage must be
implemented in some other manner.
The PIC16F84 (the default target for PBP programs) has 64 bytes of on-
chip EEPROM. PBP programs may use this for EEPROM operations
and supports the Stamp's DATA, EEPROM, READ and WRITE commands.
Many other PIC MCUs have up to 1024 bytes of EEPROM space.
195
PICBASIC PRO Compiler
READ and WRITE will not work on devices with on-chip I2C interfaced
serial EEPROM like the PIC12CE67x and PIC16CE62x parts. Use the
I2CREAD and I2CWRITE instructions instead.
10.13. DEBUG
DEBUG sends serial data out on PORTB, pin 0 at 2400 baud, unless
otherwise DEFINEd.
Question marks (?) in DEBUG statements are ignored. The modifier ASC?
Is not supported and should not be used.
10.14. FOR..NEXT
The BS2 automatically sets the direction of the STEP for a FOR..NEXT
loop. If the ending value is smaller than the starting value and a STEP
value is not specified, -1 is assumed. PICBASIC PRO always defaults to
1 if a STEP value is not specified. If a STEP of -1 is desired to make the
loop count backwards, it must be specified:
For i = 10 To 1 Step -1
The PIC MCUs have Call and Return instructions as well as an eight level
stack. PBP programs make use of these instructions and may use four
levels of this stack, with the other four levels being reserved for library
routines. Thus, W6 is unused, subroutines may still be nested up to four
levels deep (12 for PIC17Cxxx and 27 for PIC18Xxxxx) and the number
of GOSUBs is limited only by the PIC MCU's code space.
196
PICBASIC PRO Compiler
The other difference is that the control byte format has changed. You no
longer set the address size as part of the control byte. Instead, the
address size is determined by the type of the address variable. If a byte-
sized variable is used, an 8-bit address is sent. If a word-sized variable is
used, a 16-bit address is sent.
10.17. IF..THEN
The BASIC Stamps and the original PICBASIC compiler only allow a
label to be specified after an IF..THEN. PICBASIC PRO additionally
allows an IF..THEN..ELSE..ENDIF construct as well as allowing
actual code to be executed as a result of an IF or ELSE.
LOOKDOWN and LOOKUP use BS1 syntax. LOOKDOWN2 and LOOKUP2 use
BS2 syntax. LOOKDOWN and LOOKUP only support 8-bit constants in the
table, not variables as in the BS1. You must use LOOKDOWN2 or
LOOKUP2 if variables are required in the table.
The MAX and MIN operator’s function have been altered somewhat from
the way they work on the Stamp and the original PICBASIC Compiler.
MAX will return the maximum of two values. MIN will return the minimum
of two values. This corresponds more closely to most other BASICs and
does not have the 0 and 65535 limit problems of the Stamp’s MIN and
MAX instructions.
In most cases, you need only change MIN to MAX and MAX to MIN in your
Stamp programs for them to work properly with PBP.
197
PICBASIC PRO Compiler
SERIN and SEROUT use BS1 syntax. SERIN2 and SEROUT2 use BS2
syntax. A BS2 style timeout has been added to the SERIN command.
SERIN and SEROUT have been altered to run up to 9600 baud from the
BS1 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.
10.21. SLEEP
Whenever the PIC MCU was reset during SLEEP calibration, it altered the
states of some of the internal registers. For smaller PIC MCUs with few
registers, these registers could be saved before and restored after
calibration resets. However, since PBP may be used on many different
PIC MCUs with many registers that are altered upon reset, this save and
restore proved to be too unwieldy.
198
PICBASIC PRO Compiler
Appendix A
199
PICBASIC PRO Compiler
200
PICBASIC PRO Compiler
Appendix B
Defines
DEFINE ADC_BITS 8 ‘Number of bits in Adcin
result
DEFINE ADC_CLOCK 3 ‘ADC clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ‘ADC sampling time in
microseconds
DEFINE BUTTON_PAUSE 10 ‘Button debounce delay in ms
DEFINE CCP1_REG PORTC ‘Hpwm channel 1 pin port
DEFINE CCP1_BIT 2 ‘Hpwm channel 1 pin bit
DEFINE CCP2_REG PORTC ‘Hpwm channel 2 pin port
DEFINE CCP2_BIT 1 ‘Hpwm channel 2 pin bit
DEFINE CCP3_REG PORTG ‘Hpwm channel 3 pin port
DEFINE CCP3_BIT 0 ‘Hpwm channel 3 pin bit
DEFINE CCP4_REG PORTG ‘Hpwm channel 4 pin port
DEFINE CCP4_BIT 3 ‘Hpwm channel 4 pin bit
DEFINE CCP5_REG PORTG ‘Hpwm channel 5 pin port
DEFINE CCP5_BIT 4 ‘Hpwm channel 5 pin bit
DEFINE CHAR_PACING 1000 ‘Serout character pacing in us
DEFINE DEBUG_REG PORTB ‘Debug pin port
DEFINE DEBUG_BIT 0 ‘Debug pin bit
DEFINE DEBUG_BAUD 2400 ‘Debug baud rate
DEFINE DEBUG_MODE 1 ‘Debug mode: 0 = True, 1 =
Inverted
DEFINE DEBUG_PACING 1000 ‘Debug character pacing in us
DEFINE DEBUGIN_REG PORTB ‘Debugin pin port
DEFINE DEBUGIN_BIT 0 ‘Debugin pin bit
DEFINE DEBUGIN_MODE 1 ‘Debugin mode: 0 = True, 1 =
Inverted
DEFINE HPWM2_TIMER 1 ‘Hpwm channel 2 timer select
DEFINE HPWM3_TIMER 1 ‘Hpwm channel 3 timer select
DEFINE HSER_BAUD 2400 ‘Hser baud rate
DEFINE HSER_SPBRG 25 ‘Hser spbrg init
DEFINE HSER_RCSTA 90h ‘Hser receive status init
DEFINE HSER_TXSTA 20h ‘Hser transmit status init
DEFINE HSER_EVEN 1 ‘Use only if even parity
desired
DEFINE HSER_ODD 1 ‘Use only if odd parity
desired
DEFINE HSER_BITS 9 ‘Use for 8 bits + parity
DEFINE HSER_CLROERR 1 ‘Automatically clear Hserin
overflow errors
DEFINE HSER_PORT 1 ‘Hser port to use on devices
with more than one
DEFINE HSER2_BAUD 2400 ‘Hser2 baud rate
DEFINE HSER2_SPBRG 25 ‘Hser2 spbrg2 init
DEFINE HSER2_RCSTA 90h ‘Hser2 receive status init
DEFINE HSER2_TXSTA 20h ‘Hser2 transmit status init
DEFINE HSER2_EVEN 1 ‘Use only if even parity
desired
DEFINE HSER2_ODD 1 ‘Use only if odd parity
desired
201
PICBASIC PRO Compiler
202
PICBASIC PRO Compiler
Appendix C
Reserved Words
203
PICBASIC PRO Compiler
204
PICBASIC PRO Compiler
Appendix D
ASCII Table
8 8 BS (backspace) Ctrl-H
205
PICBASIC PRO Compiler
206
PICBASIC PRO Compiler
32 20 Space 64 40 @ 96 60 `
33 21 ! 65 41 A 97 61 a
34 22 " 66 42 B 98 62 b
35 23 # 67 43 C 99 63 c
36 24 $ 68 44 D 100 64 d
37 25 % 69 45 E 101 65 e
38 26 & 70 46 F 102 66 f
39 27 ' 71 47 G 103 67 g
40 28 ( 72 48 H 104 68 h
41 29 ) 73 49 I 105 69 i
42 2A * 74 4A J 106 6A j
43 2B + 75 4B K 107 6B k
44 2C , 76 4C L 108 6C l
45 2D - 77 4D M 109 6D m
46 2E . 78 4E N 110 6E n
47 2F / 79 4F O 111 6F o
48 30 0 80 50 P 112 70 p
49 31 1 81 51 Q 113 71 q
50 32 2 82 52 R 114 72 r
51 33 3 83 53 S 115 73 s
52 34 4 84 54 T 116 74 t
53 35 5 85 55 U 117 75 u
54 36 6 86 56 V 118 76 v
55 37 7 87 57 W 119 77 w
207
PICBASIC PRO Compiler
56 38 8 88 58 X 120 78 x
57 39 9 89 59 Y 121 79 y
58 3A : 90 5A Z 122 7A z
59 3B ; 91 5B [ 123 7B {
60 3C < 92 5C \ 124 7C |
61 3D = 93 5D ] 125 7D }
62 3E > 94 5E ^ 126 7E ~
63 3F ? 95 5F _ 127 7F DEL
208
PICBASIC PRO Compiler
Appendix E
Contact Information
209
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
Software License