Welcome

MicroCode Studio is a powerful, visual Integrated Development Environment (IDE) with In Circuit Debugging (ICD) capability designed specifically for microEngineering Labs PICBasic PRO compiler. The code explorer allows you to automatically jump to include files, defines, constants, variables, aliases and modifiers, symbols and labels that are contained within your source code. It's easy to set up your compiler, assembler and programmer options or you can let MicroCode Studio do it for you with its built in autosearch feature. Compilation and assembler errors can easily be identified and corrected using the error results window. MicroCode Studio even comes with a serial communications window.

The In Circuit Debugger (ICD), enables you to execute a PICBasic Program on a host PIC microcontroller and view variable values, Special Function Registers (SFR), memory and EEPROM as the program is executing. You can toggle multiple breakpoints and step through your PICBasic code line by line. The graphical interface is built on microEngineering Labs debug architecture, which is both efficient and robust.

See Also

Menu Options
The Main Toolbar
The Edit Toolbar
The Compile and Program Toolbar
The ICD Toolbar
The Code Explorer
The Serial Communications Window
PICBasic Options
Editor Options
Installing a Programmer
Using the ICD

MicroCode Studio is an easy to use code editor for microEngineering Labs PICBasic compilers. The main editor provides full syntax highlighting of your code with context sensitive keyword help and syntax hints. The code explorer allows you to automatically jump to include files, defines, constants, variables, aliases and modifiers, symbols and labels that are contained within your source code. Full cut, copy, paste and undo is provided, together with search and replace features. Its easy to set up your compiler, assembler and programmer options or you can let MicroCode Studio do it for you with its built in autosearch feature. Compilation and assembler errors can easily be identified and corrected using the error results window. MicroCode Studio even comes with a serial communications window, allowing you to debug and view serial output from your microcontroller.

MicroCode Studio also has an In Circuit Debugger (ICD), enabling you to execute a PICBasic Program on a host PIC microcontroller and view variable values, Special Function Registers (SFR), memory and EEPROM as the program is executing. You can toggle multiple breakpoints and step through your PICBasic code line by line. The graphical interface is built on microEngineering Labs debug architecture, which is both efficient and robust.

If you have any questions, problems or comments about this product, please feel free to contact me directly here. Suggestions on how to improve this product will be most welcome.


Mecanique

License Agreement

Please read the following carefully before using this software. By installing the software you are agreeing to be bound by the following terms and conditions. MicroCode Studio is free for non-commercial use. It is not time limited in any way. If you are a commercial organisation or educational establishment, you need to purchase MicroCode Studio Plus.

Please note that this Software Package is not copyright free. If you wish to redistribute this Software Package or make it available for download via the Internet or World Wide Web (WWW), you must contact Mecanique UK first and obtain permission.

Copyright

All title and copyrights in and to the Software Package and any copies of the Software Package are owned by Mecanique UK with these exceptions. The Software Package is protected by copyright laws and international treaty provisions. Therefore, you must treat the software like any other copyrighted material. The Software Package and elements of the Software Package may not be reverse engineered, sold, lent, displayed, hired out, or copied without seeking written approval from Mecanique UK. The Software Package may not be used in any commercial context whatsoever. You may not sublicense, assign or sell the Software Package and you agree to use your best efforts to ensure that the terms of this agreement are adhered to.

Term

This Agreement is effective from the date the Software Package is installed on your machine and will remain in force until terminated by destroying all parts of the Software Package or breach of any of the terms contained in this Agreement whereupon termination shall be immediate.

Disclaimer of Liability

Mecanique UK disclaims all warranties, express or implied, including the implied warranty of fitness for a particular purpose and the implied warranty of merchantability. In no event shall Mecanique UK be liable for any incidental, indirect, special or consequential damages arising out of the use of this software.


Mecanique

COPYRIGHT NOTICE

Parts of this online help file 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.

Publication and redistribution of this manual over the Internet or in any other medium without prior written consent is expressly forbidden. In all cases this copyright notice must remain intact and unchanged.

microEngineering Labs, Inc.
2845 Ore Mill Road, STE 4
Colorado Springs CO 80904
(719) 520-5323
(719) 520-1867 fax
email: support@melabs.com
web: www.melabs.com

TRADEMARKS

PIC™, PICmicro™, MPLAB™ are registered trademarks of Microchip Technology Inc. in the USA and other countries. PICBASIC™, PICBASIC PRO™, PICPROTO™ and EPIC™ are trademarks of Microchip Technology Inc. in the USA and other countries.


Mecanique

Contact Information

Mecanique
85 Marine Parade
Saltburn by the Sea
TS12 1BZ
United Kingdom
www.mecanique.co.uk

Tel | from the UK | 01287 625168
 | outside the UK | +44 1287 625168
email |  | enquiries@mecanique.co.uk


Purchase MicroCode Studio Plus

MicroCode Studio Plus

MicroCode Loader
In Circuit Debugger (ICD)
Where to Purchase

The standard version of MicroCode Studio is free for non-commercial use. If you are a commercial organisation or educational establishment, you need to purchase MicroCode Studio Plus.

MicroCode Loader

MicroCode Studio Plus also comes with MicroCode Loader, a bootloader application that allows you to program most of the 16F8xx(A) and 18Fxxx(x) series of microcontroller without the need of a hardware programmer. For an up to date list of supported devices, visit supported loader devices.

MicroCode Loader can be used as a stand alone application, or it can fully integrate with the MicroCode Studio Plus IDE. For information on MicroCode Loader, check out the online website here.

In Circuit Debugger (ICD)

The MicroCode Studio In Circuit Debugger (ICD) enables you to execute a PICBasic Program on a host PIC microcontroller and view variable values, Special Function Registers (SFR), memory and EEPROM as your program is running. Each line of source code is animated in the main editor window, showing you which program line is currently being executed by the host microcontroller. You can even toggle multiple breakpoints and step through your PICBasic code line by line. Using the MicroCode Studio ICD can really help accelerate program development. It's also a lot of fun and a great tool for learning more about programming PIC microcontrollers.

If you want to use additional ICD Models, you should also consider purchasing MicroCode Studio Plus. For an up to date list of supported models, visit supported models.

You can purchase the MicroStudio Studio Plus CD from:

United Kingdom

Mecanique
85 Marine Parade
Saltburn by the Sea
TS12 1BZ
United Kingdom
Voice: +44 (0)1287 625168
www.mecanique.co.uk
sales@mecanique.co.uk

For overseas orders, please visit one of our resellers

  • MicroCode Studio PLUS reseller


The Main Menu

File Menu

  • New - Creates a new document. A header is automatically generated, showing information such as author, copyright and date. To toggle this feature on or off, or edit the header properties, you should select editor options. When a new document is created, the default target processor device is set to the 16F877. To change the default, edit the file 'default.ini', located in your main installation folder. You need to restart MicroCode Studio after making the changes.
  • Open - Displays a open dialog box, enabling you to load a document into the MicroCode Studio IDE. If the document is already open, then the document is made the active editor page.
  • Save - Saves a document to disk. This button is normally disabled unless the document has been changed. If the document is 'untitled', a save as dialog is invoked. A save as dialog is also invoked if the document you are trying to save is marked as read only.
  • Save As - Displays a save as dialog, enabling you to name and save a document to disk.
  • Close - Closes the currently active document
  • Close All - Closes all editor documents and then creates a new editor document.
  • Reopen - Displays a list of Most Recently Used (MRU) documents.
  • Print Setup - Displays a print setup dialog.
  • Print Preview - Displays a print preview window.
  • Print - Prints the currently active editor page.
  • Exit - Enables you to exit MicroCode Studio

Edit Menu

  • Undo - Cancels any changes made to the currently active document page.
  • Redo - Reverse an undo command.
  • Cut - Cuts any selected text from the active document page and places it into the clipboard. This option is disabled if no text has been selected.
  • Copy - Copies any selected text from the active document page and places it into the clipboard. This option is disabled if no text has been selected.
  • Paste - Paste the contents of the clipboard into the active document page. This option is disabled if the clipboard does not contain any suitable text.
  • Delete - Deletes any selected text. This option is disabled if no text has been selected.
  • Select All - Selects the entire text in the active document page.
  • Find - Displays a find dialog.
  • Replace - Displays a find and replace dialog.
  • Find Next - Automatically searches for the next occurrence of a word. If no search word has been selected, then the word at the current cursor position is used. You can also select a whole phrase to be used as a search term. If the editor is still unable to identify a search word, a find dialog is displayed.

View Menu

  • Code Explorer - Display or hide the code explorer window.
  • Serial Communicator - Displays the Serial Communicator software. For more information, see the online help supplied with Serial Communicator.
  • EasyHID USB Wizard - Automatically create code for USB HID projects (MCS Plus only).
  • ICD Model Creator - In Circuit Debugging (ICD) model creator software.
  • Loader - Displays the MicroCode Loader application. This option is only available with MicroCode Studio Plus.
  • Loader Options - Displays the MicroCode Loader options dialog. This option is only available with MicroCode Studio Plus.
  • Compile and Program Options - Displays the Compile and Program Options dialog.
  • Editor Options - Displays the main editor options dialog.
  • Toolbars - Changes toolbar icon size and colors.

Project Menu

  • Compile - Selecting this option will compile the currently active editor page.
  • Compile and Program - Selecting this option will compile the currently active editor page and then automatically start your chosen programmer.
  • Program - Automatically start your chosen programmer.
  • ICD Compile - Selecting this option will compile the currently active editor page with debugging information.
  • ICD Compile and Program - Selecting this option will compile the currently active editor page with debugging information and then automatically start your chosen programmer.

Help Menu

  • Help Topics - Displays this file.
  • Loader Help Topics - Displays the MicroCode Loader help file. This option is only available with MicroCode Studio Plus.
  • Online Forum - Visit the PICBASIC online forum.
  • About - Display about dialog, giving both the MicroCode Studio and PICBasic version numbers.

See Also


The Main Toolbar

New

Creates a new document. A header is automatically generated, showing information such as author, copyright and date. To toggle this feature on or off, or edit the header properties, you should select the editor options dialog from the main menu.

When a new document is created, the default target processor device is set to the 16F877. To change the default, edit the file 'default.ini', located in your main installation folder. You need to restart MicroCode Studio after making the changes.

Open

Displays a open dialog box, enabling you to load a document into the MicroCode Studio IDE. If the document is already open, then the document is made the active editor page.

Save

Saves a document to disk. This button is normally disabled unless the document has been changed. If the document is 'untitled', a save as dialog is invoked. A save as dialog is also invoked if the document you are trying to save is marked as read only.

Cut

Cuts any selected text from the active document page and places it into the clipboard. This option is disabled if no text has been selected.

Copy

Copies any selected text from the active document page and places it into the clipboard. This option is disabled if no text has been selected.

Paste

Paste the contents of the clipboard into the active document page. This option is disabled if the clipboard does not contain any suitable text.

Undo

Cancels any changes made to the currently active document page.

Redo

Reverse an undo command.

Print

Prints the currently active editor page.

See Also


The Edit Toolbar

Find

Displays a find dialog.

Find and Replace

Displays a find and replace dialog.

Indent

Shifts all selected lines to the next tab stop. If multiple lines are not selected, a single line is moved from the current cursor position. All lines in the selection (or cursor position) are moved the same number of spaces to retain the same relative indentation within the selected block. You can change the tab width from the editor options dialog.

Outdent

Shifts all selected lines to the previous tab stop. If multiple lines are not selected, a single line is moved from the current cursor position. All lines in the selection (or cursor position) are moved the same number of spaces to retain the same relative indentation within the selected block. You can change the tab width from the editor options dialog.

Block Comment

Adds the comment character to each line of a selected block of text. If multiple lines are not selected, a single comment is added to the start of the line containing the cursor.

Block Uncomment

Removes the comment character from each line of a selected block of text. If multiple lines are not selected, a single comment is removed from the start of the line containing the cursor.

See Also


The Compile and Program Toolbar

Compile

Pressing this button will compile the currently active editor page. The compile button will generate a *.hex file, which you then have to manually program into your microcontroller. Alternatively, press F11 to automatically start your chosen programmer after compilation has finished. For more information on setting up a programmer, refer to the Using a Programmer with MicroCode Studio section. If you want to use the In Circuit Debugging (ICD) capability of MicroCode Studio, you should use the ICD compile button instead. The ICD process will not work if compiled using this button.

NOTE : Pressing the compile button will automatically save all open files to disk. This is to ensure that the PICBasic compiler is passed an up to date copy of the file(s) your are editing.

Compile and Program

Pressing this button will compile the currently active editor page. The compile and program button will generate a *.hex file and then automatically start your chosen programmer. For more information on setting up a programmer, refer to the Using a Programmer with MicroCode Studio section. If you want to use the In Circuit Debugging (ICD) capability of MicroCode Studio, you should use the ICD compile and program button instead. The ICD process will not work if compiled using this button.

You can also select different programmers from the main toolbar by pressing the small down arrow, located to the right of the compile and program button.

NOTE : Pressing the compile button will automatically save all open files to disk. This is to ensure that the PICBasic compiler is passed an up to date copy of the file(s) your are editing.

Loader Verify

This button will verify a *.hex file (if one is available) against the program resident on the microcontroller. The loader verify button is only displayed if MicroCode Loader is the currently selected programmer. Please note that MicroCode Loader is only available with MicroCode Studio Plus.

Loader Read

This button will upload the code and data contents of a microcontroller to MicroCode Loader. The loader read button is only displayed if MicroCode Loader is the currently selected programmer. Please note that MicroCode Loader is only available with MicroCode Studio Plus.

Loader Erase

This button will erase program memory for the 18Fxxx(x) series of microcontroller. The loader erase button is only displayed if MicroCode Loader is the currently selected programmer. Please note that MicroCode Loader is only available with MicroCode Studio Plus.

Loader Information

This button will display the microcontroller loader firmware version. The loader information button is only displayed if MicroCode Loader is the currently selected programmer. Please note that MicroCode Loader is only available with MicroCode Studio Plus.

See Also


The ICD Toolbar

The In Circuit Debugger (ICD) toolbar is only visible when a suitable ICD model is available, which is dependent on the selected microcontroller.

ICD Compile

The ICD compile button works in exactly the same way as the main MicroCode Studio compile toolbar button, with the exception that additional debug information is automatically included in the build. ICD compile will generate a hex file, which you then have to manually program into your microcontroller. Alternatively, press F11 to automatically start your chosen programmer after compilation has finished. For more information on setting up a programmer, refer to the Using a Programmer with MicroCode Studio section. Remember, you can only interface to the ICD after building your project with either ICD compile or ICD compile and program.

NOTE : Pressing the compile button will automatically save all open files to disk. This is to ensure that the PICBasic compiler is passed an up to date copy of the file(s) your are editing. In addition, the generated *.hex file programmed into your MCU will only work under the control of the ICD process. It will not work independently of the ICD process. If you do not intend to use the ICD, use the compile button instead.

ICD Compile and Program

The ICD compile and program button works in exactly the same way as the main MicroCode Studio compile and program toolbar button, with the exception that additional debug information is automatically included in the build. ICD compile and program will generate a hex file and then automatically start your chosen programmer. For more information on setting up a programmer, refer to the Using a Programmer with MicroCode Studio section. Remember, you can only interface to the ICD after building your project with either ICD compile or ICD compile and program.

NOTE : Pressing the compile button will automatically save all open files to disk. This is to ensure that the PICBasic compiler is passed an up to date copy of the file(s) your are editing. In addition, the generated *.hex file programmed into your MCU will only work under the control of the ICD process. It will not work independently of the ICD process. If you do not intend to use the ICD, use the compile and program button instead.

ICD Control

The control buttons enable you to run, stop, pause and step the ICD. Remember, you must build your project with either ICD compile or ICD compile and program before pressing the run button. When the ICD has started, you can select the pause button to suspend the ICD, allowing you to step through the program line by line. Alternatively, you can have the pause button in the down position before starting the ICD. If a breakpoint is reached during program execution, MicroCode Studio will automatically pause the ICD.

ICD Communications Port

The communications port drop down box enables you to select the serial port used by the ICD to communicate with the target microcontroller. The ICD only communicates with a PIC microcontroller using its hardware USART. For details on setting up your hardware for use by the ICD, please refer to the Setting Up Your Hardware section.

ICD Breakpoint

Breakpoints are used to stop the execution of a program at any given point. The MicroCode Studio ICD enables you to add multiple breakpoints. You can even have breakpoints in PICBasic include files. To add a breakpoint, move the editor cursor to the line requiring a breakpoint. Next, press the ICD breakpoint button. To remove the breakpoint, press the button again. You can also add a breakpoint by using the left mouse button and clicking on the gray bar located to the left of the MicroCode Studio editor.

ICD Animate

When the animate button is down (default), MicroCode Studio animates program execution. That is, you will see each program line highlighted in the main editor window as it is being executed.

In addition, the ICD Explorer is updated with the current values of all variables, SFRs, memory and EEPROM. When the animate button is in the up position, MicroCode Studio will not animate program execution. Neither the main editor window or the ICD Explorer is updated.

The ICD will animate at different speeds, depending on both the OSC setting of the target device and also the speed of the host PC. You will generally get better update speeds when using higher OSC settings. Don't expect blistering animation speeds if you are running a P90 with 8MB of RAM and a target microcontroller running at 4MHz. In ideal situations, you can expect update speeds of 10 Instructions Per Second (IPS) when the animate button is in the down position. If the animation is switched off, you can expect thousands of IPS. However, the ICD is highly configurable. You can get the ICD to run in real time for critical code sections if you want. For more information on how to configure the ICD, please refer to the Reducing the ICD Code Overhead and Increasing the Speed of the ICD sections.

See Also


The Compile and Program Toolbar

The Device (MCU) Toolbar

Before compiling your program, ensure that the correct processor has been selected from the drop down target processor box. You can generate a lot of errors, particularly at the assembler stage if an incorrect processor is selected. Once you have compiled and assembled your program, you do not need to set the target processor each time you open your source file. MicroCode Studio will automatically select the correct device for you.

The device toolbar also has a command line edit box. This allows you to pass user definable command line options to the compiler. This is particularly useful when using command line 'define' directives, which can be passed to the compiler.

See Also


Code Explorer

The code explorer allows you to automatically jump to include files, defines, constants, variables, aliases and modifiers, symbols and labels that are contained within your source code. MicroCode Studio will also identify duplicate include files, defines, constants, variables, aliases and modifiers, symbols and labels .

Viewing Include Files

When you click on an include file, the editor will automatically open that file for viewing and editing. If the include file cannot be found or does not exist, a new document is created for you. If this happens and you are sure that the file does exist, trying adding an include path using the options dialog to enable the editor to find the file.

Sorting

To sort the Code Explorer nodes, right click of the explorer window and select the 'sort' option.


Results Window

Error Results Window

The error results window will only appear if errors are encountered when compiling or assembling your program. The window enables you to quickly jump to lines of code that contain errors by clicking on the reported error contained in the window. If no errors are reported, the error results window is hidden and a compilation success message is displayed in the MicroCode Studio status bar.


Serial Communications Window

Serial Communicator

The Serial Communicator enables you to connect to and monitor a serial port. For more information, see the online help provided with the Serial Communicator software.


Options

Options Window

The options window enables you to configure and control many of MicroCode Studios compiler, assembler and programming features.

Compiler Options

You can get MicroCode Studio to uses the default compiler path by clicking on the 'Default' button. Alternatively, you can select the directory manually by selecting the find manually button.

  • Use Compiler Long Words. If enabled, LONG variables are made available. This mode is only available when compiling for a target device with the PIC18 prefix. LONG variables are interpreted as twos-complement, signed values.
  • Generate COFF. If enabled, generates a COFF debug file.
  • Uses MPASMX Assembler. If enabled, ueses the Microchip MPASM assembler. By default the compiler uses MPASMWin.

Assembler Options

  • MPASM Close After Compile. If enabled, the assembler will automatically close after assembly.
  • MPASM Listing File. If enabled, generates a detailed assembler listing file.
  • MPASM Macro Expansion. If enabled, expands assembler macros.

User Command Line Options

This edit box can be used to enter your own command line parameters. For a detailed list of available options, you should refer to your PBP manual.

Programmer Options

This section enables you to configure the programmer used by the IDE.

See Also

Editor Options


Editor Options

The editor options dialog enables you to configure and control many of MicroCode Studios features. The window is composed of four main areas, which are accessed by selecting the General, Highlighter and Program Header.

Tab Options

General
Highlighter
Program Header

See Also

Compile and Program Options


General

General Tab

Show Line Numbers in Left Gutter

Display line numbers in the editors left hand side gutter. If enabled, the gutter width is increased in size to accommodate a five digit line number.

Show Right Gutter

Displays a line to the right of the main editor. You can also set the distance from the left margin (in characters). This feature can be useful for aligning your program comments.

Use Smart Tabs

Normally, pressing the tab key will advance the cursor by a set number of characters. With smart tabs enabled, the cursor will move to a position along the current line which depends on the text on the previous line. Can be useful for aligning code blocks.

Convert Tabs to Spaces

When the tab key is pressed, the editor will normally insert a tab control character, whose size will depend on the value shown in the width edit box (the default is four spaces). If you then press the backspace key, the whole tab is deleted (that is, the cursor will move back four spaces). If convert tabs to spaces is enabled, the tab control character is replaced by the space control character (multiplied by the number shown in the width edit box). Pressing the backspace key will therefore only move the cursor back by one space.

NOTE : Internally, the editor does not use hard tabs, even if convert tabs to spaces is unchecked.

Automatically Indent

When the carriage return key is pressed in the editor window, automatically indent will advance the cursor to a position just below the first word occurrence of the previous line. When this feature is unchecked, the cursor just moves to the beginning of the next line.

Wrap Document Selection Tabs

The editor allows multiple documents to be open at the same time. If many documents are open, the page selection tabs will extend beyond the available display space. Enabling wrap document selection tabs ensures that all of the tabs remain visible, no matter how many documents are open.

Automatically Jump to First Error

When this is enabled, MicroCode Studio will automatically jump to the first error line if any errors are generated during compilation.

Clear Undo History After Compile

If checked, a successful compilation will clear the undo history buffer. A history buffer takes up system resources, especially if many documents are open at the same time. It's a good idea to have this feature enabled if you plan to work on many documents at the same time.

Open Last File(s) When Application Starts

When checked, the documents that were open when MicroCode Studio was closed are automatically loaded again when the application is restarted.

Display Full Filename Path in Application Title Bar

By default, MicroCode Studio only displays the document filename in the main application title bar (that is, no path information is includes). Check display full pathname if you would like to display additional path information in the main title bar.

Prompt if File Reload Needed

MicroCode Studio automatically checks to see if a file time stamp has changed after compilation, or if another document page tab is selected. If it has, then a dialog box is displayed asking if the file should be reloaded. If prompt on file reload is unchecked, the file is automatically reloaded without any prompting.

Auto Change Identifiers

When checked, this option will automatcally change the identifier being typed to match that of the actual declaration. For example, if you have the following declaration,

MyIndex VAR BYTE

and you type 'myindex' in the editor window, MicroCode Studio will automatically change 'myindex' to 'MyIndex'. Please note that 'Auto Change Identifiers' does not actually change the value typed, it just changes the way it is displayed in the editor window. If you copy the above example and paste it into another document, it will still show as 'myindex'. Code within ASM...ENDASM blocks are not automatically changed, even if 'Auto Change Identifiers' is enabled. This feature is also only scoped within the currently active document. It will not change identifiers that have been declared in an INCLUDE file.

Use .PBP as Default Extension

Enabling this option ensures that *.PBP is used as the default extension when saving files to disk. If you want the default extension to be *.BAS, then uncheck this option.

Default Source Folder

MicroCode Studio will automatically go to this folder when you invoke the file open or save as dialogs. To disable this feature, uncheck the 'Enabled' option, shown directly below the default source folder.


Highlighter

Highlighter Tab

Font Properties

Use font properties to change the editor font name and size.

Item Properties

The syntax highlighter tab lets you change the the color and attributes (for example, bold and italic) of the following items:

  • Comment
  • Reserved Word
  • Identifier
  • Symbol
  • String
  • Number
  • Assembler

Reserved Word Formating

This option enables you to set how MicroCode Studio displays keywords. For example, you can get MicroCode Studio to automatically uppercase, lowercase or uppercase the first character after a keyword has been typed.


Header

Program Header Tab

The header notice tab allows you to change the author and copyright name that is placed in a header when a new document is created. For example,

'****************************************************************
'* Name    : UNTITLED.BAS                                        *
'* Author  : David John Barker                                   *
'* Notice  : Copyright (c) 2001 Mecanique                        *
'*         : All Rights Reserved                                 *
'* Date    : 10/15/01                                            *
'* Version : 1.0                                                 *
'* Notes   :                                                     *
'*         :                                                     *
'****************************************************************

If you do not want to use this feature, simply deselect the enable check box.


Programmer Tab

Programmer

With MicroCode Studio, you can start your preferred programming software from within the Integrated Development Environment (IDE). This enables you to compile and then program your microcontroller with just a few mouse clicks (or keyboard strokes, if you prefer). The first thing you need to do is tell MicroCode Studio which programmer you are using.

Select the programmer you want MicroCode Studio to use, then choose the Next button. MicroCode Studio will now search your computer until it locates the required executable. If your programmer is not in the list, you will need to create a custom programmer entry.

Your programmer is now ready for use. When you press the Compile and Program button on the main toolbar, you PICBasic program is compiled and the programmer software started. The hex filename and target device is automatically set in the programming software (if this feature is supported), ready for you to program your microcontroller.

You can also select different programmers from the main toolbar by clicking on the small drop down arrow to the right of the compile icon, as shown below.

See Also


Using a Programmer - Custom

Creating a Custom Programmer Entry

In most cases, MicroCode Studio has a set of pre-configured programmers available for use. However, if you use a programmer not included in this list, you will need to add a custom programmer entry. To do this, check the 'create a custom programmer entry', shown below

The next screen asks you to enter the display name. This is the name that will be displayed in any programmer related drop down boxes. MicroCode Studio enables you to add and configure multiple programmers. You can easily switch from different types of programmer from the compile and program button, located on the main editor toolbar. The multiple programmer feature means you do not have to keep reconfiguring your system when you switch programmers. MicroCode Studio will remember the settings for you. In the example below, the display name is 'My New Programmer'.

The next screen asks for the programmer executable name. You do not have to give the full path, just the name of the executable name will do.

The next screen is the path to the programmer executable. You can let MicroCode Studio find it automatically, or you can select it manually.

The final screen is used to set the parameters that will be passed to your programmer. Some programmers, for example, EPICWin allow you to pass the device name and hex filename. MicroCode Studio enables you to 'bind' the currently selected device and hex file you are working on.

For example, if you are compiling 'blink.bas' in MicroCode Studio, using a 16F628, you would want to pass the 'blink.hex' file to the programmer and also the name of the microcontroller you intend to program. Here is the EPICWin example:

-pPIC$target-device$ $hex-filename$

When EPICWin is started, the device name and hex filename are 'bound' to $target-device$ and $hex-filename$ respectively. In the 'blink.bas' example, the actual parameter passed to the programmer would be:

-pPIC16F628 blink.hex

See Also


Programmer Options

Additional Programmer Options

If you install a pre-configured programmer, many of the command line options are taken care for you by MicroCode Studio. However, you can add additional key commands to tell your programming software what to do when it is started by MicroCode Studio. For example, you may want your programmer to start programming the target device as soon as it is displayed, rather than having to manually start the programming operation

Example

This example shows you how to set EPICWin, Meloader and the Warp13 to automatically start programming the target device when opened by MicroCode Studio. First, you need to select VIEW...OPTIONS from the MicroCode Studio menu bar. Next, select the 'programmer' tab.

Select the programmer you want to edit, and then press the 'Edit...' button. This will invoke the edit programmer wizard. Keep pressing the next button until you reach the 'Select Parameters' screen, as shown below.

All you now need to do is add the relevant key commands for your particular programmer, like this...

Programmer | Parameters
Meloader | $long-hex-filename$ [ALT+L,P]
EPICWin | -pPIC"$target-device$" $long-hex-filename$ [Alt+R,P]
Newfound Warp13 | $hex-filename$ -$target-device$ [Alt+P,P]

Please note that in all of the above examples, the single characters must be in uppercase.

See Also


ICD Overview

Overview

The MicroCode Studio ICD enables you to execute a PICBasic Program on a host PIC microcontroller and view variable values, Special Function Registers (SFR), memory and EEPROM as the program is executing. You can toggle multiple breakpoints and step through your PICBasic code line by line. The graphical interface is built on microEngineering Labs debug architecture, which is both efficient and robust.

See Also

System Requirements
Hardware Setup
Available Models
Code Overhead
Execution Speed
The ICD Toolbar
The ICD Explorer
Breakpoints
Sample Project
ICD Serial Communications
Problems


System Requirements

In order to run the ICD, you will need a copy of either MicroCode Studio or MicroCode Studio Plus. In addition, you will also need the microEngineering Labs PICBasic PRO compiler, version 2.20 or higher. The MicroCode Studio ICD will not work with the PICBasic standard compiler.

See Also


Hardware Setup

The MicroCode Studio ICD does not require any special hardware to host the microcontroller. However, you will need a host board that supports RS232 serial communication. Many boards will support the MicroCode Studio ICD. For example, the AMICUS board enables you to connect just a standard USB cable between the board and the host PC and you are ready to go!

Amicus Development Board with
PIC 18F25K20

There are many other boards that support RS232. All you have to do is connect your chosen board to the computer running MicroCode Studio using a suitable cable. Alternatively, you can build your own board that will connect to the MicroCode Studio ICD.

Click for larger image...

Connecting a microcontroller to MicroCode Loader
with optional software reset. Courtesy Reynolds Electronics

The MicroCode Studio ICD communicates with the microcontroller using its hardware USART. You should refer the the Microchip data sheet for the microcontroller you are using if you are unsure which pins the device uses for its USART. For example, the PIC16F628A uses PORTB.1 for RX and PORTB.2 for TX. The PIC16F877A uses PORTC.7 for RX and PORTC.6 for TX.

The ICD will work with microcontrollers running at different clock speeds. However, it is essential that your PICBasic code has the correct oscillator setting defined. If your target device is running at a different speed, you must make sure the appropriate define is used in your PICBasic code. For example, if you have a microcontroller running at 20MHz, use the following statement at the beginning of your program:

DEFINE OSC 20

Failing to set the correct oscillator setting causes problems for the ICD. In short, if the setting in your code does not match the actual speed of your PIC microcontroller, the ICD will not work.

See Also


ICD Models

Available ICD Models

MicroCode Studio uses an ICD Model in order to initialise and control the operation of the ICD for a given PIC microcontroller.

MicroCode Studio - Standard Version

The ICD for MicroCode Studio supports the following PIC microcontroller devices.

16F887
16F877A
18F25K20
18F452
18F4520

MicroCode Studio PLUS

MicroCode Studio Plus supports many more common microcontrollers. The good news is that if no ICD model is supported, you can create your own using the ICD Model Creator software, supplied with MicroCode Studio. If you would like to purchase MicroCode Studio Plus, please read How to Purchase MicroCode Studio Plus.

See Also


ICD Reduce Code Overhead

Reducing the ICD Code Overhead

When you build a project using the ICD Compile or ICD Compile and Program buttons, a special header is included during the build (you won't see this normally, unless you examine the ASM file). This additional code is used to enable your microcontroller and the MicroCode Studio ICD to communicate with each other. In addition, a special instruction is placed before every one of your PICBasic instructions in order to update the ICD Explorer and main editor window.

As a result, your final hex filesize will be larger than a program compiled normally. File sizes will vary, depending on the processor selected and the length of your source code. The minimum overhead for an ICD build is about 150-200 words of program memory (depending on the type of MCU selected). That is, if you ICD build an 'empty' PICBasic source file, you will see between 150 and 200 words used. This is the ICD header code. In addition, 8 bytes of data memory are used, all residing in bank zero. Obviously, as your program size increases, so does the size of the code inserted during an ICD build.

Fortunately, you can control the amount of debugging information added to your ICD build by using the PICBasic DISABLE DEBUG and ENABLE DEBUG directives. For example, with the sample sort.bas program, you could add the following.

DISABLE DEBUG
   FOR Index = 0 TO ArraySize - 1
      RANDOM RandomValue
      Array(Index) = RandomValue
   NEXT Index
ENABLE DEBUG

By doing this, the build size will be smaller, because no debugging code is included between the DISABLE DEBUG and ENABLE DEBUG directives. A really useful tip is to include a DISABLE DEBUG directive at the beginning of your program, then wrap the code you want the ICD to control with ENABLE DEBUG and DISABLE DEBUG. This will provide a considerable reduction in code overhead for large programs. For example, lets take a look at a complete listing of sort.bas using this approach,

' *** disable debug information ***
DISABLE DEBUG
DEFINE OSC 10

' constants
ArraySize CON 10
True CON 1
False CON 0

' variables
Array VAR WORD(ArraySize)
Index VAR BYTE
InnerIndex VAR BYTE
OuterIndex VAR BYTE
ListSorted VAR BYTE
RandomValue VAR WORD
TmpValue VAR WORD

ProgramStart:

 ' *** enable debug information for code block ***
 ENABLE DEBUG
   FOR Index = 0 TO ArraySize - 1
      RANDOM RandomValue
      Array(Index) = RandomValue
   NEXT Index
DISABLE DEBUG
' *** debug information now disabled ***
' sort the array - simple bubble sort
ListSorted = False
OuterIndex = 0

WHILE NOT ListSorted AND (OuterIndex < ArraySize)
   ListSorted = True

   ' check for exchange
   FOR InnerIndex = 0 TO ArraySize - 2
      Index = InnerIndex + 1
      IF Array(InnerIndex) < Array(Index) THEN
         TmpValue = Array(InnerIndex)
         Array(InnerIndex) = Array(Index)
         Array(Index) = TmpValue
         ListSorted = False
      ENDIF
   NEXT InnerIndex
   OuterIndex = OuterIndex + 1
WEND

' repeat forever
GOTO ProgramStart

In this example, the ICD will only be activated when the array is being initialised. Remember, DISABLE DEBUG and ENABLE DEBUG are compiler directives. This means that you can leave them in your source program, even if you compile and program normally. Taking them out will not make your final hex file any smaller.

See Also


ICD Increase Speed

Increasing ICD Execution Speed

When you build a project using the ICD Compile or ICD Compile and Program buttons, a special header is included during the build (you won't see this normally, unless you examine the ASM file). This additional code is used to enable your microcontroller and the MicroCode Studio ICD to communicate with each other. In addition, a special instruction is placed before every one of your PICBasic instructions in order to update the ICD Explorer and main editor window.

The ICD does not slow down the execution speed of each individual PICBasic instruction. If you have a PICBasic instruction like PULSIN or PAUSE, they will run at the same speed regardless of whether you have built your project using ICD compile. However, the overall execution speed of the program will depend on a number of factors.

The ICD will animate at different speeds, depending on both the OSC setting of the target device and also the speed of the host PC. You will generally get better update speeds when using higher OSC settings. Don't expect blistering animation speeds if you are running a P90 with 8MB of RAM and a target microcontroller running at 4MHz. In ideal situations, you can expect update speeds of 10 Instructions Per Second (IPS) when the animate button is in the down position (see also bank optimisation). If animation is switched off, you can expect many hundreds of PICBasic instructions per second.

In some situations, you may want to prevent the ICD from interfering with whole sections of your PICBasic program. For example, you might have a critical code block where precise timing is required. Using the ICD in such a critical section may prevent your code from functioning correctly. To overcome this, you can use the PICBasic DISABLE DEBUG and ENABLE DEBUG directives. For example, with the sample sort.bas program, you could add the following.

DISABLE DEBUG
   FOR Index = 0 TO ArraySize - 1
      RANDOM RandomValue
      Array(Index) = RandomValue
   NEXT Index
ENABLE DEBUG

In the above example, no debugging code is included between the DISABLE DEBUG and ENABLE DEBUG directives. The section will run at full speed. As soon as the program leaves the code block, the ICD regains control of the target processor. You can also use this technique to reduce the code overhead associated with building a project using ICD Compile or ICD Compile and Program. For more information, please refer to the Reducing the ICD Code Overhead section.

See Also


ICD Models

ICD Model Creator

The ICD Model Creator software allows you to create model files for microcontrollers not currently supported by MicroCode Studio. The software can be accessed from VIEW...ICD MODEL CREATOR from the MicroCode Studio main menu.

Welcome Screen

The first screen shows the location of MPLAB and MPASM that the ICD Model Creator software has obtained from the host machine registry. If these paths are not displayed, it is likely that MPLAB is not installed correctly. If this is the case, you will need to re-install MPLAB in order to proceed. Press the 'Next' button to move to the next screen.

Candidate List

This screen will scan the host machine MPLAB installation and obtain a list of candidate microcontrollers. This may take a little time, so please be patient! When the search process has finished, the 'Next' button will become active. Select the microcontroller you want to build a model file for and then press the 'Next' buton.

ICD Monitor File

An ICD model requires two files. The first one is a simple *.ini file, which is generated automatically from the information obtained from the MPLAB installation. For example, a list of SFRs used by the selected microcontroller. You can actually view this file after the generation process by examining your 'MyDocuments' folder and looking under 'ICDModelCreator\INI'. The next file is a program that controls how ICD commands are interpreted and executed. This code is written in PICBASIC, you can take a look at a sample program here. The ICD Model Creator comes supplied with a monitor file that is geared towards 18 series microcontrollers. You can find this program in you main MicroCode installation, under '..\bin\icd\monitor'. In some cases, you may have to edit this file (make a backup first!). For example, some devices may need their communications ports set to digital to enable RS232 communication. A useful tip is to write a small program that communicates with the target device using MicroCode Studios Serial Communicator Software. This will give you an idea of what changes you may need to make. When you have loaded the monitor file, press the 'Next' button.

Finished

The last screen informs you that the creation process has finished and gives the location of the model file. This is typically '..\MyDocuments\ICDModelCreator\Models'. You will need to copy this file into your MicroCode Studio 'ICDModels' subfolder. You must then restart MicroCode Studio for the model file to be loaded.

See Also


ICD Explorer

The ICD Explorer

When the ICD is started, the ICD Explorer is automatically opened by MicroCode Studio. Tabs at the top of the ICD Explorer enable you to select which values are displayed. These are; variables, Special Function Registers (SFRs), memory and EEPROM. The EEPROM tab is only visible for those microcontrollers that have onboard EEPROM. Data is displayed in decimal, hexadecimal and binary format. When in EEProm view, ASCII values are also displayed.

Before each PICBasic instruction is executed, the ICD requests a complete dump of banked memory from the microcontroller. These are mapped to actual variable and SFR names and then displayed in the ICD Explorer. The variable and register tabs therefore represent mapped data values. The memory tab is a complete unmapped data dump from the microcontroller. EEPROM is an exception, in that a request to dump EEPROM data is only made by the ICD if the EEPROM tab is visible. This is because reading EEPROM can be quite slow, so if your PICBasic program does not use EEPROM, there is little point in slowing down the ICD by dumping the contents of EEPROM.

Reset MCU

You can instruct the ICD to do a software reset of the target MCU by right clicking on the ICD Explorer window and selecting 'Reset MCU'. Please note this is not the same as a Power On Reset (POR). Internal Special Function Registers (SFRs) will not default to the values given in the Microchip datasheet. If you require the correct SFR default values, you will need to perform a hard reset. A software or hardware reset will cause the ICD to start program execution at the first program instruction.

Update All

You can instruct the ICD to do a complete dump of data memory and EEPROM, by right clicking on the ICD Explorer window and selecting 'Update All'. Forcing the ICD to dump the contents of data memory and EEPROM means that the ICD will run a little slower when the animation button is in the down position.

Bank Optimisation

Some microcontrollers have particularly large amounts of user RAM available, which can really slow down the ICD animation. This is because a large amount of data needs to be transferred via a relatively slow serial connection. The MicroCode Studio ICD uses bank optimisation to ensure only user variables and Special Function Registers (SFR) are dumped when the animation button is in the down position. You can toggle bank optimisation by right clicking on the ICD Explorer window and selecting 'Bank Optimisation'. If bank optimisation is off, a complete memory dump operation is performed.

Clear EEPROM

When the ICD Explorer EEProm tab is selected, you can reset the contents of on chip EEProm to zero by right clicking on the ICD Explorer window and selecting the 'Clear EEProm' option. Writing to EEProm can be a little slow when compared to writing to static RAM. This means that for larger devices containing a substantial amount of EEProm, clearing may take a little time as each EEProm location has to have a zero written to it. Please give this process a little time.

State Indicators

A value that is steady state (that is, the value has not changed) is denoted by using a green circle.

If the ICD detects a state change, the value is highlighted using a red circle and the background is grayed.

When you switch to the EEPROM tab, or you switch from the EEPROM tab to either the variable, register or memory tabs, values are shown with a yellow circle. This means that the ICD has requested a data dump and an update is pending. Pending updates will only be shown if update all is not enabled, which is the ICD default behaviour.

Arrays can take up quite a lot of space in the ICD Explorer, because each array location gets a slot of its own. Therefore, the ICD Explorer uses a plus symbol that enables the array view to be expanded or contracted. When the ICD is first started, arrays are all contracted, that is, you will need to click on the plus symbol to display each individual array location.

Arrays views that are contracted always get highlighed if one or more of its locations change state. When the view is expanded, state changes are shown for each individual array location.

See Also


ICD Breakpoints

Breakpoints

Breakpoints are used to stop the execution of a program at any given point. The MicroCode Studio ICD enables you to add multiple breakpoints. You can even have breakpoints in PICBasic include files. To add a breakpoint, use your left mouse button and click on the gray bar located to the left of the MicroCode Studio editor. Alternatively, use the ICD breakpoint button located on the ICD toolbar. To remove the breakpoint, just click on the bar again.

When the ICD is running, your PICBasic program will execute normally until a breakpoint is reached. When a breakpoint is encountered, the ICD suspends program execution and displays a small red arrow to the left of the breakpoint.

If the animation button is in the up position (disabled) and a breakpoint is encountered, animation is automatically enabled by the ICD. This forces the ICD to perform a complete data dump and update the ICD Explorer. You can then use the step button to go through each line following the breakpoint. Alternatively, just press the pause button to resume program execution.

A breakpoint is normally shown as a red bar, but when you start the ICD, some breakpoints may get grayed out. A gray breakpoint represents an unreachable point in your program. An unreachable breakpoint will not cause any problems for the ICD, it merely serves as a warning that the point you have marked will never stop program execution. The most obvious example is if you place a breakpoint at a comment, as shown below.

Non Reachable Breakpoint

Comments are not program instructions, so it is clear that the ICD will never stop program execution at this point. Another example is data declarations. A statement such as

Index VAR BYTE

is not a program instruction, so setting a breakpoint here will result in it being marked as unreachable.

Remember, if your breakpoint is set within a block of code that has been marked with the DISABLE DEBUG and ENABLE DEBUG directives, the ICD has no control over program execution and a breakpoint will not be activated.

For more information about ENABLE DEBUG and DISABLE DEBUG, please refer to the Reducing the ICD Code Overhead and Increasing the Speed of the ICD sections.

Breakpoint Properties

To access breakpoint properties, right click on a breakpoint and then select 'Breakpoint Properties...'. This will invoke the properties dialog window. You can enter a pass count value which stops program execution after a specified number of passes. The ICD increments a pass index each time the line containing the breakpoint is encountered. When the pass index equals the pass count, the ICD pauses program execution. For example, if the pass count is set to 10, program execution stops at when the line is encountered for the tenth time. A pass count of zero (default) will force the ICD to pause program execution each time the breakpoint is reached. If the 'count again when breakpoint reached' option is checked, the pass index is automatically reset to zero and counting starts again.

See Also


ICD Edit

ICD Editing

When the ICD process is running, you can edit variables, SFRs, memory and EEPROM. This is a very powerful feature, as it enables you to alter the internal values of the MCU on the fly. To do this, simply click on the ICD Explorer value you want to edit. A little edit panel will appear just below the main ICD Explorer window.

Just enter the new value in the edit box and then press the enter key. To enter a hexadecimal number, use the $ prefix. For example, $1F0F. To enter a binary number, use the % prefix. For example, %10001101. If no prefix is used, the number is interpreted as decimal. If the number you type is invalid (for example, $%10) the edit box font will change to red when the enter key is pressed.

Please note that for BYTE sized value, only the lower 8 bits of the entered number are used. For example, after entering $FF0F for a value declared as BYTE, only '$0F' will be used. For BIT sized variables, only the lower bit of the entered number is used. If the number entered is smaller than the declared value, the upper bits are padded with zeros. For example, entering $FF for a value declared as WORD will result in the value being set to $00FF.

String Data

When in ICD EEPROM view, you can also enter whole strings to EEPROM. To do this, click on the EEPROM starting address. The edit window will now show two tabs. One tab allows you to enter single byte data into EEProm, the other tab allows you to enter string data.

To enter string data, click on the 'String Data' tab. Type in the string you want to put into EEPROM and then press the enter key. There are a number of additional options available when entering string data. To access these, right click on the string data tab.

Line Terminator

Automatically appends a line terminator sequence to the string data when the enter key is pressed. Options include None, Null ($00), CR ($0D), LF ($0A), CR and LF ($0D0A), LF and CR ($0A0D).

Auto Increment EEPROM Address

This option will force the string data pointer to automatically go to the next available EEPROM location. For example, if your starting address is $00 and you enter 'hello', the next starting address will be $00 + Length('hello') + Length(line terminator sequence).

Auto Clear String Data

This option will automatically clear the string data edit box after pressing the enter key, allowing you to quickly type in the next data string.

See Also


ICD Project

An Example ICD Project

Probably the best way to start using the ICD is by trying a sample project. You should load the sample program sort.bas, which is located in the ICDSamples folder. This short tutorial assumes you have the required system specification and have setup your microcontroller hardware correctly.

Preparing the Source Program
Compiling Your Program
Starting the ICD
Problems

Preparing the Source Program

Once you have loaded sort.bas into MicroCode Studio, you should ensure that the correct OSC setting for your microcontroller is set. It is essential that your PICBasic code has the correct oscillator setting defined. By default, this is 4MHz. If your target device is running at a different speed, you must make sure the appropriate define is used in your PICBasic code. For example, if you have a PIC16F628 running at 10MHz, use the following statement at the beginning of your program:

DEFINE OSC 10

Failing to set the correct oscillator setting causes problems for the ICD. In short, if the setting in your code does not match the actual speed of your PIC microcontroller, the ICD will not work. If you are using a bootloader, you should also ensure that you have the required define at the beginning of your program. For example,

DEFINE LOADER_USED 1

Compiling Your Program

Next, you need to build your program using either the ICD Compile or ICD Compile and Program buttons. These are located on the main ICD toolbar. The ICD Compile and ICD Compile and Program buttons work in exactly the same way as the main MicroCode Studio Compile and Compile and Program toolbar buttons, with the exception that additional debug information is automatically included in the build. ICD Compile will generate a hex file, which you then have to manually program into your microcontroller. ICD Compile and Program will generate a hex file and then automatically start your chosen programmer. For more information on setting up a programmer, refer to the Using a Programmer with MicroCode Studio section. Remember, you can only interface to the ICD after building your project with one of these buttons.

Starting the ICD

Before starting the ICD, make sure you have the correct serial port selected. The communications port drop down box enables you to select the serial port used by the ICD to communicate with the target microcontroller. The ICD only communicates with a PIC microcontroller using its hardware USART. For details on setting up your hardware for use by the ICD, please refer to the Setting Up Your Hardware section.

The ICD control buttons enable you to run, stop, pause and step the ICD. Remember, you must build your project with either ICD Compile or ICD Compile and Program before pressing the run button. When the ICD has started, you can select the pause button to suspend the ICD, allowing you to step through the program line by line. Alternatively, you can have the pause button in the down position before starting the ICD. If a breakpoint is reached during program execution, MicroCode Studio will automatically pause the ICD.

When the animate button is down (default), MicroCode Studio animates program execution. That is, you will see each program line highlighted in the main editor window as it is being executed. In addition, the ICD Explorer is updated with the current values of all variables, SFRs, memory and EEPROM. When the animate button is in the up position, MicroCode Studio will not animate program execution. Neither the main editor window or the ICD Explorer is updated.

The ICD will animate at different speeds, depending on both the OSC setting of the target device and also the speed of the host PC. You will generally get better update speeds when using higher OSC settings. Don't expect blistering animation speeds if you are running a P90 with 8MB of RAM and a target microcontroller running at 4MHz. In ideal situations, you can expect update speeds of 10 Instructions Per Second (IPS) when the animate button is in the down position. If the animation is switched off, you can expect around 1,000 IPS. However, the ICD is highly configurable. You can get the ICD to run in real time for critical code sections if you want. For more information on how to configure the ICD, please refer to the Reducing the ICD Code Overhead and Increasing the Speed of the ICD sections.

Problems

By following the above, you should be able to get the ICD up and running with the minimum of fuss. However, if you do encounter problems, try reading through the ICD Problems section first. If you are still having difficulties with the ICD, please contact Mecanique for further support.

See Also


ICD Problems

Problems

The MicroCode ICD is very easy to use, but ocasionally problems do occur. If you are still unable to get the ICD to work properly after reading the following sections, please contcct Mecanique for further support.

ICD Address Mismatch
ICD Build Required
ICD Compiler Version
ICD Connection Timeout
ICD Identification Mismatch
ICD Line Truncate
ICD Model Not Supported
ICD Model Version
ICD Port Access
ICD System Error

See Also


ICD Serial Communications - Overview

MicroCode Studio allows you to receive and transmit serial data when the ICD process is executing. Serial data can be sent to a PICBasic HSERIN instruction using the ICD Serial In window. Serial data sent by a HSEROUT instruction is received and displayed using the ICD Serial Out window.

It is essential that MicroCode Studio takes complete control of the microcontrollers hardware serial port (USART), to ensure that the ICD functions correctly. A USART that is not configured properly could compromise the ICD process. Certain user defines are therefore disabled during an ICD Compile or ICD Compile and Program and include:

HSER_BAUD    'baud rate
HSER_SPBRG   'spbrg init
HSER_RCSTA   'receive status init
HSER_TXSTA   'transmit status init
HSER_EVEN    'even parity
HSER_ODD     'odd parity

The ICD will only disable hardware serial defines if they are present in your main program. MicroCode Studio will not disable defines if they are present in an include file. Using hardware serial defines in an include file may, in certain circumstances, cause the ICD process to fail. In addition, the MicroCode Studio ICD will only support HSERIN and HSEROUT if they are used from within your main program block.

The MicroCode Studio ICD uses the default PICBasic serial data format of 8 data bits, no parity and one stop bit (8N1) to communicate with your computer. In addition, the following defines are used:

DEFINE HSER_SPBRG Value  'spbrg init
DEVICE HSER_TXSTA Value  'transmit status init

You won't see these values normally, but you can view the actual values used by the MicroCode Studio ICD by right clicking on the ICD Explorer window and then selecting 'ICD Serial Settings...' The ICD also uses the following RCSTA value, which is a default PICBasic define:

DEFINE HSER_RCSTA 90H    'receive status init

This means that when using the ICD, you do not need to configure HSERIN and HSEROUT as you would normally, because the ICD will do this automatically. However, you may need one or more of the above defines in your final code build, if HSERIN and HSEROUT are used.

Example

Here is a simple program, which reads in a value using HSERIN and then echoes it to screen using HSEROUT. It assumes you are using a microcontroller running at 20MHz, programmed with bootloader software.

DEFINE LOADER_USED 1
DEFINE OSC 20

CR CON 13
Char VAR BYTE

HSEROUT ["Program Starting...",CR]
ProgramStart:
   HSERIN [Char]
   HSEROUT ["Char = '", Char,"' is ASCII = ",DEC Char,CR]
   GOTO ProgramStart

The above program will run within the ICD process, but not if you compile and program your microcontroller normally (that is, you have not used ICD Compile or ICD Compile and Program). You can view the defines MicroCode Studio has used by right clicking on the ICD Explorer window and then selecting 'ICD Serial Settings...'

If you want to use HSERIN and HSEROUT in your final program, then just add the above defines to your source code. For example,

DEFINE HSER_TXSTA 24H ' add TXSTA value, high speed
DEFINE HSER_SPBRG 0AH ' add SPBRG value

DEFINE LOADER_USED 1
DEFINE OSC 20

CR CON 13
Char VAR BYTE

HSEROUT ["Program Starting...",CR]
ProgramStart:
   HSERIN [Char]
   HSEROUT ["Char = '", Char,"' is ASCII = ",DEC Char,CR]
   GOTO ProgramStart

See Also


ICD Serial In

The ICD Serial In window allows you to communicate serial information to a PICBasic HSERIN instruction. The ICD Serial In window will automatically appear when your program reaches a HSERIN statement. You can also open the ICD Serial In window by right clicking on the ICD Explorer window and selecting 'ICD Serial In...'.

To send serial information, simply type the required data in the editor and then press enter. Alternatively, you can press the 'Send Message' button, located on the toolbar. The editor text changes from blue to grey, as each byte of data is transmitted by the ICD to the host microcontroller.

You can also send control characters in your serial data. For example, you might want to send a carriage return or line feed in your message string. Further information on how to format special control characters can be found here.

ICD Serial In Control

The control buttons work in a very similar way to the main ICD Toolar buttons. You can send a message, stop, pause and also single step the serial data. Pressing the send message button (or carriage return key) will load the editor string into the transmission buffer. As each HSERIN instruction is executed, the transmission buffer is used to feed HSERIN. Pressing stop will clear the transmission buffer. You can also select the pause button to suspend transmission and use step to send data one byte at a time to HSERIN.

ICD Serial In Message Loop

The transmission buffer feeds a HSERIN instruction until the buffer is empty, at which point transmission to HSERIN will stop. Rather than manually having to send the message again, you can use the loop button to automatically re-transmit. Looping is enabled when the button is in the down position.

ICD Serial In History

Each time you press the send message button (or carriage return key), the message string is saved to a history list. You can use the forward and back buttons to quickly access a history item. This enables you to quickly access previously transmitted messages, without having to type them in again. The status bar will display the currently selected history item.

To delete a history item, right click on the ICD Serial In editor window and then select 'Delete History Item'.

See Also


ICD Serial Out

The ICD Serial Out window allows you to receive and display serial information from a PICBasic HSEROUT instruction. The ICD Serial Out window will automatically appear when your program reaches a HSEROUT statement. You can also open the ICD Serial Out window by right clicking on the ICD Explorer window and selecting 'ICD Serial Out...'.

The ICD Serial Out window will display serial data as it is received from the microcontroller and word wrap if required. A carriage return control character (13 decimal, $D hexadecimal) can be sent in the serial stream to force a new line. You can also use a line feed (10 decimal, $A hexadecimal) or a CRLF pair (13,10).

See Also


Identifiers

An identifier is, quite simply, a name. Identifiers are used in PICBasic 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, PICBasic only recognizes the first 32.

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Line Labels

In order to mark statements that the program might wish to reference with GOTO or GOSUB commands, PICBasic uses line labels. Unlike many older BASICs, PICBasic doesn't allow line numbers and doesn't require that each line be labeled. Rather, any line may start with a line label, which is simply an identifier followed by a colon (:).

Example

here:
   SEROUT 0,N2400,["Hello, World!",13,10]
   GOTO here

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Variables

Variables are where temporary data is stored in a PicBasic Pro program. They are created using the VAR keyword. Variables may be bits, bytes or words. Space for each variable is automatically allocated in the microcontrollers RAM by PBP. The format for creating a variable is as follows:

Label VAR Size{.Modifiers}

Label is any identifier, excluding keywords, as described above. Size is BIT, BYTE or WORD. Optional Modifiers add additional control over how the variable is created. Some examples of creating variable are:

dog VAR byte
cat VAR bit
w0 VAR word

There are no predefined user variables in PicBasic. For compatibility sake, two files have been provided that create the standard variables used with the BASIC Stamps: "bs1defs.bas" and "bs2defs.bas". To use one of these files, add the line:

INCLUDE "bs1defs.bas"

or

INCLUDE "bs2defs.bas"

near the top of the PicBasic program. These files contain numerous VAR statements that create all of the BASIC Stamp variables and pin definitions. However, instead of using these "canned" files, we recommend you create your own variables using names that are meaningful to you. The number of variables available depends on the amount of RAM on a particular device and the size of the variables and arrays. PICBasic reserves approximately 24 RAM locations for its own use. It may also create additional temporary variables for use in sorting out complex equations.


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. For example,

fido VAR dog ' fido is another name for dog
b0 VAR w0.byte0 ' b0 is the first byte of word w0
b1 VAR w0.byte1 ' b1 is the second byte of word w0
flea VAR dog.0 ' flea is bit0 of dog

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
BIT9 or 9 | Create alias to bit 9 of word
BIT10 or 10 | Create alias to bit 10 of word
BIT11 or 11 | Create alias to bit 11 of word
BIT12 or 12 | Create alias to bit 12 of word
BIT13 or 13 | Create alias to bit 13 of word
BIT14 or 14 | Create alias to bit 14 of word
BIT15 or 15 | Create alias to bit 15 of word
BYTE0 or LOWBYTE | Create alias to low byte of word
BYTE1 or HIGHBYTE | Create alias to high byte of word


Arrays

Variable arrays can be created in a similar manner to variables.

Label VAR Size[Number of elements]

Label is any identifier, excluding keywords, as described above. Size is BIT, BYTE or WORD. Number of elements is how many array locations is desired. Some examples of creating arrays are:

sharks VAR byte[10]
fish VAR bit[8]

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:

Size | Maximum Number of elements
BIT | 256
BYTE | 96*
WORD | 48*

* Processor dependent. See the section on memory allocation for more information.

Arrays must fit entirely within one RAM bank on most PICmicros. They may not span RAM banks on 14-bit or 17Cxxx devices. (Arrays may span banks on 18Cxxx devices. Byte- and word-sized arrays are only limited in length by the amount of memory.) The compiler will assure that arrays will fit in memory before successfully compiling.


Constants

Named constants may be created in a similar manner to variables. It can be more convenient to use a constant name instead of a constant number. If the number needs to be changed, it may be changed in only one place in the program; where the constant is defined. Variable data cannot be stored in a constant.

Example

mice CON 3
traps CON mice * 1000


Symbols

SYMBOL provides yet another method for aliasing variables and constants. It is included for BS1 compatibility. SYMBOL cannot be used to create a variable. Use VAR to create a variable.

Example

SYMBOL lion = cat ' cat was previously created using VAR
SYMBOL mouse = 1 ' Same as mouse con 1

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Numeric Constants

PICBasic allows numeric constants to be defined in the three bases: decimal, binary and hexadecimal. Binary values are defined using the prefix '%' and hexadecimal values using the prefix '$'. Decimal values are the default and require no prefix.

Example

100 ' Decimal value 100
%100 ' Binary value for decimal 4
$100 ' Hexadecimal value for decimal 256

For ease of programming, single characters are converted to their ASCII equivalents. Character constants must be quoted using double quotes and must contain only one character (otherwise, they are string constants).


String Constants

PICBasic 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 PICBasic commands have this handling built-in).

Example

LCDOUT "Hello" ' Output String (Short for "H","e","l","l","o")

Strings are usually treated as a list of individual character values.


Pins

Pins may be accessed in a number of different ways. The best way to specify a pin for an operation is to simply use its PORT name and bit number:

PORTB.1 = 1 ' Set PORTB, bit 1 to a 1

To make it easier to remember what a pin is used for, it should be assigned a name using the VAR command. In this manner, the name may then be used in any operation:

led VAR PORTA.0 ' Rename PORTA.0 as led
HIGH led ' Set led (PORTA.0) high

For compatibility with the BASIC Stamp, pins used in PicBasic Compiler commands may also be referred to by number, 0 - 15. These pins are physically mapped onto different PICmicro hardware ports dependent on how many pins the microcontroller has.

No. PICmicro Pins | 0 - 7 | 8 - 15
8-pin | GPIO* | GPIO*
18-pin | PORTB | PORTA*
28-pin (except 14C000) | PORTB | PORTC
28-pin (14C000) | PORTC | PORTD
40-pin | PORTB | PORTC

*GPIO and PORTA do not have 8 I/O pins.

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 PICmicro. Depending on the particular PICmicro, 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 PORTC.0 for a PIC14C000) . Pins may be referenced by number (0 - 15), name (e.g. Pin0, if one of the bsdefs.bas files are included or you have defined them yourself), or full bit name (e.g. PORTA.1). Any pin or bit of the microcontroller can be accessed using the latter method. 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:

led VAR PORTB.3

However, two definition files have been provided to enhance BASIC Stamp compatibility. The file "bs1defs.bas" or "bs2defs.bas" may be included in the PicBasic Pro program to provide pin and bit names that match the BASIC Stamp names. BS1DEFS.BAS defines Pins, B0-B13, W0-W6 and most of the other BS1 pin and variable names. BS2DEFS.BAS defines Ins, Outs, B0-B25, W0-W12 and most of the other BS2 pin and variable names.

When a PICmicro 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 pin an output. Setting a TRIS bit to 1 makes its pin an input. For example:

TRISA = %00000000 ' Or TRISA = 0

sets all the PORTA pins to outputs.

TRISB = %11111111 ' Or TRISB = 255

sets all the PORTB pins to inputs.

TRISB = %11111111 ' Or TRISB = 255

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 should not be used with the PicBasic Pro Compiler. TRIS should be used instead, but has the opposite state of Dirs. This following does not work in PicBasic Pro:

Dir0 = 1 ' Doesn’t set pin PORTB.0 to output

Do this instead:

TRISB.0 = 0 ' Set pin PORTB.0 to output

or simply use a command that automatically sets the pin direction.


Comments

A PBP comment starts with either the REM keyword or the single quote ('). All following characters on this line are ignored. Unlike many BASICs, REM is a unique keyword and not an abbreviation for REMark. Thus, variable names may begin with REM (although REM itself is not valid).


Multi

Multi-Statement Lines

In order to allow more compact programs and logical grouping of related commands, PICBasic supports the use of the colon (:) to separate statements placed on the same line. Thus, the following two examples are equivalent:

W2 = W0
W0 = W1
W1 = W2

is the same as:

W2 = W0 : W0 = W1 : W1 = W2

This does not, however, change the size of the generated code.


Line

Line Extension Character

The maximum number of characters that may appear on one PICBasic 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.

Example

BRANCH B0,[label0,label1,label2,_
label3,label4]


INCLUDE

Other BASIC source files may be added to a PBP program by using INCLUDE. You may have standardized subroutines, definitions or other files that you wish to keep separate. The Stamp and serial mode definition files are examples of this. These files may be included in programs where they are necessary, but kept out of programs where they are not needed. The included files source code lines are inserted into the program exactly where the INCLUDE is placed.

Example

INCLUDE "modedefs.bas"

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DEFINE

For the compiler directive #DEFINE, see here.

Some elements, like the clock oscillator frequency and the LCD pin locations, are predefined in PBP. DEFINE allows a PICBasic PRO program to change these definitions if desired. These definitions must be in all upper case.

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 1 pin port
DEFINE CCP1_BIT 2 'Hpwm 1 pin bit
DEFINE CCP2_REG PORTC 'Hpwm 2 pin port
DEFINE CCP2_BIT 1 'Hpwm 2 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_TMR 1 'Hpwm 2 timer select
DEFINE HPWM3_TMR 1 'Hpwm 3 timer select
DEFINE HSER_BAUD 2400 'Hser baud rate
DEFINE HSER_CLROERR 1 'Hser clear overflow automatically
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 9th bit for parity
DEFINE HSER2_BAUD 2400 'Hser(2) baud rate
DEFINE HSER2_CLROERR 1 'Hser(2) clear overflow automatically
DEFINE HSER2_SPBRG 25 'Hser(2) spbrg init
DEFINE HSER2_RCSTA 90h 'Hser(2) receive status init
DEFINE HSER2_TXSTA 20h 'Hser(2) transmit status init
DEFINE HSER2_EVEN 1 'Hser(2) Use only if even parity desired
DEFINE HSER2_ODD 1 'Hser(2) Use only if odd parity desired
DEFINE HSER2_BITS 9 'Hser(2) Use 9th bit for parity
DEFINE I2C_HOLD 1 'Pause I2C transmission while clock held low
DEFINE I2C_INTERNAL 1 'Use for internal EEPROM on 16CExxx and 12CExxx
DEFINE I2C_SCLOUT 1 'Set serial clock to bipolar instead of open-collector
DEFINE I2C_SLOW 1 'Use for >8MHz OSC with standard speed devices
DEFINE I2C_SDA PORTA,0 'Data pin for I2C (12-bit core only)
DEFINE I2C_SCL PORTA,1 'Clock pin for I2C (12-bit core only)
DEFINE LCD_DREG PORTA 'LCD data port
DEFINE LCD_DBIT 0 'LCD data starting bit 0 or 4
DEFINE LCD_RSREG PORTA 'LCD register select port
DEFINE LCD_RSBIT 4 'LCD register select bit
DEFINE LCD_EREG PORTB 'LCD enable port
DEFINE LCD_EBIT 3 'LCD enable bit
DEFINE LCD_RWREG PORTE 'LCD read/write port
DEFINE LCD_RWBIT 2 'LCD read/write bit
DEFINE LCD_BITS 4 'LCD bus size 4 or 8
DEFINE LCD_LINES 2 'Number lines on LCD
DEFINE LCD_COMMANDUS 2000 'Command delay time in us
DEFINE LCD_DATAUS 50 'Data delay time in us
DEFINE LOADER_USED 1 'Bootloader Used
DEFINE NO_CLRWDT 1 'Forces manual use of CLRWDT
DEFINE ONINT_USED 1 'Serves as LOADER_USED for versions before 2.33
DEFINE PULSIN_MAX 1000 'Maximum counts allowed before pulsin times out
DEFINE OSC 4 'Oscillator speed in MHz: 3(3.58) 4 8 10 12 16 20 24 25 32 33 40
DEFINE OSCCAL_1K 1 'Set OSCCAL for PIC12C671/CE673
DEFINE OSCCAL_2K 1 'Set OSCCAL for PIC12C672/CE674
DEFINE SER2_BITS 8 'Set number of data bits for Serin2 and Serout2
DEFINE SER2_ODD 1 'Use odd parity instead of even parity
DEFINE SHIFT_PAUSEUS 50 'Slow down the Shiftin and Shiftout clock
DEFINE USE_LFSR 1 'Use 18Cxxx LFSR instruction
DEFINE XINXLAT_OFF 1 'Don’t translate Xin commands to BS2 format
DEFINE XOUTXLAT_OFF 1 'Don’t translate Xout commands to BS2 format
Copyright © 2002 microEngineering Labs, Inc.


DIRECTIVES

#DEFINE

#DEFINE constant_name {value}

The #DEFINE directive creates a compile-time constant and, optionally, assigns a value to the constant. Constant_name may be any word that is not in the reserved word list, not used for another entity (variable, constant, alias, label, etc) within the PBP program, and does not exist as a register (SFR) name in the target PIC MCU. Value may be numeric, or a string enclosed in quotation marks:

#DEFINE foo 10
#DEFINE foo1 "18F"

Once created, these constants can be used in conditionals with #IF, #IFDEF, and #IFNDEF. The can also be used with message directives #MSG, #ERROR, and #WARNING.

Compile-time constants created with #DEFINE are not the same as run-time constants created with the CON directive, and are not accessible to PBP program code. Compile-time constants are only accessible to preprocessor (#) directives listed in this section. There are several pre-defined system constants that are created automatically and accessible in the same fashion as those created manually with #DEFINE. These constants are are named in the form __name__. They are:

  • __DATE__ Date of compilation from computer's clock.
  • __TIME__ Time of compilation from the computer's clock
  • __TIMESTAMP__ The timestamp from the PBP program file.
  • __PROCESSOR__ The target device part number.
  • __VERSION__ The version of PBP.
  • __LONG__ Indicator that long words are in use (1 denotes true, 0 denotes false).
  • __LINE__ The line number where written. (Used with #MSG, #ERROR, or #WARNING to report a line number.)
  • __FILE__ The name of the PBP program file.

Compile-time constants can also be created with the –d command line switch.

#ERROR

#ERROR {"message"}

The #ERROR directive, when encountered, will abort the compilation process and report the error message that you specify. This directive should always be written inside of a conditional block. If #ERROR is used outside of a conditional, it will always abort the compile.

#IF __LONG__ = 0
   #ERROR "This program requires PBPL"
#ENDIF

#IF...#ELSE...#ENDIF

#IF condition {AND|OR condition}

The #IF allows sections of code to be omitted or compiled based on a condition. The conditional expression must be constructed from compile-time constants that have been previously declared using #DEFINE. (Run-time variables and constants cannot be used here.) The purpose of this directive is to give the user the means to easily and globally change the program before it is compiled based on a control constant. This is useful when a single program needs to be compiled with modifications for different application types, but the user desires to maintain only one program file.

One example would be to compile the same program for two different PIC MCUs. Consider the case where the hardware exists in two versions; one is an older version that uses the PIC16F877A, and an updated hardware revision exists that uses the PIC16F887. These parts are almost identical, except for some differences in register names and settings. You could accommodate both parts with a conditional compile.

#DEFINE device_type = "16F877" 'Set to 887 for the newer part

#IF device_type = "16F877"
  ADCON1 = 7 'All pins digital on the 877A
#ELSE
  ANSEL = 0 'AN0-AN7 digital on the 887
  ANSELH = 0 'AN8-AN13 digital on the 887
#ENDIF

Note the difference between the compile-time #IF and the run-time IF. When the #IF is used, only one section of code is actually compiled. The unused code is "thrown away" before compilation. This saves code space and avoids compilation errors associated with non-existent register names. The run-time IF would attempt to compile both sections of code for later execution based on a run-time condition.

The #IF and associated directives will control ANY code written. This includes variable and constant declarations, configuration blocks, in-line Assembly blocks, and program code. This makes them very powerful, but opens the door to potential syntax errors when used improperly. Consider the following:

#DEFINE omit 1 'Set a flag to omit code
#IF omit <> 1
  FOR x = 0 TO 7
  HIGH LED
  PAUSE 100
  LOW LED
  PAUSE 100
#ENDIF
NEXT x

In this example, a compile error will result only when the compile-time constant "omit" is set to 1. In that case, the top portion of the FOR..NEXT is omitted, leaving only the NEXT.

#IFDEF...#ELSE...#ENDIF

#IFDEF constant

The #IFDEF directive checks to see whether a constant has been defined. With #IFDEF, the value of the constant is irrelevant. If the constant exists, #IFDEF will be satisfied, regardless of the value.

Consider the case where hardware exists in two versions; one is an older version that uses the PIC16F877A, and an updated hardware revision exists that uses the PIC16F887. These parts are almost identical, except for some differences in register names and settings. You could accommodate both parts with a conditional compile that is triggered by the existence of the compile-time constant "16F877A":

#DEFINE 16F877A 'Specify the target device by creating a constant
#IFDEF 16F877A 'Compile this section only if the target is 16F877A
  ADCON1 = 7 'All pins digital on the 877A
#ENDIF
#IFDEF 16F887 'Compile this section only if the target is 16F887
  ANSEL = 0 'AN0-AN7 digital on the 887
  ANSELH = 0 'AN8-AN13 digital on the 887
#ENDIF

#IFDEF, like #IF, must be used with #ENDIF. It can also be used with #ELSE:

#IFDEF 16F877A 'Compile this section only if the target is 16F877A
  ADCON1 = 7 'All pins digital on the 877A
#ELSE 'Compile this section only if the target is NOT 16F877A
  ANSEL = 0 'AN0-AN7 digital on the 887
  ANSELH = 0 'AN8-AN13 digital on the 887
#ENDIF
#IFNDEF

#IFNDEF...#ELSE...#ENDIF

#IFNDEF constant

The #IFNDEF directive is the opposite of #IFDEF. #IFNDEF evaluates a true condition if the specified constant is NOT defined.

#WARNING

#WARNING {"message"}

The #WARNING directive will report the specified warning message during compilation, but it will allow the compilation to continue.

This directive would normally be written inside of a conditional block. If written outside of a conditional, a warning will always be reported.

#IF __LONG__ = 1
  #WARNING "PBPW is recommended for this program"
#ENDIF

#MSG

#MSG "message"

The #MSG directive causes a message to be reported to the user during compilation. The message may be a string enclosed in quotes, a compile-time constant, or a concatenation of both.

#MSG "Compiling for target " + __PROCESSOR__

Copyright © 2011 microEngineering Labs, Inc.


12 Bit Core Support

PicBasic Pro version 2.4 adds limited support for all the 12-bit core PICmicro microcontrollers. The reason the support is limited is that the resources on the 12-bit core devices are very limited. Some of these limits include only a two-level hardware stack and very small amounts of general purpose RAM memory. The code page size is also small at 512 bytes. There is also a limitation that calls and computed jumps can only be made to the first half (256 words) of any code page. These limitations have made it necessary to eliminate some compiler commands and modify the operation of some others.

While many useful programs can be written for the 12-bit core PICmicros using the PicBasic Pro Compiler, some applications will not be suited for these devices. Choosing a 14- or 16-bit core device with more resources will, in many cases, be the best solution.

Commands that are not supported for the 12-bit core PICmicros:

ADCIN
DATA
DTMFOUT
EEPROM
FREQOUT
HPWM
HSERIN
HSEROUT
ON INTERRUPT
READ
READCODE
RESUME
SERIN2
SEROUT2
USBIN
USBINIT
USBOUT
WRITE
WRITECODE
XIN
XOUT 		No internal ADCs
No on-chip EEPROM
Not enough RAM or stack
No on-chip EEPROM
Not enough RAM or stack
No hardware PWM
No hardware serial port
No hardware serial port
No Interrupts
No on-chip EEPROM
No flash devices
No Interrupts
Not enough RAM or stack
Not enough RAM or stack
No USB devices
No USB devices
No USB devices
No on-chip EEPROM
No flash devices
Not enough RAM or stack
Not enough RAM or stack

Trying to use these commands with 12-bit core devices will result in numerous errors. If you must use one of these commands, choose a 14- or 16-bit core device with more resources.

Modified Commands

BUTTON

The Define for debounce, BUTTON_PAUSE is limited to 65 milliseconds.

DEBUG, DEBUGIN

The Serin2 and Serout2 modifiers are not supported for these commands because of memory and stack size limits.

I2CREAD, I2CWRITE

The I2C clock and data pins are fixed at compile time by Defines. They still must be specified in the I2CRead and I2CWrite statements, though this information is ignored by the compiler.

DEFINE I2C_SDA PORTA,0
DEFINE I2C_SCL PORTA,1

Because of memory and stack constraints, the Define for I2C_SLOW 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.

The Define for I2C_HOLD has no effect.

LCDOUT

The Serout2 modifiers are not supported for this command because of memory and stack size limits.

OWIN, OWOUT

The Rep, Skip and Str modifiers are not supported for these commands because of memory and stack size limits.

SEROUT

The open drain modes are not available due to TRIS register constraints.

SHIFTIN, SHIFTOUT

The Define for SHIFT_PAUSEUS is not available because of stack size limitations.

General Considerations

Because of the architecture of the 12-bit core PICmicro MCUs, programs compiled for them by PBP will, in general, be larger and slower that programs compiled for the other PICmicro families. In many cases, choosing a device from one of these other families will be more appropriate. However, many useful programs can be written and compiled for the 12-bit core devices.

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.

The compiler 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 PICmicro 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 PICmicro MCU with more general purpose RAM.

12-bit core PICmicro 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 PICmicro 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 PICmicro MCU instead of the 12-bit core device.

Copyright © 2001 microEngineering Labs, Inc.


Math Operators

Unlike the BASIC Stamp, the PicBasic Compiler performs all math 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 operations are carried out in the order you would like, use parenthesis to group the operations:

A = (B + C) * (D - E)

All math operations are unsigned and performed with 16-bit precision. The operators supported are:

Math Operators | Description
+ | Addition
- | Subtraction
* | Multiplication
** | Top 16 Bits of Multiplication
*/ | Middle 16 Bits of Multiplication
/ | Division
// | Remainder (Modulus)
DIV32 | 32 bit division
<< | Shift Left
>> | Shift Right
ABS | Absolute Value
COS | Cosine
DCD | 2n Decode
DIG | Digit
MAX | Maximum*
MIN | Minimum*
NCD | Encode
REV | Reverse Bits
SIN | Sine
SQR | Square Root
& | Bitwise AND
| | Bitwise OR
^ | Bitwise Exclusive OR
~ | Bitwise NOT
&/ | Bitwise NOT AND
|/ | Bitwise NOT OR
^/ | Bitwise NOT Exclusive OR

*Implementation differs from BASIC Stamp.


Multiplication

PBP performs 16x16 multiplication. The '*' operator returns the lower 16 bits of the 32-bit result. This is the typical multiplication found in most programming languages. The '**' operator returns the upper 16 bits of the 32-bit result. These two operators can be used in conjunction to perform 16x16 multiplication that produces 32-bit results.

Example

W1 = W0 * 1000 ' Multiply value in W0 by 1000 and place the result in W1
W2 = W0 ** 1000 ' Multiply W0 by 1000 and place the high order 16 bits (which may be 0) in W2

The >*/= operator returns the middle 16 bits of the 32-bit result.

W3 = W1 */ W0 ' Multiply W1 by W0 and place the middle 16 bits in W3


DIVISION

PBP performs 16x16 division. The '/' operator returns the 16-bit result. The '//' operator returns the remainder. This is sometimes referred to as the modulus of the number.

Example

W1 = W0 / 1000 ‘ Divide value in W0 by 1000 and place the result in W1
W2 = W0 // 1000 ‘ Divide value in W0 by 1000 and place the remainder in W2

See Also

DIV32

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SHIFT

The '<<' and '>>' operators shift a value left or right, respectively, 0 to 15 times. The newly shifted-in bits are set to 0.

Example

B0 = B0 << 3 ' Shifts B0 left 3 places (same as multiply by 8)
W1 = W0 >> 1 ' Shifts W0 right 1 position and places result in W1 (same as divide by 2)


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.

Example

B1 = ABS B0

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


REV

ATN

ATN returns the 8-bit arctangent of 2 twos-complement 8-bit values. If a byte is greater than 127 (high bit set), it is treated as a negative value. The arctangent returned is in binary radians, 0 to 255, representing a range of 0 to 359 degrees.

Example

ang = x ATN y

Copyright © 2011 microEngineering Labs, Inc.


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.

Example

B1 = COS B0

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DCD

DCD returns the decoded value of a bit number. It changes a bit number (0 - 15) into a binary number with only that bit set to 1. All other bits are set to 0.

Example

B0 = DCD 2 ' Sets B0 to %00000100

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DIG

DIG returns the value of a decimal digit. Simply tell it the digit number (0 - 4 with 0 being the rightmost digit) you would like the value of, and voila.

Example

B0 = 123 ' Set B0 to 123
B1 = B0 DIG 1 ' Sets B1 to 2 (digit 1 of 123)


REV

HYP

HYP returns the hypotenuse of a right triangle, or the length of the side opposite the right angle. It simply calculates the square root of the sum of the squares of the length of the 2 sides adjacent to the right angle.

The input values are treated as twos-complement numbers representing a range of +127 to -128. If the compiler 'Use Long Words' option is enabled, a long variable or constant must be used if a negative value is to be represented. In any case, the value returned is always positive.

Example

B2 = B0 HYP B1
' Same as B2 = SQR ((B0 * B0)+ (B1 * B1))

Copyright © 2011 microEngineering Labs, Inc.


MAX and MIN

MAX and MIN returns the maximum and minimum, respectively, of two numbers. It is usually used to limit numbers to a value.

Example

B1 = B0 MAX 100 ' Set B1 to the larger of B0 and 100 (B1 will be between 100 & 255)
B1 = B0 MIN 100 ' Set B1 to the smaller of B0 and 100 (B1 can’t be bigger than 100)


NCD

NCD returns the priority encoded bit number (1 - 16) of a value. It is used to find the highest bit set in a value. It returns 0 if no bit is set.

B0 = NCD %01001000 ' Sets B0 to 7
Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


REV

REV reverses the order of the lowest bits in a value. The number of bits to be reversed is from 1 to 16.

Example

B0 = %10101100 REV 4 ' Sets B0 to %10100011


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

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SQR

SQR returns the square root of a value. Since PicBasic only works with integers, the result will always be an 8-bit integer no larger than the actual result.

Example

B0 = SQR W1 ' Sets B0 to square root of W1


Bitwise Operators

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. For example,

B0 = B0 & %00000001 ' Isolate bit 0 of B0
B0 = B0 | %00000001 ' Set bit 0 of B0
B0 = B0 ^ %00000001 ' Reverse state of bit 0 of B0


Comparison Operators

Comparison operators are used in IF..THEN statements to compare one expression with another. The operators supported are:

Comparison Operator | Description
= or == | Equal
<> or != | Not Equal
< | Less Than
> | Greater Than
<= | Less Than or Equal
>= | Greater Than or Equal


Logical Operators

Logical operators differ from bitwise operations. They yield a true/false result from their operation. Values of 0 are treated as false. Any other value is treated as true. They are mostly used in conjunction with the comparison operators in an IF..THEN statement. The operators supported are:

Logical Operator | Description
AND or && | Logical AND
OR or || | Logical OR
XOR or ^^ | Logical Exclusive OR
NOT AND | Logical NAND
NOT OR | Logical NOR
NOT XOR | Logical NXOR

Example

IF (A == big) AND (B > mean) THEN run

Be sure to use parenthesis to tell PICBasic the exact order you want the operations to be performed.


@ Statement

@

@ Statement

When used at the beginning of a line, @ provides a shortcut for inserting one assembly language statement into your PBP program. You can use this shortcut to freely mix assembly language code with PicBasic Pro statements.

Example

i var byte
rollme var byte

FOR i = 1 TO 4
   @ rlf _rollme, F ; Rotate byte left once
NEXT i

The @ shortcut can also be used to include assembly language routines in another file. For example:

@ Include "fp.asm"

@ resets the register page to 0 before executing the assembly language instruction. The register page should not be altered using @.

See Also

ASM...ENDASM

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ADCIN

ADCIN Channel,Var

Read the on-chip analog to digital converter channel and store the result in the variable 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. ADCON1 also needs to be set to assign the desired pins to analog inputs and in some cases to set the result format and clock source. See the Microchip data sheets for more information on these registers and how to set them for the specific device. Several DEFINEs may also be used:

Example

DEFINE ADC_BITS 8       ' Set number of bits in result
DEFINE ADC_CLOCK 3     ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

TRISA = 255 ' Set PORTA to all input
ADCON1 = 2  ' PORTA is analog
ADCIN 0, B0 ' Read channel 0 to B0

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


HSERIN

ARRAYREAD

ARRAYREAD ArrayVar, {Maxlength, Label,}[Item...]

Read one or more Items from byte array ArrayVar using SERIN2 modifiers. ARRAYREAD can be used to scan a byte array for values and other strings and move these elements to other variables.

An optional Maxlength and Label may be included to allow the program to limit the number of characters read from the array so as not to read past its allocated length. Maxlength must be less than 256, though longer arrays may be read using either multiple ARRAYREADs or by leaving off this optional parameter. If the count exceeds the Maxlength, the program will exit the ARRAYREAD command and jump to Label.

Input Modifiers

Modifier | Operation
BIN{1..32} | Receive binary digits
DEC{1..10} | Receive decimal digits
HEX{1..8} | Receive 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

See Also

ARRAYWRITE

Copyright © 2011 microEngineering Labs, Inc.


HSERIN

ARRAYWRITE

ARRAYWRITE ArrayVar, {Maxlength, Label,}[Item...]

Write one or more Items to byte array ArrayVar using SEROUT2 modifiers. ARRAYWRITE allows the writing of formatted data to a byte array which can then be output by other compiler commands, such as I2CWRITE, to write to a serial LCD, for example.

An optional Maxlength and Label may be included to allow the program to limit the number of characters written to the array so as not to exceed its allocated length. Maxlength must be less than 256, though longer arrays may be written using either multiple ARRAYWRITEs or by leaving off this optional parameter. If the count exceeds the Maxlength, the program will exit the ARRAYWRITE command and jump to Label.

An assortment of string-formatting modifiers is available for use within the item list of this command. These modifiers can be used to format string output that includes numeric values converted from variables:

Output Modifiers

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 char\count | Send character c repeated n times
STR ArrayVar{\count} | Send string of n characters

ARRAYWRITE is not supported on 12-bit core PIC MCUs due to RAM and stack constraints.

' Send the ASCII value of B0 followed by
' a period and 2 digit ASCII value of B1
ARRAYWRITE A,[DEC B0,".",DEC2 B1]
' Send "B0 =" followed by the binary

See Also

ARRAYREAD

Copyright © 2011 microEngineering Labs, Inc.


ASM

ASM...ENDASM

ASM
   {assembler code}
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 statements. You can use these two instructions to freely mix assembly language code with PicBasic statements.

The maximum size for an assembler text section is 8K. This is the maximum size for the actual source, including comments, not the generated code. If the text block is larger than this, break it into multiple ASM..ENDASM sections or simply include it in a separate file. 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.

Example

ASM
   bsf PORTA, 0 ; Set bit 0 on PORTA
   bcf PORTB, 0 ; Clear bit 0 on PORTB
ENDASM

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


BRANCH

BRANCH Index,[Label{,Label...}]

BRANCH causes the program to jump to a different location based on a variable index.

Index selects one of a list of labels. Execution resumes at the indexed label. For example, if Index is zero, the program jumps to the first label specified in the list, if Index is one, the program jumps to the second label, and so on. If Index is greater than or equal to the number of labels, no action is taken and execution continues with the statement following the BRANCH. Up to 255 (256 for 18Cxxx) labels may be used in a BRANCH. 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.

Example

BRANCH B4,[dog,cat,fish]

This is the same as:

If B4=0 Then dog ' goto dog
If B4=1 Then cat ' goto cat
If B4=2 Then fish ' goto fish

See Also

BRANCHL

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


BRANCHL

BRANCHL Index,[Label{,Label...}]

BRANCHL (BRANCH long) works very similarly to BRANCH in that it causes the program to jump to a different location based on a variable index. The main differences are that it can jump to a label that is in a different code page than the BRANCH instruction and that it generates code that is about twice the size as code generated by the BRANCH instruction. If you are sure the labels are in the same page as the BRANCH instruction or if the microcontroller does not have more than one code page (2K or less of ROM), using BRANCH instead of BRANCHL will minimize memory usage.

Index selects one of a list of labels. Execution resumes at the indexed label. For example, if Index is zero, the program jumps to the first label specified in the list, if Index is one, the program jumps to the second label, and so on. If Index is greater than or equal to the number of labels, no action is taken and execution continues with the statement following the BRANCHL. Up to 127 (256 for 18Cxxx) labels may be used in a BRANCHL.

Example

BRANCHL B4,[dog,cat,fish]

This is the same as:

If B4=0 Then dog ' goto dog
If B4=1 Then cat ' goto cat
If B4=2 Then fish ' goto fish

See Also

BRANCH

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


BUTTON

BUTTON Pin,Down,Delay,Rate,BVar,Action,Label

Read pin and optionally performs debounce and auto-repeat. 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).

Down | State of pin when button is pressed (0..1).
Delay | Cycle count before auto-repeat starts (0..255). If 0, no debounce or auto-repeat is performed. If 255, debounce, but no auto-repeat, is performed.
Rate | Auto-repeat rate (0..255).
BVar | Byte-sized variable used internally for delay/repeat countdown. It must be initialized to 0 prior to use and not used elsewhere in the program.
Action | State of button to act on (0 if not pressed, 1 if pressed).
Label | Execution resumes at this label if Action is true.

BUTTON needs to be used within a loop for auto-repeat to work properly. BUTTON accomplishes debounce by delaying program execution for a period of milliseconds to wait for the contacts to settle down. The default debounce delay is 10ms. To change the debounce to another value, use DEFINE:

Example

DEFINE BUTTON_PAUSE 50 ' button debounce delay is 50ms

Be sure that BUTTON_PAUSE is all in upper case. In general, it is easier to simply read the state of the pin in an IF..THEN than to use the BUTTON command as follows:

If PORTB.2 = 1 Then notpressed

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


CALL

CALL Label

Execute the assembly language subroutine named Label. GOSUB is normally used to execute a PicBasic subroutine. The main difference between GOSUB and CALL is that with CALL, the existence of Label is not checked until assembly time. Using CALL, a Label in an assembly language section can be accessed that is otherwise inaccessible to PicBasic.

Example

CALL pass ' Execute assembly language subroutine named _pass

See Also

GOSUB

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


CLEAR

Set all RAM registers to zero. CLEAR zeroes all the RAM registers in each bank. This will set all variables, including the internal system variables to zero. This is not automatically done when a PicBasic Pro program starts as it is on a BASIC Stamp. In general, the variables should be set in the program to an appropriate initial state rather than using CLEAR.

Example

CLEAR ' Clear all variables to 0

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


CLEARWDT

Clear (tickle) the Watchdog Timer.

The Watchdog Timer is used in conjunction with the SLEEP and NAP instructions to wake the PICmicro after a certain period of time. Assembler instructions (clrwdt) to keep the Watchdog Timer from timing out under normal circumstances and resetting the PICmicro are automatically inserted at appropriate places throughout the program.

Example

CLEARWDT ' Clear Watchdog Timer

See Also

NAP
SLEEP

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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).
The resolution of Period is in milliseconds. It tracks the oscillator frequency based on the DEFINEd OSC.

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).

Example

' Count # of pulses on Pin1 in 100 milliseconds
COUNT PORTB.1, 100, W1

' Determine frequency on a pin
COUNT PORTA.2, 1000, W1 ' Count for 1 second
SEROUT PORTB.0, N2400, [W1]


DATA

DATA {@Location,}Constant{,Constant...}

Store constants in on-chip non-volatile EEPROM when the device is first programmed. If the optional Location value is omitted, the first DATA statement starts storing at address 0 and subsequent statements store at the following locations. If the Location value is specified, it denotes the starting location where these values are stored. An optional label can be assigned to the starting EEPROM address for later reference by the program.

Constant can be a numeric constant or a string constant. Only the least significant byte of numeric values are stored unless the WORD modifier is used. Strings are stored as consecutive bytes of ASCII values. No length or terminator is automatically added.

DATA only works with microcontrollers with on-chip EEPROM such as the PIC16F84 and PIC16C84. 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.

Example

' Store 10, 20 and 30 starting at location 5
DATA @5,10,20,30

' Assign a label to a word at the next location
dlabel DATA word $1234 ' Stores $34, $12

' Skip 4 locations and store 10 0s
DATA (4), 0(10)

See Also

WRITE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DEBUG

DEBUG Item {,Item...}

Send one or more items to a predefined pin at a predefined baud rate in standard asynchronous format using 8 data bits, no parity and 1 stop bit (8N1). The pin is automatically made an output. If a pound sign (#) precedes an Item, the ASCII representation for each digit is sent serially. DEBUG also supports the same data modifiers as SEROUT2.

Modifier | Operation
{I}{S}BIN{1..16} | Send binary digits
{I}{S}DEC{1..5} | Send decimal digits
{I}{S}HEX{1..4} | Send hexadecimal digits
REP c\n | Send character c repeated n times
STR ArrayVar{\n} | Send string of n characters

DEBUG is one of several built-in asynchronous serial functions. It is the smallest of the software generated serial routines. It can be used to send debugging information (variables, program position markers, etc.) to a terminal program like Hyperterm or the Serial Communications Window in MicroCode Studio. It can also be used anytime serial output is desired on a fixed pin at a fixed baud rate. The serial pin and baud rate are specified using DEFINEs. For example,

' Set Debug pin port
DEFINE DEBUG_REG PORTB

' Set Debug pin bit
DEFINE DEBUG_BIT 0

' Set Debug baud rate
DEFINE DEBUG_BAUD 2400

' Set Debug mode: 0 = true, 1 = inverted
DEFINE DEBUG_MODE 1

DEBUG assumes a 4MHz oscillator when generating its bit timing. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to any different oscillator value. In some cases, the transmission rates of DEBUG instructions may present characters too quickly to the receiving device. A DEFINE adds character pacing to the serial output transmissions. This allows additional time between the characters as they are transmitted. The character pacing DEFINE allows a delay of 1 to 65,535 microseconds (.001 to 65.535 milliseconds) between each character transmitted. For example, to pause 1 millisecond between the transmission of each character:

DEFINE DEBUG_PACING 1000

While single-chip RS-232 level converters are common and inexpensive, thanks to current RS-232 implementation and the excellent I/O specifications of the PICmicro, most applications don't require level converters. Rather, inverted TTL (DEBUG_MODE = 1) can be used. A current limiting resistor is suggested (RS-232 is suppose to be short-tolerant).

See Also

DEBUGIN
SEROUT2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DISABLE

DISABLE both debug and interrupt processing following this instruction. Interrupts can still occur but the BASIC interrupt handler in the PicBasic Pro program and the debug monitor will not be executed until an ENABLE is encountered. DISABLE and ENABLE are more like pseudo-ops in that they give the compiler directions, rather than actually generate code.

Example

DISABLE ' Disable interrupts in handler
myint: led = 1 ' Turn on LED when interrupted
RESUME ' Return to main program
ENABLE ' Enable interrupts after handler

See Also

ENABLE
ON DEBUG
ON INTERRUPT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DIV32

DIV32 Number

PBPs multiply (*) function operates as a 16-bit x 16-bit multiply yielding a 32-bit result. However, since the compiler only supports a maximum variable size of 16 bits, access to the result had to happen in 2 steps: c = b * a returns the lower 16 bits of the multiply while d = b ** a returns the upper 16 bits. There was no way to access the 32-bit result as a unit.

In many cases it is desirable to be able to divide the entire 32-bit result of the multiply by a 16-bit number for averaging or scaling. A new function has been added for this purpose called DIV32. DIV32 is actually limited to dividing a 31-bit unsigned integer (max 2147483647) by a 15-bit unsigned integer (max 32767). This should suffice in most circumstances.

As the compiler only allows a maximum variable size of 16 bits, DIV32 relies that a multiply was just performed and that the internal compiler variables still contain the 32-bit result of the multiply. No other operation may occur between the multiply and the Div32 or the internal variables may be altered, destroying the 32-bit multiplication result. This means, among other things, that ON INTERRUPT must be disabled from before the multiply until after the DIV32. If ON INTERRUPT is not used, there is no need to add DISABLE to the program. Interrupts in assembler should have no effect on the internal variables so they may be used without regard to DIV32.

Example

a VAR WORD
b VAR WORD
c VAR WORD
dummy VAR WORD

b = 500
c = 1000

DISABLE        ' Necessary if On Interrupt used
dummy = b * c ' Could also use ** or */
a = DIV32 100
ENABLE        ' Necessary if On Interrupt used

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. In this example, Div32 divides the 32-bit result of the multiplication b * c by 100 and stores the result of this division, 5000, in the word-sized variable a.

See Also

MATH OPERATORS

Copyright © 2001 microEngineering Labs, Inc.


WHILE

DO...LOOP

DO {UNTIL Condition} {WHILE Condition}
Statement...
LOOP {UNTIL Condition} {WHILE Condition}

Repeatedly execute Statements in a loop. An optional UNTIL or WHILE may be added to check a Condition.

The addition of DO...LOOP to the compiler means that "loop" can no longer be used as a label. If "loop" is used as a label, the compiler will issue an error. These "loop" labels will need to be changed to some other, hopefully more meaningful, name such as "Mainloop", "Buttonloop" or "Waitloop", for examples. Any GOTOs or other instructions that reference a "loop" label will, of course, need to be changed as well.

DO
  Pwm PORTC.2,127,100
LOOP

i = 1
DO UNTIL i > 10
  Serout 0,N2400,["No:",#i,13,10]
  i = i + 1
LOOP

i = 1
DO
  Serout 0,N2400,["No:",#i,13,10]
  i = i + 1
LOOP UNTIL i > 10

i = 1
DO WHILE i <= 10
  Serout 0,N2400,["No:",#i,13,10]
  i = i + 1
LOOP

i = 1
DO
  Serout 0,N2400,["No:",#i,13,10]
  i = i + 1
LOOP WHILE i <= 10

Copyright © 2011 microEngineering Labs, Inc.


DTMFOUT

DTMFOUT Pin,{Onms,Offms,}[Tone{,Tone...}]

Produce DTMF touch tone sequence on Pin. 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). 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 uses FREQOUT to generate the dual tones. FREQOUT generates tones using a form of pulse width modulation. The raw data coming out of the pin looks pretty scary. Some kind of filter is usually necessary to smooth the signal to a sine wave get rid of some of the harmonics that are generated.

DTMFOUT works best with a 20MHz oscillator. It can also work with a 10MHz 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 DTMFOUT to generate a frequency that is a ratio of the actual oscillator used and 20MHz which will not be very useful for sending touch tones.

Example

' Send DTMF tones for 212 on Pin1
DTMFOUT PORTB.1,[2,1,2]

See Also

FREQOUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


EEPROM

EEPROM {Location,}[Constant{,Constant...}]

Store constants in on-chip EEPROM. If the optional Location value is omitted, the first EEPROM statement starts storing at address 0 and subsequent statements store at the following locations. If the Location value is specified, it denotes the starting location where these values are stored. Constant can be a numeric constant or a string constant. Only the least significant byte of numeric values are stored. Strings are stored as consecutive bytes of ASCII values. No length or terminator is automatically added.

EEPROM only works with microcontrollers with on-chip EEPROM such as the PIC16F84 and PIC16C84. 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.

Example

' Store 10, 20 and 30 starting at location 5
EEPROM 5,[10,20,30]

See Also

WRITE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ENABLE

ENABLE debug and interrupt processing that was previously DISABLEd following this instruction. DISABLE and ENABLE are more like pseudo-ops in that they give the compiler directions, rather than actually generate code.

Example

DISABLE ' Disable interrupts in handler
myint: led = 1 ' Turn on LED when interrupted
RESUME ' Return to main program
ENABLE ' Enable interrupts after handler

See Also

DISABLE
ON DEBUG
ON INTERRUPT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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. An END or STOP or GOTO should be placed at the end of every program to keep it from falling off the end of memory and starting over.

See Also

SLEEP
STOP
GOTO

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ERASECODE

ERASECODE Block

Some flash PICmicro MCUs, like the PIC18Fxxx 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. See the Microchip data sheet for information on the size of the erase block for the particular PICmicro MCU you are using.

The first location of the block to be erased should be specified by Block. Block is a byte address, rather than a word address, for PIC18Fxxx devices. Be careful not to specify a Block that contains program code. Flash program writes must be enabled in the configuration for the PICmicro MCU at device programming time for ERASECODE to be able to erase.

Using this instruction on devices that do not support block erase will cause a compilation error.

Example

ERASECODE $100 ' Erase code block starting at location $100

See Also

WRITECODE
READCODE

Copyright © 2002 microEngineering Labs, Inc.


END

EXIT

EXIT jumps to the line after the end of the current block structure and continues program execution from there. This allows the current FOR..NEXT or other loop construct to be left without having to satisfy a specific condition. As none of the block structures in PBP use the stack, there is no problem with the stack and EXIT.

FOR x = 0 TO 255
  IF (x = 27) THEN EXIT
NEXT x

Copyright © 2011 microEngineering Labs, Inc.


FOR

FOR...NEXT

FOR Count = Start TO End {STEP {-}
Inc}
{Body}
NEXT {Count}

The FOR..NEXT loop allows programs to execute a number of statements a given number of times using a variable as a counter. Due to its complexity and versatility, FOR..NEXT is best described step by step:

  1. The value of Start is assigned to the index variable, Count. Count can be a variable of any type.
  2. The Body is executed. The Body is optional and can be omitted (perhaps for a delay loop).
  3. The value of Inc is added to (or subtracted from if "-" is specified) Count. If no STEP clause is defined, Count is incremented by one.
  4. If Count has not passed End or overflowed the variable type, execution returns to Step 2.
    If the loop needs to Count to more than 255, a word-sized variable must be used.

Example

FOR i = 1 TO 10 ' Count from 1 to 10
   SEROUT 0,N2400,[#i,” “] ' Send each number to Pin0 serially
NEXT i ' Go back to and do next count
SEROUT 0,N2400,[10] ' Send a linefeed

FOR B2 = 20 TO 10 STEP -2 ' Count from 20 to 10 by 2
   SEROUT 0,N2400,[#B2,” “] ' Send each number to Pin0 serially
NEXT B2 ' Go back to and do next count
SEROUT 0,N2400,[10] ' Send a linefeed

See Also

WHILE...WEND
REPEAT...UNTIL

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


FREQOUT

FREQOUT Pin,Onms,Frequency1{,Frequency2}

Produce the Frequency(s) on Pin for Onms milliseconds. 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). One or two different frequencies from 0 to 32767 hertz may be produced at a time. FREQOUT generates tones using a form of pulse width modulation. The raw data coming out of the pin looks pretty scary. Some kind of filter is usually necessary to smooth the signal to a sine wave get rid of some of the harmonics that are generated.

FREQOUT works best with a 20MHz oscillator. It can also work with a 10MHz 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.

Example

' Send 1KHz tone on Pin1 for 2 seconds
FREQOUT PORTB.1,2000,1000

See Also

SOUND
DTMFOUT
PWM

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


GOSUB

GOSUB Label

Jump to the subroutine at Label saving its return address on the stack. Unlike GOTO, when a RETURN statement is reached, execution resumes with the statement following the last executed GOSUB statement. An unlimited number of subroutines may be used in a program. Subroutines may also be nested. In other words, it is possible for a subroutine to call another subroutine. Such subroutine nesting should be restricted to no more than four levels deep.

Example

GOSUB beep ' Execute subroutine named beep
...
beep: HIGH 0 ' Turn on LED connected to Pin0
SOUND 1,[80,10] ' Beep speaker connected to Pin1
LOW 0 ' Turn off LED connected to Pin0
RETURN ' Go back to main routine that called us

See Also

RETURN
GOTO
BRANCH
BRANCHL

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


GOTO

GOTO Label

Program execution continues with the statements at Label.

Example

GOTO send ' Jump to statement labeled send
...
send: SEROUT 0,N2400,["Hi"] ' Send “Hi” out Pin0 serially

See Also

GOSUB
BRANCH
BRANCHL

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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).

Example

HIGH 0 ' Make Pin0 an output and set it high (~5 volts)
HIGH PORTA.0 ' Make PORTA, pin 0 an output and set it high (~5 volts)
led VAR PORTB.0 ' Define LED pin
HIGH led ' Make LED pin an output and set it high (~5 volts)

Alternatively, if the pin is already an output, a much quicker and shorter way (from a generated code standpoint) to set it high would be:

PORTB.0 = 1 ' Set PORTB pin 0 high

See Also

LOW

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


HPWM

HPWM Channel,Dutycycle,Frequency

HPWM run continuously in the background while the program is doing other things. Channel specifies which hardware PWM channel to use. Some devices have 1, 2 or 3 PWM channels. On devices with 2 channels, the Frequency must be the same on both channels. Dutycycle specifies the on/off (high/low) ratio of the signal. It ranges from 0 to 255, where 0 is off (low all the time) and 255 is on (high) all the time. A value of 127 gives a 50% duty cycle (square wave). Frequency is the desired frequency of the PWM signal. Not all frequencies are available at all oscillator settings. The lowest frequency at 4MHz is 245Hz. The highest frequency at any oscillator speed is 32767Hz.

The lowest usable HPWM Frequency at each oscillator setting is shown in the following table:

OSC | 14-bit core and 18Cxxx | 17Cxxx
4MHz | 145Hz | 3907Hz
8MHz | 489Hz | 7813Hz
10MHz | 611Hz | 9766Hz
12MHz | 733Hz | 11719Hz
16MHz | 977Hz | 15625Hz
20MHz | 1221Hz | 19531Hz
24MHz | 1465Hz | 23438Hz
33MHz | 2015Hz | 32227Hz
40MHz | 2442Hz | na

Some devices, such as the PIC18C452, have alternate pins that may be used for HPWM. The following DEFINEs allow using these pins:

DEFINE CCP1_REG PORTC 'Hpwm 1 pin port
DEFINE CCP1_BIT 2 'Hpwm 1 pin bit
DEFINE CCP2_REG PORTC 'Hpwm 2 pin port
DEFINE CCP2_BIT 1 'Hpwm 2 pin bit

The following DEFINEs specify which timer, 1 or 2, to use with PWM channel 2 and PWM channel 3 for the PIC17C7xx devices. The default is timer 1 if no DEFINE is specified.

DEFINE HPWM2_TIMER 1 'Hpwm 2 timer select
DEFINE HPWM3_TIMER 1 'Hpwm 3 timer select

Example

HPWM 1,127,1000 ' Send a 50% duty cycle PWM signal at 1kHz
HPWM 1,64,200   ' Send a 25% duty cycle PWM signal at 2kHz

See Also

PWM

Copyright © 2001 microEngineering Labs, Inc.


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.
HSERIN is one of several built-in asynchronous serial functions. It can only be used with devices that have a hardware USART. See the device data sheet for information on the serial input pin and other parameters. The serial parameters and baud rate are specified using DEFINEs:

' Set receive register to receiver enabled
DEFINE HSER_RCSTA 90h

' Set transmit register to transmitter enabled
DEFINE HSER_TXSTA 20h

' Set baud rate
DEFINE HSER_BAUD 2400

' Set SPBRG directly (normally set by HSER_BAUD)
DEFINE HSER_SPBRG 25

HSERIN assumes a 4MHz oscillator when calculating the baud rate. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. An optional Timeout and Label may be included to allow the program to continue if a character is not received within a certain amount of time. Timeout is specified in 1 millisecond units.
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:

' Use only if even parity desired
DEFINE HSER_EVEN 1

' Use only if odd parity desired
DEFINE HSER_ODD 1

The parity setting, along with all of the other HSER DEFINEs, affect both HERIN and HSEROUT. An optional ParityLabel may be included in the statement. The program will continue at this location if a character with a parity error is received. It should only be used if parity is enabled using one of the preceding DEFINEs. 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. HSERIN supports the same data modifiers that SERIN2 does.

Modifier | Operation
BIN{1..16} | Receive binary digits
DEC{1..5} | Receive decimal digits
HEX{1..4} | Receive 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

On 17Cxxx devices with 2 serial ports, HSERIN will only access the first port. The second port should be set up and read by accessing the registers directly.

See Also

SERIN
SERIN2
SEROUT
SEROUT2
HSEROUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


HSEROUT

HSEROUT [Item {,Item...}]

Send one or more Items to the hardware serial port on devices that support asynchronous serial communications in hardware.
HSEROUT is one of several built-in asynchronous serial functions. It can only be used with devices that have a hardware USART. See the device data sheet for information on the serial output pin and other parameters. The serial parameters and baud rate are specified using DEFINEs:

' Set receive register to receiver enabled
DEFINE HSER_RCSTA 90h

' Set transmit register to transmitter enabled
DEFINE HSER_TXSTA 20h

' Set baud rate
DEFINE HSER_BAUD 2400

' Set SPBRG directly (normally set by HSER_BAUD)
DEFINE HSER_SPBRG 25

HSEROUT assumes a 4MHz oscillator when calculating the baud rate. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. 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:

' Use only if even parity desired
DEFINE HSER_EVEN 1

' Use only if odd parity desired
DEFINE HSER_ODD 1

The parity setting, along with all of the other HSER DEFINEs, affect both HSERIN and HSEROUT. Since the serial transmission 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 HSEROUT. HSEROUT supports the same data modifiers that SEROUT2 does.

Modifier | Operation
{I}{S}BIN{1..16} | Send binary digits
{I}{S}DEC{1..5} | Send decimal digits
{I}{S}HEX{1..4} | Send hexadecimal digits
REP c\n | Send character c repeated n times
STR ArrayVar{\n} | Send string of n characters

On 17Cxxx devices with 2 serial ports, HSEROUT will only access the first port. The second port should be set up and read by accessing the registers directly.

' Send the decimal value of B0 followed by a linefeed out the hardware USART
HSEROUT [dec B0,10]

See Also

SERIN
SERIN2
HSERIN
SEROUT
SEROUT2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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 is one of several built-in asynchronous serial functions. It can only be used with devices that have a hardware USART. See the device data sheet for information on the serial input pin and other parameters. The serial parameters and baud rate are specified using DEFINEs:

' Set receive register to receiver enabled
DEFINE HSER2_RCSTA 90h

' Set transmit register to transmitter enabled
DEFINE HSER2_TXSTA 20h

' Set baud rate
DEFINE HSER2_BAUD 2400

' Set SPBRG directly (normally set by HSER_BAUD)
DEFINE HSER2_SPBRG 25

HSERIN2 assumes a 4MHz oscillator when calculating the baud rate. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. An optional Timeout and Label may be included to allow the program to continue if a character is not received within a certain amount of time. Timeout is specified in 1 millisecond units. 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:

' Use only if even parity desired
DEFINE HSER2_EVEN 1

' Use only if odd parity desired
DEFINE HSER2_ODD 1

The parity setting, along with all of the other HSER2 DEFINEs, affect both HSERIN2 and HSEROUT2. An optional ParityLabel may be included in the statement. The program will continue at this location if a character with a parity error is received. It should only be used if parity is enabled using one of the preceding DEFINEs. 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 HSERIN2. HSERIN2 supports the same data modifiers that SERIN2 does.

Modifier | Operation
BIN{1..16} | Receive binary digits
DEC{1..5} | Receive decimal digits
HEX{1..4} | Receive 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

See Also

SERIN
SERIN2
SEROUT
SEROUT2
HSERIN
HSEROUT
HSEROUT2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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 is one of several built-in asynchronous serial functions. It can only be used with devices that have a hardware USART. See the device data sheet for information on the serial output pin and other parameters. The serial parameters and baud rate are specified using DEFINEs:

' Set receive register to receiver enabled
DEFINE HSER2_RCSTA 90h

' Set transmit register to transmitter enabled
DEFINE HSER2_TXSTA 20h

' Set baud rate
DEFINE HSER2_BAUD 2400

' Set SPBRG directly (normally set by HSER_BAUD)
DEFINE HSER2_SPBRG 25

HSEROUT2 assumes a 4MHz oscillator when calculating the baud rate. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. 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:

' Use only if even parity desired
DEFINE HSER2_EVEN 1

' Use only if odd parity desired
DEFINE HSER2_ODD 1

The parity setting, along with all of the other HSER DEFINEs, affect both HSERIN and HSEROUT2. Since the serial transmission 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 HSEROUT2. HSEROUT2 supports the same data modifiers that SEROUT2 does.

Modifier | Operation
{I}{S}BIN{1..16} | Send binary digits
{I}{S}DEC{1..5} | Send decimal digits
{I}{S}HEX{1..4} | Send hexadecimal digits
REP c\n | Send character c repeated n times
STR ArrayVar{\n} | Send string of n characters

' Send the decimal value of B0 followed by a linefeed out the hardware USART
HSEROUT2 [dec B0,10]

See Also

SERIN
SERIN2
HSERIN
HSEROUT
HSERIN2
SEROUT
SEROUT2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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.

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 PicBasic I2C operations. For example, when communicating with a 24LC01B, the control code is %1010 and the chip selects are unused so the Control byte would be %10100000 or $A0. Formats of Control bytes for some of the different parts follows:

Device | Capacity | Control | Address size
24LC01B | 128 bytes | %1010xxx0 | 1 byte
24LC02B | 256 bytes | %1010xxx0 | 1 byte
24LC04B | 512 bytes | %1010xxb0 | 1 byte
24LC08B | 1K bytes | %1010xbb0 | 1 byte
24LC16B | 2K bytes | %1010bbb0 | 1 byte
24LC32B | 4K bytes | %1010ddd0 | 2 bytes
24LC65 | 8K bytes | %1010ddd0 | 2 bytes

bbb = block select (high order address) bits
ddd = device select bits
xxx = don't care

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. If a word-sized Var is specified, 2 bytes are read and stored into the Var high byte first, followed by the low byte. 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]
I2CREAD PORTC.4,PORTC.3,$a0,0,[STR a\8]

If a word-sized array is specified, the 2 bytes that comprise each element are read low byte first. This is the opposite of how simple words are read and is consistent with the way the compiler normally stores word-sized variables. If the optional Label is included, this label will be jumped to if an acknowledge is not received from the I2C device. 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 than 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

Transfer on the I2C bus can be paused by the receiving device by its holding the clock line low. 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, as they are both run in a bi-directional open-collector manner. To make the I2C clock line bipolar instead of open-collector the following DEFINE may be added to the program:

DEFINE I2C_SCLOUT 1
addr VAR byte
cont CON %10100000
addr = 17 ' Set address to 17
' Read data at address 17 into B2
I2CREAD PORTA.0,PORTA.1,cont,addr,[B2]

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.

See Also

I2CWRITE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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). 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.

When writing to a serial EEPROM it is necessary to wait 10ms (device dependent) for the write to complete before attempting communication with the device again. If a subsequent I2CREAD or I2CWRITE is attempted before the write is complete, the access will be ignored. While a single I2CWRITE statement may be used to write multiple bytes at once, doing so may violate the above write timing requirement for serial EEPROMs. Some serial EEPROMS let you write multiple bytes into a single page before necessitating the wait. Check the data sheet for the specific device you are using for these details. The multiple byte write feature may also be useful with I2C devices other than serial EEPROMs that don't have to wait between writes. If a word-sized Value is specified, 2 bytes are sent, high byte first, followed by the low byte. 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 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]
I2CWRITE PORTC.4,PORTC.3,$a0,0,[STR a\8]

If a word-sized array is specified, the 2 bytes that comprise each element are written low byte first. This is the opposite of how simple words are written and is consistent with the way the compiler normally stores word-sized variables. If the optional Label is included, this label will be jumped to if an acknowledge is not received from the I2C device. 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 than 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

Transfer on the I2C bus can be paused by the receiving device by its holding the clock line low. 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

Example

addr VAR byte
cont CON %10100000
addr = 17 ' Set address to 17
' Send the byte 6 to address 17
I2CWRITE PORTA.0,PORTA.1,cont,addr,[6]
PAUSE 10 ' Wait 10ms for write to complete
addr = 1 ' Set address to 1
' Send the byte in B2 to address 1
I2CWRITE PORTA.0,PORTA.1,cont,addr,[B2]
PAUSE 10 ' Wait 10ms for write to complete

See Also

I2CREAD

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


I2CIN

I2CIN Control, Address, Variable {,Variable}

See Also

I2COUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


I2COUT

I2COUT Control, Address, Value {,Value}

See Also

I2CIN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


IF

IF...THEN...ELSEIF...ELSE

IF Comp {AND/OR Comp...} THEN Label

IF Comp {AND/OR Comp...} THEN Statement

IF Comp {AND/OR Comp...} THEN
   Statements...
{ELSEIF Comp {AND/OR Comp...} THEN
   Statements...}
{ELSE
   Statements...}
ENDIF

Performs one or more comparisons. Each Comp term can relate a variable to a constant or other variable and includes one of the comparison operators. If..Then evaluates the comparison terms for true or false. If it evaluates to true, the operation after the Then is executed. If it evaluates to false, the operation after the Then is not executed. Comparisons that evaluate to 0 are considered false. Any other value is considered true. All comparisons are unsigned. Be sure to use parenthesis to specify the order the operations should be tested in. Otherwise, operator precedence will determine it for you and the result may not be as expected.

IF..THEN can operate in 2 manners. In one form, the THEN in an IF..THEN is essentially a GOTO. If the condition is true, the program will GOTO the label after the THEN. If the condition evaluates to false, the program will continue at the next line after the IF..THEN. Another statement may not be placed after the THEN, it must be a label.

Example

IF Pin0 = 0 THEN pushd ' If button connected to Pin0 is pushed (0), jump to label pushd
IF B0 >= 40 THEN old ' If the value in variable B0 is greater than or equal to 40, jump to old
IF PORTB.0 THEN itson ' If PORTB, pin 0 is high (1), jump to itson
IF (B0 = 10) AND (B1 = 20) THEN loop

In the second form, IF..THEN can conditionally execute a group of statements following the THEN. The Statements can be followed by an optional ELSEIF or ELSE with a required ENDIF to complete the structure.

IF B0 <> 10 THEN
  B0 = B0 + 1
  B1 = B1 - 1
ENDIF

IF B0 = 20 THEN
  led = 1
ELSE
  led = 0
ENDIF

See Also

SELECT CASE

Copyright © 2011 microEngineering Labs, Inc.


INPUT

INPUT Pin

Makes the specified Pin 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).

Example

INPUT 0 ' Make Pin0 an input
INPUT PORTA.0 ' Make PORTA, pin 0 an input

Alternatively, the pin may be set to an input in a much quicker and shorter way (from a generated code standpoint):

TRISB.0 = 1 ' Set PORTB, pin 0 to an input

All of the pins on a port may be set to inputs by setting the whole TRIS register at once:

TRISB = %11111111 ' Set all of PORTB to inputs

See Also

OUTPUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


LET

{LET} Var = Value

Assign a Value to a Variable. The Value may be a constant, another variable or the result of an expression. The keyword LET itself is optional.

Example

LET B0 = B1 * B2 + B3
B0 = SQR W1

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


LCDOUT

LCDOUT Item {,Item...}

Display Items on an intelligent Liquid Crystal Display (LCD). PICBasic supports LCD modules with a Hitachi 44780 controller or equivalent. These LCDs usually have a 14- or 16-pin single- or dual-row header at one edge. If a pound sign (#) precedes an Item, the ASCII representation for each digit is sent to the LCD. LCDOUT can also use any of the modifiers used with SEROUT2.

Modifier | Operation
{I}{S}BIN{1..16} | Send binary digits
{I}{S}DEC{1..5} | Send decimal digits
{I}{S}HEX{1..4} | 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 at least half a second before sending the first command to an LCD. It can take quite a while for an LCD to start up. Commands are sent to the LCD by sending a $FE followed by the command. Some useful commands are listed in the following table:

Command | Operation
$FE, 1 | Clear display
$FE, 2 | Return home (beginning of first line)
$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, $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 is a command to move the cursor to the beginning of the second line of a 2-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 $0 and the second line starts at $40. The command:

LCDOUT $FE, $C0

sets the display to start writing characters at the beginning of the second 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. See the data sheet for the particular LCD device for the character memory locations and additional commands.

Example

LCDOUT $FE, 1, "Hello" ' Clear display and show “Hello”
LCDOUT B0, #B1

The LCD may be connected to the PICmicro 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-bit bus is used, it 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 should be tied to ground as the LCDOUT command is write only. PICBasic asumes the LCD is connected to specific pins unless told otherwise. It assumes the LCD will be used with a 4-bit bus with data lines DB4 - DB7 connected to PICmicro PORTA.0 - PORTA.3, Register Select to PORTA.4 and Enable to PORTB.3. It is also preset to initialize the LCD to a 2 line display. To change this setup, place one or more of the following DEFINEs, all in upper-case, at the top of your PicBasic program:

' Set LCD Data port
DEFINE LCD_DREG PORTB
' Set starting Data bit (0 or 4) if 4-bit bus
DEFINE LCD_DBIT 4
' Set LCD Register Select port
DEFINE LCD_RSREG PORTB
' Set LCD Register Select bit
DEFINE LCD_RSBIT 1
' Set LCD Enable port
DEFINE LCD_EREG PORTB
' Set LCD Enable bit
DEFINE LCD_EBIT 0
' Set LCD bus size (4 or 8 bits)
DEFINE LCD_BITS 4
' Set number of lines on LCD
DEFINE LCD_LINES 2
' Set command delay time in us
DEFINE LCD_COMMANDUS 2000
' Set data delay time in us
DEFINE LCD_DATAUS 50

This setup will tell PICBasic a 2-line LCD is connected in 4-bit mode with the data bus on the top 4 bits of PORTB, Register Select on PORTB.1, and Enable on PORTB.0.

See Also

LCDIN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


LOOKDOWN

LOOKDOWN Search,[Constant{,Constant...}],Var

The LOOKDOWN statement searches a list of 8-bit Constant values for the presence of the Search value. If found, the index of the matching constant is stored in Var. Thus, if the value is found first in the list, Var is set to zero. If second in the list, Var is set to one. And so on. If not found, no action is taken and Var remains unchanged. The constant list can be a mixture of numeric and string constants. Each character in a string is treated as a separate constant with the character's ASCII value. 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 18Cxxx) constants are allowed in the list.

Example

SERIN 1,N2400,B0 ' Get hexadecimal character from Pin1 serially
LOOKDOWN B0,["0123456789ABCDEF"],B1 ' Convert hexadecimal character in B0 to decimal value B1
SEROUT 0,N2400,[#B1] ' Send decimal value to Pin0 serially

See Also

LOOKUP
LOOKDOWN2
LOOKUP2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


LOOKDOWN2

LOOKDOWN2 Search,{Test}[Value{,Value...}],Var

The LOOKDOWN2 statement searches a list of Values for the presence of the Search value. If found, the index of the matching constant is stored in Var. Thus, if the value is found first in the list, Var is set to zero. If second in the list, Var is set to one. And so on. If not found, no action is taken and Var remains unchanged. The optional parameter Test can be used to perform a test for other than equal to (A=@) while searching the list. For example, the list could be searched for the first Value greater than the Search parameter by using A>@ as the Test parameter. If Test is left out, A=@ is assumed. The Value list can be a mixture of 16-bit 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. Array variables with a variable index may not be used in LOOKDOWN2 although array variables with a constant index are allowed. Up to 85 (256 for 18Cxxx) values are allowed in the list.

LOOKDOWN2 generates code that is about 3 times larger than LOOKDOWN. If the search list is made up only of 8-bit constants and strings, use LOOKDOWN.

Example

LOOKDOWN2 W0,[512,W1,1024],B0
LOOKDOWN2 W0,<[10,100,1000],B0

See Also

LOOKUP2
LOOKUP
LOOKDOWN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


LOOKUP

LOOKUP Index,[Constant{,Constant...}],Var

The LOOKUP statement can be used to retrieve values from a table of 8-bit constants. If Index is zero, Var is set to the value of the first Constant. If Index is one, Var is set to the value of the second Constant. And so on. If Index is greater than or equal to the number of entries in the constant list, no action is taken and Var remains unchanged. The constant list can be a mixture of numeric and string constants. Each character in a string is treated as a separate constant equal to the character's ASCII value. Array variables with a variable index may not be used in LOOKUP although array variables with a constant index are allowed. Up to 255 (256 for 18Cxxx) constants are allowed in the list.

Example

FOR B0 = 0 TO 5 ' Count from 0 to 5
  LOOKUP B0,["Hello!"],B1 ' Get character number B0 from string to variable B1
  SEROUT 0,N2400,[B1] ' Send character in B1 to Pin0 serially
NEXT B0 ' Do next character

See Also

LOOKDOWN
LOOKUP2
LOOKDOWN2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


LOOKUP2

LOOKUP2 Index,[Value{,Value...}],Var

The LOOKUP2 statement can be used to retrieve entries from a table of Values. If Index is zero, Var is set to the first Value. If Index is one, Var is set to the second Value. And so on. If Index is greater than or equal to the number of entries in the list, no action is taken and Var remains unchanged. The Value list can be a mixture of 16-bit 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. Array variables with a variable index may not be used in LOOKUP2 although array variables with a constant index are allowed. Up to 85 (256 for 18Cxxx) values are allowed in the list.

LOOKUP2 generates code that is about 3 times larger than LOOKUP. If the Value list is made up of only 8-bit constants and strings, use LOOKUP.

Example

LOOKUP2 B0,[256,512,1024],W1

See Also

LOOKDOWN2
LOOKUP
LOOKDOWN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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).

Example

LOW 0 ' Make Pin0 an output and set it low (0 volts)
LOW PORTA.0 ' Make PORTA, pin 0 an output and set it low (0 volts)

led VAR PORTB.0 ' Define LED pin
LOW led ' Make LED pin an output and set it low (0 volts)

Alternatively, if the pin is already an output, a much quicker and shorter way (from a generated code standpoint) to set it low would be:

PORTB.0 = 0 ' Set PORTB, pin 0 low

See Also

HIGH

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


NAP

NAP Period

Places the microcontroller into low power mode for short periods of time. During this NAP, power consumption is reduced to minimum. The listed periods are only approximate because the timing is derived from the Watchdog Timer which is R/C driven and can vary greatly from chip to chip and over temperature. Since NAP uses the Watchdog Timer, its timing is independent of the oscillator frequency.

Period | Delay (Approx.)
0 | 18 milliseconds
1 | 36 milliseconds
2 | 72 milliseconds
3 | 144 milliseconds
4 | 288 milliseconds
5 | 576 milliseconds
6 | 1.152 seconds
7 | 2.304 seconds

Example

NAP 7 ' Low power pause for about 2.3 seconds

See Also

SLEEP

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ON INTERRUPT

ON INTERRUPT GOTO Label

ON INTERRUPT allows the handling of microcontroller interrupts by a PICBasic subroutine. There are 2 ways to handle interrupts using the PicBasic Pro Compiler. The first is to write an assembly language interrupt routine. This is the way to handle interrupts with the shortest latency and lowest overhead. The second method is to write a PicBasic Pro interrupt handler. This looks just like a PicBasic Pro subroutine but ends with a RESUME.

When an interrupt occurs, it is flagged. As soon as the current PicBasic Pro statement's execution is complete, the program jumps to the BASIC interrupt handler at Label. Once the interrupt handler is complete, a RESUME statement sends the program back to where it was when the interrupt occurred, picking up where it left off. DISABLE and ENABLE allow different sections of a PicBasic Pro program to execute without the possibility of being interrupted. The most notable place to use DISABLE is right before the actual interrupt handler. Or the interrupt handler may be placed before the ON INTERRUPT statement as the interrupt flag is not checked before the first ON INTERRUPT in a program.

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. PICBasic 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.

Overhead is another issue. ON INTERRUPT will add an instruction after every statement to check whether or not an interrupt has occurred. DISABLE turns off the addition of this instruction. ENABLE turns it back on again. Usually the additional instruction will not be much of a problem, but long programs in small microcontrollers could suffer. More than one ON INTERRUPT may be used in a program.

Example

ON INTERRUPT GOTO myint ' Interrupt handler is myint
INTCON = %10010000 ' Enable RB0 interrupt

. . .

DISABLE ' Disable interrupts in handler
myint: led = 1 ' Turn on LED when interrupted
RESUME ' Return to main program
ENABLE ' Enable interrupts after handler

To turn off interrupts permanently (or until needed again) once ON INTERRUPT has been used, set INTCON to $80:

INTCON = $80

See Also

ENABLE INTERRUPT
DISABLE INTERRUPT
ENABLE
DISABLE
RESUME

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


OUTPUT

OUTPUT Pin

Make the specified Pin 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).

Example

OUTPUT 0 ' Make Pin0 an output
OUTPUT PORTA.0 ' Make PORTA, pin 0 an output

Alternatively, the pin may be set to an output in a much quicker and shorter way (from a generated code standpoint):

TRISB.0 = 0 ' Set PORTB, pin 0 to an output

All of the pins on a port may be set to outputs by setting the whole TRIS register at once:

TRISB = %00000000 ' Set all of PORTB to outputs

See Also

INPUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


OWIN

OWIN Pin, Mode,[Item {,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. 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). Mode specifies whether a reset is sent before and/ or after the operation and the size of the data items, either bit or byte.

Mode bit number | Effect
0 | 1 = send reset pulse before data
1 | 1 = send reset pulse after data
2 | 0 = byte-sized data, 1 = bit-sized data

Some Mode examples would be: Mode of 0 means no reset and byte-sized data, Mode of 1 means reset before data and byte-sized data, Mode of 4 means no reset and bit-sized data. Item is one or more variables or modifiers separated by commas. The allowable modifiers are STR for reading data into a byte array variable and SKIP for skipping a number of input values. The SKIP and STR modifiers are not supported for the 12-bit core PICmicro MCUs because of RAM and stack size limits.

Example

OWIN PORTC. 0,0,[temperature\2, SKIP 4, count_remain, count_per_c]

This statement would receive bytes from a one-wire device on PORTC pin 0 with no reset pulse being sent. It would receive 2 bytes and put them into the byte array temperature, skip the next 4 bytes and then read the final 2 bytes into separate variables.

See Also

OWOUT

Copyright © 2001 microEngineering Labs, Inc.


OWOUT

OWOUT Pin, Mode, [Item{, Item...}]

Optionally send a reset pulse to a one-wire device and then writes one or more bits or bytes of data from it, optionally ending with another reset pulse. 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). Mode specifies whether a reset is sent before and/or after the operation and the size of the data items, either bit or byte.

Mode bit number | Effect
0 | 1 = send reset pulse before data
1 | 1 = send reset pulse after data
2 | 0 = byte-sized data, 1 = bit-sized data

Some Mode examples would be: Mode of 0 means no reset and byte-sized data, Mode of 1 means reset before data and byte-sized data, Mode of 4 means no reset and bit-sized data. Item is one or more constants, variables or modifiers separated by commas. The allowable modifiers are STR for sending data from a byte array variable and REP for sending a number of repeated values. The REP and STR modifiers are not supported for the 12-bit core PICmicro MCUs because of RAM and stack size limits.

Example

OWOUT PORTC. 0,1,[$cc,$be]

This statement would send a reset pulse to a one-wire device on PORTC pin 0 followed by the bytes $cc and $be.

See Also

OWIN

Copyright © 2001 microEngineering Labs, Inc.


PAUSE

PAUSE Period

Pause the program for Period milliseconds. Period is 16-bits, so delays can be up to 65,535 milliseconds (a little over a minute). Unlike the other delay functions (NAP and SLEEP), PAUSE doesn't put the 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. PAUSE assumes an oscillator frequency of 4MHz. If an oscillator other that 4MHz is used, PBP must be told using a DEFINE OSC OSC command.

Example

PAUSE 1000 ' Delay for 1 second

See Also

PAUSEUS
NAP
SLEEP

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


PAUSEUS

PAUSEUS Period

Pause the program for Period microseconds. Period is 16-bits, so delays can be up to 65,535 microseconds. Unlike the other delay functions (NAP and SLEEP), PAUSEUS doesn't put the microcontroller into low power mode. Thus, PAUSEUS consumes more power but is also much more accurate. It has the same accuracy as the system clock. Because PAUSEUS takes a minimum number of cycles to operate, depending on the frequency of the oscillator, delays of less than a minimum number of microseconds are not possible using PAUSEUS. To obtain shorter delays, use an assembly language routine in an ASM..ENDASM construct.

OSC | Minimum delay
3 (3.58) | 20us
4 | 24us
8 | 12us
10 | 8us
12 | 7us
16 | 5us
20 | 3us
25* | 2us
32* | 2us
33* | 2us
40** | 2us

* PIC17Cxxx and PIC18Cxxx only.
** PIC18Cxxx only.

PAUSEUS assumes an oscillator frequency of 4MHz. If an oscillator other that 4MHz is used, PBP must be told using a DEFINE OSC command.

Example

PAUSEUS 1000 ' Delay for 1 millisecond

See Also

PAUSE
NAP
SLEEP

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


PEEK

PEEK Address,Var

Read the microcontroller register at the specified Address and stores the result in Var. Special PICmicro features such as A/D converters and additional I/O ports may be read using PEEK. However, all of the PICmicro registers can be and should be accessed without using PEEK and POKE. All of the PICmicro 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.

Version 2.40 - PEEK and POKE Command Changes

PEEK and POKE have been changed to work more like the standard PicBasic compiler. For example

PEEK PORTB, B0

will now store the value of the PORTB pins to B0. It is still recommended that PEEK and POKE not be used. It is much better to simply say

B0 = PORTB

See Also

POKE

Copyright © 2001 microEngineering Labs, Inc.


HSERIN

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.

PEEKCODE $3FF, OSCCAL 'Get OSCCAL value for PIC12C671/12CE673
PEEKCODE $7FF, OSCCAL 'Get OSCCAL value

See Also

POKECODE

Copyright © 2011 microEngineering Labs, Inc.


POKE

POKE Address,Value

Write Value to the microcontroller register at the specified Address. Special PICmicro features such as A/D converters and additional I/O ports may be written using POKE. However, all of the PICmicro registers can be and should be accessed without using PEEK and POKE. All of the PICmicro 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.

Version 2.40 - PEEK and POKE Command Changes

PEEK and POKE have been changed to work more like the standard PicBasic compiler. For example,

PEEK PORTB, B0

will now store the value of the PORTB pins to B0. It is still recommended that PEEK and POKE not be used. It is much better to simply say

B0 = PORTB

See Also

PEEK

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


HSERIN

POKECODE

POKECODE {@Address,}Value{,Value...}

Store Values to the code space at the current program address or optional specified Address at the time the microcontroller is programmed.

  • Note that POKECODE is a specialized command intended for use under circumstances that make standard methods unusable. LOOKUP and LOOKUP2 are usually a better choice for constructing lookup tables in code space.

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.

If the optional Address is not specified, data storage will be located immediately after the preceding program instruction written.

To avoid interruption of program flow, POKECODE should be the last line of your program. It should be placed after the END or STOP command.

POKECODE 10, 20, 30 ' Store 10, 20, and 30in code space

Generates:

retlw 10
retlw 20
retlw 30

POKECODE @$7ff, $94 ' Set OSCCAL value for PIC12C672/12CE674

Generates:

org 7ffh
retlw 94h

See Also

POKECODE

Copyright © 2011 microEngineering Labs, Inc.


POT

POT Pin,Scale,Var

Reads a potentiometer (or some other resistive device) on Pin. 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). The resistance is measured by timing the discharge of a capacitor through the resistor (typically 5K to 50K). Scale is used to adjust for varying RC constants. For larger RC constants, Scale should be set low (a minimum value of one). For smaller RC constants, Scale should be set to its maximum value (255). If Scale is set correctly, Var should be zero near minimum resistance and 255 near maximum resistance.

Unfortunately, Scale must be determined experimentally. To do so, set the device under measure to maximum resistance and read it with Scale set to 255. Under these conditions, Var will produce an appropriate value for Scale. (NOTE: This is the same type of process performed by the Alt-P option of the BS1 environment).

Example

POT 3,255,B0 ' Read potentiometer on Pin3 to determine scale
SEROUT 0,N2400,[#B0] ' Send pot value serially out Pin0


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. If an 8-bit variable is used, only the LSB of the 16-bit measurement is used. 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). The resolution of PULSIN is dependent upon the oscillator frequency. If a 4MHz oscillator is used, the pulse width is returned in 10us increments. If a 20MHz oscillator is used, the pulse width will have a 2us resolution. Defining an OSC value has no effect on PULSIN. The resolution always changes with the actual oscillator speed.

Example

' Measure high pulse on Pin4 stored in W3
PULSIN PORTB.4,1,W3

See Also

PULSOUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


PULSOUT

PULSOUT Pin,Period

Generates a pulse on Pin of specified Period. The pulse is generated by toggling the pin twice, thus the initial state of the pin determines the polarity of the pulse. 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). The resolution of PULSOUT is dependent upon the oscillator frequency. If a 4MHz oscillator is used, the Period of the generated pulse will be in 10us increments. If a 20MHz oscillator is used, Period will have a 2us resolution. Defining an OSC value has no effect on PULSOUT. The resolution always changes with the actual oscillator speed.

Example

' Send a pulse 1mSec long (at 4MHz) to Pin5
PULSOUT PORTB.5,100

See Also

PULSIN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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). The Cycle time of PWM is dependent upon the oscillator frequency. If a 4MHz oscillator is used, each Cycle would be about 5ms long. If a 20MHz oscillator is used, each Cycle would be about 1ms in length. Defining an OSC value has no effect on PWM. The Cycle time always changes with the actual oscillator speed. Pin is made an output just prior to pulse generation and reverts to an input after generation stops. The PWM output on a pin looks like so much garbage, not a beautiful series of square waves. A filter of some sort is necessary to turn the signal into something useful. An RC circuit can be used as a simple D/A converter.

Example

PWM PORTB.7,127,100 ' Send a 50% duty cycle PWM signal out Pin7 for 100 cycles

See Also

HPWM

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


RANDOM

RANDOM Var

Perform one iteration of pseudo-randomization on Var. Var should be a 16-bit variable. Array variables with a variable index may not be used in RANDOM, although array variables with a constant index are allowed. Var is used both as the seed and to store the result. The pseudo-random algorithm used has a walking length of 65535 (only zero is not produced).

Example

RANDOM W4 ' Get a random number to W4

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


RCTIME

RCTIME Pin,State,Var

RCTIME measures the time a Pin stays in a particular State. It is basically half a PULSIN. 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). RCTIME may be used to read a potentiometer (or some other resistive device). Resistance can be measured by discharging and timing the charge (or vice versa) of a capacitor through the resistor (typically 5K to 50K). The resolution of RCTIME is dependent upon the oscillator frequency. If a 4MHz oscillator is used, the time in state is returned in 10us increments. If a 20MHz oscillator is used, the time in state will have a 2us resolution. Defining an OSC value has no effect on RCTIME. The resolution always changes with the actual oscillator speed. If the pin never changes state, 0 is returned.

Example

LOW PORTB.3 ' Discharge cap to start
PAUSE 10 ' Discharge for 10ms
RCTIME PORTB.3,0,W0 ' Read potentiometer on Pin3

See Also

POT
PULSIN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


READ

READ Address,Var

Read the on-chip EEPROM at the specified Address and stores the result in Var. This instruction may only be used with a PICmicro that has an on-chip EEPROM data area such as the PIC16F84, PIC16C84 and the PIC16F87x series. READ will not work on devices with on-chip I2C interfaced serial EEPROM like the 12CE67x and 16CE62x parts. Use the I2CREAD instruction instead.

Example

READ 5,B2 ' Put the value at EEPROM location 5 into B2

See Also

WRITE
I2CREAD
I2CWRITE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


REPEAT

REPEAT...UNTIL

REPEAT
  Statements...
UNTIL Condition

REPEAT...UNTIL allow a group of instructions to be executed until a specified condition is true. The conditional expression is placed after UNTIL. For example,

i = 0
REPEAT
   PORTB.0[i] = 0
   i = i + 1
UNTIL i > 7

See Also

FOR...NEXT
WHILE...WEND

Copyright © 2003 microEngineering Labs, Inc.


RESUME

RESUME {Label}

Pick up where program left off after handling an interrupt. RESUME is similar to RETURN but is used at the end of a PicBasic Pro interrupt handler. If the optional Label is used, program execution will continue at the Label instead of where it was when it was interrupted. In this case, any other return addresses on the stack will no longer be accessible.

See Also

ON INTERRUPT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


RETURN

Return from subroutine. RETURN resumes execution at the statement following the GOSUB which called the subroutine.

Example

GOSUB sub1 ' Go to subroutine labeled sub1
...
sub1:
  SEROUT 0,N2400,["Lunch"] ' Send “Lunch” out Pin0 serially
  RETURN ' Return to main program after Gosub

See Also

GOSUB

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


REVERSE

REVERSE Pin

If Pin is an input, it is made an output. If Pin is an output, it is 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).

Example

OUTPUT 4 ' Make Pin4 an output
REVERSE 4 ' Change Pin4 to an input

See Also

INPUT
OUTPUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SERIN

SERIN Pin,Mode,{Timeout,Label,}{[Qual...],}{Item...}

Receive one or more Items on Pin in standard asynchronous format using 8 data bits, no parity and one stop bit (8N1). SERIN is similar to the BS1 Serin command with the addition of a Timeout. 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). The Mode names (e.g. T2400) are defined in the file MODEDEFS.BAS. To use them, add the line:

INCLUDE "modedefs.bas"

to the top of the PicBasic program. BS1DEFS.BAS and BS2DEFS.BAS already includes MODEDEFS.BAS. Do not include it again if one of these files is already included. The Mode numbers may be used without including this file.

Mode | Mode No. | Baud Rate | State
T2400 | 0 | 2400 | True
T1200 | 1 | 1200
T9600 | 2 | 9600
T300 | 3 | 300
N2400 | 4 | 2400 | Inverted
N1200 | 5 | 1200
N9600 | 6 | 9600
N300 | 7 | 300

An optional Timeout and Label may be included to allow the program to continue if a character is not received within a certain amount of time. Timeout is specified in units of 1 millisecond. The list of data items to be received may be preceded by one or more qualifiers enclosed within brackets. SERIN must receive these bytes in exact order before receiving the data items. If any byte received does not match the next byte in the qualifier sequence, the qualification process starts over (i.e. the next received byte is compared to the first item in the qualifier list). A Qualifier can be a constant, variable or a string constant. Each character of a string is treated as an individual qualifier.

Once the qualifiers are satisfied, SERIN begins storing data in the variables associated with each Item. If the variable name is used alone, 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. SERIN assumes a 4MHz oscillator when generating its bit timing. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. While single-chip RS-232 level converters are common and inexpensive, the excellent I/O specifications of the PICmicro allow most applications to run without level converters.

Example

' Wait until the character “A” is received serially on Pin1 and put next character into B0
SERIN 1,N2400,["A"],B0

See Also

SEROUT
SERIN2
SEROUT2
HSERIN
HSEROUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SELECT...CASE

SELECT CASE var
   CASE expr1 {, expr...}
      statements
   CASE expr2 {, expr...}
      statements
   {CASE ELSE statements}
END SELECT

CASE statements, in some cases, are easier to use than multiple IF.. THENs. These statements are used to compare a variable with different values or ranges of values, and take action based on the value.

The variable used in all of the comparisons is specified in the SELECT CASE statement. Each CASE is followed by the statements to be executed if the CASE is true. IS may be used to specify a comparison other than equal to. If none of the CASEs are true, the statements under the optional CASE ELSE statement are executed. An END SELECT closes the SELECT CASE.

Example

SELECT CASE x
  CASE 1
    y = 10
  CASE 2, 3
    y = 20
  CASE IS > 5
    y = 100
  CASE ELSE
    y = 0
END SELECT

See Also

IF...THEN

Copyright © 2001 microEngineering Labs, Inc.


SERIN2

SERIN2 DataPin{\FlowPin},Mode,{ParityLabel,} {Timeout,Label,}[Item...]

Receive one or more Items on Pin in standard asynchronous format. SERIN2 is similar to the BS2 Serin command. DataPin is automatically made an input. The optional FlowPin is automatically made an output. DataPin and FlowPin 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). 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

Some standard baud rates are listed in the following table.

Baud Rate | Bits 0 - 12
300 | 3313
600 | 1646
1200 | 813
2400 | 396
4800 | 188
9600 | 84
19200 | 32

Bit 13 selects even parity (bit 13 = 1) or no parity (bit 13 = 0). Normally, the serial transmissions are 8N1 (8 data bits, no parity and 1 stop bit). If parity is selected, the data is received as 7E1 (7 data bits, even parity and 1 stop bit). 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.

Some examples of Mode are: Mode = 84 (9600 baud, no parity, true), Mode = 16780 (2400 baud, no parity, inverted), Mode = 27889 (300 baud, even parity, inverted). If ParityLabel is included, this label will be jumped to if a character with bad parity is received. It should only be used if even parity is selected (bit 13 = 1). An optional Timeout and Label may be included to allow the program to continue if a character is not received within a certain amount of time. Timeout is specified in units of 1 millisecond. 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. With parity disabled (the default):

DEFINE SER2_BITS 4 ' Set Serin2 and Serout2 data bits to 4
DEFINE SER2_BITS 5 ' Set Serin2 and Serout2 data bits to 5
DEFINE SER2_BITS 6 ' Set Serin2 and Serout2 data bits to 6
DEFINE SER2_BITS 7 ' Set Serin2 and Serout2 data bits to 7
DEFINE SER2_BITS 8 ' Set Serin2 and Serout2 data bits to 8 (default)

With parity enabled:

DEFINE SER2_BITS 5 ' Set Serin2 and Serout2 data bits to 4
DEFINE SER2_BITS 6 ' Set Serin2 and Serout2 data bits to 5
DEFINE SER2_BITS 7 ' Set Serin2 and Serout2 data bits to 6
DEFINE SER2_BITS 8 ' Set Serin2 and Serout2 data bits to 7 (default)
DEFINE SER2_BITS 9 ' Set Serin2 and Serout2 data bits to 8

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..16} | Receive binary digits
DEC{1..5} | Receive decimal digits
HEX{1..4} | Receive 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

1) | A variable preceded by BIN will receive the ASCII representation of its binary value. For example, if BIN B0 is specified and A1000" is received, B0 will be set to 8.
2) | A variable preceded by DEC will receive the ASCII representation of its decimal value. For example, if DEC B0 is specified and A123" is received, B0 will be set to 123.
3) | A variable preceded by HEX will receive the ASCII representation of its hexadecimal value. For example, if HEX B0 is specified and AFE" is received, B0 will be set to 254.
4) | SKIP followed by a count will skip that many characters in the input stream. For example, SKIP 4 will skip 4 characters..
5) | STR followed by a byte array variable, count and optional ending character will receive a string of characters. The string length is determined by the count or when the optional character is encountered in the input.
6) | The list of data items to be received may be preceded by one or more qualifiers between parenthesis after WAIT. SERIN2 must receive these bytes in exact order before receiving the data items. If any byte received does not match the next byte in the qualifier sequence, the qualification process starts over (i.e. the next received byte is compared to the first item in the qualifier list). A Qualifier can be a constant, variable or a string constant. Each character of a string is treated as an individual qualifier.
7) | WAITSTR can be used as WAIT above to force SERIN2 to wait for a string of characters of an optional length before proceeding.

Once any WAIT or WAITSTR qualifiers are satisfied, SERIN2 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 BIN, DEC or HEX, then SERIN2 converts a binary, decimal or hexadecimal 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 value is also discarded.

BIN, DEC and HEX may be followed by a number. Normally, these modifiers receive as many digits as are in the input. However, if a number follows the modifier, SERIN2 will always receive that number of digits, skipping additional digits as necessary. SERIN2 assumes a 4MHz oscillator when generating its bit timing. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. While single-chip RS-232 level converters are common and inexpensive, thanks to current RS-232 implementation and the excellent I/O specifications of the PICmicro, most applications don't require level converters. Rather, inverted TTL (Mode bit 14 = 1) can be used. A current limiting resistor is suggested (RS-232 is suppose to be short-tolerant).

See Also

SEROUT2
SERIN
SEROUT
HSERIN
HSEROUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SEROUT

SEROUT Pin,Mode,[Item {,Item...}]

Sends one or more items to Pin in standard asynchronous format using 8 data bits, no parity and one stop (8N1). SEROUT is similar to the BS1 Serout command. 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). The Mode names (e.g. T2400) are defined in the file MODEDEFS.BAS. To use them, add the line:

INCLUDE "modedefs.bas"

to the top of the PicBasic program. BS1DEFS.BAS and BS2DEFS.BAS already includes MODEDEFS.BAS. Do not include it again if one of these files is already included. The Mode numbers may be used without including this file.

Mode | Mode No. | Baud Rate | State
T2400 | 0 | 2400 | Driven True
T1200 | 1 | 1200
T9600 | 2 | 9600
T300 | 3 | 300
N2400 | 4 | 2400 | Driven Inverted
N1200 | 5 | 1200
N9600 | 6 | 9600
N300 | 7 | 300
OT2400 | 8 | 2400 | Open True
OT1200 | 9 | 1200
OT9600 | 10 | 9600
OT300 | 11 | 300
ON2400 | 12 | 2400 | Open Inverted
ON1200 | 13 | 1200
ON9600 | 14 | 9600
ON300 | 15 | 300

SEROUT supports three different data types which may be mixed and matched freely within a single SEROUT statement.

1) | A string constant is output as a literal string of characters.
2) | A numeric value (either a variable or a constant) will send the corresponding ASCII character. Most notably, 13 is carriage return and 10 is line feed.
3) | A numeric value preceded by a pound sign ( # ) will send the ASCII representation of its decimal value. For example, if W0 = 123, then #W0 (or #123) will send '1', '2', '3'.

SEROUT assumes a 4MHz oscillator when generating its bit timing. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. In some cases, the transmission rates of SEROUT instructions may present characters too quickly to the receiving device. A DEFINE adds character pacing to the serial output transmissions. This allows additional time between the characters as they are transmitted. The character pacing DEFINE allows a delay of 1 to 65,535 microseconds (.001 to 65.535 milliseconds) between each character transmitted. For example, to pause 1 millisecond between the transmission of each character:

DEFINE CHAR_PACING 1000

While single-chip RS-232 level converters are common and inexpensive, thanks to current RS-232 implementation and the excellent I/O specifications of the PICmicro, most applications don't require level converters. Rather, inverted TTL (N300..N9600) can be used. A current limiting resistor is suggested (RS-232 is suppose to be short-tolerant).

Example

' Send the ASCII value of B0 followed by a linefeed out Pin0 serially
SEROUT 0,N2400,[#B0,10]

See Also

SERIN
SERIN2
SEROUT2
HSERIN
HSEROUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SEROUT2

SEROUT2 DataPin{\FlowPin},Mode,{Pace,} {Timeout,Label,}[Item...]

Send one or more Items to DataPin in standard asynchronous format. SEROUT2 is similar to the BS2 Serout command. DataPin is automatically made an output. The optional FlowPin is automatically made an input. DataPin and FlowPin 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). 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. An optional Timeout and Label may be included to allow the program to continue if the FlowPin does not change to the enabled state within a certain amount of time. Timeout is specified in units of 1 millisecond.

In some cases, the transmission rates of SEROUT2 instructions may present characters too quickly to the receiving device. It may not be desirable to use an extra pin for flow control. An optional Pace can be used to add character pacing to the serial output transmissions. This allows additional time between the characters as they are transmitted. The character pacing allows a delay of 1 to 65,535 milliseconds between each character transmitted. 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

Some standard baud rates are listed in the following table.

Baud Rate | Bits 0 - 12
300 | 3313
600 | 1646
1200 | 813
2400 | 396
4800 | 188
9600 | 84
19200 | 32

Bit 13 selects even parity (bit 13 = 1) or no parity (bit 13 = 0). Normally, the serial transmissions are 8N1 (8 data bits, no parity and 1 stop bit). If parity is selected, the data is sent as 7E1 (7 data bits, even parity and 1 stop bit). 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. Some examples of Mode are: Mode = 84 (9600 baud, no parity, true, always driven), Mode = 16780 (2400 baud, no parity, inverted, driven), Mode = 60657 (300 baud, even parity, inverted, open).

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. With parity disabled (the default):

DEFINE SER2_BITS 4 ' Set Serin2 and Serout2 data bits to 4
DEFINE SER2_BITS 5 ' Set Serin2 and Serout2 data bits to 5
DEFINE SER2_BITS 6 ' Set Serin2 and Serout2 data bits to 6
DEFINE SER2_BITS 7 ' Set Serin2 and Serout2 data bits to 7
DEFINE SER2_BITS 8 ' Set Serin2 and Serout2 data bits to 8 (default)

With parity enabled:

DEFINE SER2_BITS 5 ' Set Serin2 and Serout2 data bits to 4
DEFINE SER2_BITS 6 ' Set Serin2 and Serout2 data bits to 5
DEFINE SER2_BITS 7 ' Set Serin2 and Serout2 data bits to 6
DEFINE SER2_BITS 8 ' Set Serin2 and Serout2 data bits to 7 (default)
DEFINE SER2_BITS 9 ' Set Serin2 and Serout2 data bits to 8

SEROUT2 supports many different data modifiers which may be mixed and matched freely within a single SEROUT2 statement to provide various output formatting.

Modifier | Operation
{I}{S}BIN{1..16} | Send binary digits
{I}{S}DEC{1..5} | Send decimal digits
{I}{S}HEX{1..4} | Send hexadecimal digits
REP c\n | Send character c repeated n times
STR ArrayVar{\n} | Send string of n characters

1) | A string constant is output as a literal string of characters.
2) | A numeric value (either a variable or a constant) will send the corresponding ASCII character. Most notably, 13 is carriage return and 10 is line feed.
3) | A numeric value preceded by BIN will send the ASCII representation of its binary value. For example, if B0 = 8, then BIN B0 (or BIN 8) will send "1000".
4) | A numeric value preceded by DEC will send the ASCII representation of its decimal value. For example, if B0 = 123, then DEC B0 (or DEC 123) will send "123".
5) | A numeric value preceded by HEX will send the ASCII representation of its hexadecimal value. For example, if B0 = 254, then HEX B0 (or HEX 254) will send "FE".
6) | REP followed by a character and count will repeat the character, count time. For example, REP A0"\4 will send "0000".
7) | STR followed by a byte array variable and optional count will send a string of characters. The string length is determined by the count or when a 0 character is encountered in the string.

BIN, DEC and HEX may be preceded or followed by several optional parameters. If any of them are preceded by an I (for indicated), the output will be preceded by either a "%", "#" or "$" to indicate the following value is binary, decimal or hexadecimal. 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". Any or all of the modifier combinations may be used at once. For example, ISDEC4 B0. SEROUT2 assumes a 4MHz oscillator when generating its bit timing. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to the new oscillator value. While single-chip RS-232 level converters are common and inexpensive, thanks to current RS-232 implementation and the excellent I/O specifications of the PICmicro, most applications don't require level converters. Rather, inverted TTL (Mode bit 14 = 1) can be used. A current limiting resistor is suggested (RS-232 is suppose to be short-tolerant).

Example

' Send the ASCII value of B0 followed by a linefeed out Pin0 serially at 2400 baud
SEROUT2 0,16780,[dec B0,10]

' Send “B0 =” followed by the binary value of B0 out PORTA pin 1 serially at 9600 baud
SEROUT2 PORTA.1,84,["B0=", ihex4 B0]

See Also

SERIN2
SERIN
SEROUT
HSERIN
HSEROUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SHIFTIN

SHIFTIN DataPin,ClockPin,Mode,[Var{\Bits}...]

Clock ClockPin, synchronously shift in bits on 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). \Bits optionally specifies the number of bits to be shifted in. If it is not specified, 8 bits are shifted in, independent of the variable type. The Mode names (e.g. MSBPRE) are defined in the file MODEDEFS.BAS. To use them, add the line:

INCLUDE "modedefs.bas"

to the top of the PicBasic Pro program. BS1DEFS.BAS and BS2DEFS.BAS already includes MODEDEFS.BAS. Do not include it again if one of these files is already included. The Mode numbers may be used without including this file. Some Modes do not have a name. 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.

Mode | Mode No. | Operation
MSBPRE | 0 | Shift data in highest bit first, Read data before sending clock. Clock idles low.
LSBPRE | 1 | Shift data in lowest bit first, Read data before sending clock. Clock idles low.
MSBPOST | 2 | Shift data in highest bit first, Read data after sending clock. Clock idles low.
LSBPOST | 3 | Shift data in lowest bit first, Read data after sending clock. Clock idles low.
 | 4 | Shift data in highest bit first, Read data before sending clock. Clock idles high.
 | 5 | Shift data in lowest bit first, Read data before sending clock. Clock idles high.
 | 6 | Shift data in highest bit first, Read data after sending clock. Clock idles high.
 | 7 | Shift data in lowest bit first, Read data after sending clock. Clock idles 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 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. For example, to slow the clock by an additional 100 microseconds:

DEFINE SHIFT_PAUSEUS 100

Example

SHIFTIN 0,1,MSBPRE,[B0,B1\4]

See Also

SHIFTOUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SHIFTOUT

SHIFTOUT DataPin,ClockPin,Mode,[Var{\Bits}...]

Synchronously shift out Var on ClockPin and DataPin. 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). \Bits optionally specifies the number of bits to be shifted out. If it is not specified, 8 bits are shifted out, independent of the variable type. The Mode names (e.g. LSBFIRST) are defined in the file MODEDEFS.BAS. To use them, add the line:

INCLUDE "modedefs.bas"

to the top of the PicBasic Pro program. BS1DEFS.BAS and BS2DEFS.BAS already includes MODEDEFS.BAS. Do not include it again if one of these files is already included. The Mode numbers may be used without including this file. Some Modes do not have a name. 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.

Mode | Mode No. | Operation
LSBFIRST | 0 | Shift data out lowest bit first. Clock idles low.
MSBFIRST | 1 | Shift data out highest bit first. Clock idles low.
 | 4 | Shift data out lowest bit first. Clock idles high.
 | 5 | Shift data out highest bit first. Clock idles 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 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. For example, to slow the clock by an additional 100 microseconds:

DEFINE SHIFT_PAUSEUS 100

Example

SHIFTOUT 0,1,MSBFIRST,[B0,B1]
SHIFTOUT PORTA.1, PORTA.2, 1,[wordvar\4]

See Also

SHIFTIN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SLEEP

SLEEP Period

Place microcontroller into low power mode for Period seconds. Period is 16-bits, so delays can be up to 65,535 seconds (just over 18 hours). SLEEP uses the Watchdog Timer so it is independent of the actual oscillator frequency. The granularity is about 2.3 seconds and may vary based on device specifics and temperature. This variance is unlike the BASIC Stamp. The change was necessitated because when the PICmicro executes a Watchdog Timer reset, it resets many of the internal registers to predefined values. These values may differ greatly from what your program may expect. By running the SLEEP command uncalibrated, this issue is sidestepped.

Example

SLEEP 60 ' Sleep for about 1 minute

See Also

NAP
PAUSE
PAUSEUS

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SOUND

SOUND Pin,[Note,Duration{,Note,Duration...}]

Generates tone and/or white noise on the specified Pin. 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). 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.

SOUND outputs TTL-level square waves. Thanks to the excellent I/O characteristics of the PICmicro, a speaker can be driven through a capacitor. The value of the capacitor should be determined based on the frequencies of interest and the speaker load. Piezo speakers can be driven directly.

Example

SOUND PORTB.7,[100,10,50,10] ' Send 2 sounds consecutively to Pin7


STOP

Stop program execution by executing an endless loop. This does not place the microcontroller into low power mode. The microcontroller is still working as hard as ever. It is just not getting much done.

Example

STOP ' Stop program dead in its tracks

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


SWAP

SWAP Variable,Variable

Exchange the values between two variables. Usually, it is a tedious process to swap the value of two variables. SWAP does it in one statement without using any intermediate variables. It can be used with bit, byte and word variables. Array variables with a variable index may not be used in SWAP, although array variables with a constant index are allowed.

Example

temp = B0 ' Old way
B0 = B1
B1 = temp

SWAP B0, B1 ' New way

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


TOGGLE

TOGGLE Pin

Invert the state of the specified Pin. 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).

Example

LOW 0 ' Start Pin0 as low
TOGGLE 0 ' Change state of Pin0 to high

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


WHILE

WHILE...WEND

WHILE Condition
  Statements...
WEND

Repeatedly execute Statements WHILE Condition is true. When the Condition is no longer true, execution continues at the statement following the WEND. Condition may be any comparison expression.

Example

i = 1
WHILE i <= 10
  SEROUT 0,N2400,["No:",#i,13,10]
  i = i + 1
WEND

See Also

FOR...NEXT
REPEAT...UNTIL

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


USBINIT

Support has been added for the PIC16C745 and 765 low-speed USB devices. This support takes the form of three new PBP commands as well as some modifications to the Microchip USB libraries. USBInit needs to be one of the first statements in the program. It will initialize the USB portion of the PICmicro MCU and wait until the USB bus is configured and enabled. The USB subdirectory contains the modified Microchip USB libraries as well as example programs. USB programs require several addtional files to operate (which are in the USB subdirectory), some of which will require modification for your particular application. See the text file in the USB subdirectory for more information on the USB commands.

USB communications is much more complicated than synchronous (SHIFTIN and SHIFTOUT) and asynchronous (SERIN, SEROUT and so forth) communications. There is much more to know about USB operation that can possibly be described here. The USB information on the Microchip web site needs to be studied.

See Also

USBIN
USBOUT

Copyright © 2001 microEngineering Labs, Inc.


USBIN

USBIN Endpoint,Buffer,CountVar,Label

USBIN gets any available USB data for the endpoint and places it in the buffer. Buffer must be a byte array of suitable length to contain the data. Countvar will contain the number of bytes transferred to the buffer. Label will be jumped to if no data is available. The USB subdirectory contains the modified Microchip USB libraries as well as example programs. USB programs require several addtional files to operate (which are in the USB subdirectory), some of which will require modification for your particular application. See the text file in the USB subdirectory for more information on the USB commands.

USB communications is much more complicated than synchronous (SHIFTIN and SHIFTOUT) and asynchronous (SERIN, SEROUT and so forth) communications. There is much more to know about USB operation that can possibly be described here. The USB information on the Microchip web site needs to be studied.

See Also

USBOUT
USBINIT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


USBOUT

USBOUT Endpoint,Buffer,Count,Label

USBOut takes count number of bytes from the buffer and sends 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. The USB subdirectory contains the modified Microchip USB libraries as well as example programs. USB programs require several addtional files to operate (which are in the USB subdirectory), some of which will require modification for your particular application. See the text file in the USB subdirectory for more information on the USB commands.

USB communications is much more complicated than synchronous (SHIFTIN and SHIFTOUT) and asynchronous (SERIN, SEROUT and so forth) communications. There is much more to know about USB operation that can possibly be described here. The USB information on the Microchip web site needs to be studied.

See Also

USBIN
USBINIT

Copyright © 2001 microEngineering Labs, Inc.


USBOUT

USBSERVICE

USBSERVICE

USBService needs to be executed repeatedly in the program. Since the provided USB code is polled rather than interrupt driven, USBService needs to be executed at least every 10ms throughout the program. If it is not, the device may drop off the USB bus.See Also

USBIN
USBOUT
 USBINIT

Copyright © 2005 microEngineering Labs, Inc.


WRITE

WRITE Address,Value

Write Value to the on-chip EEPROM at the specified Address. This instruction may only be used with a PICmicro that has an on-chip EEPROM data area such as the PIC16F84, PIC16C84 and the PIC16F87x series. WRITE is used to set the values of the on-chip EEPROM at runtime. To set the values of the on-chip EEPROM at programming-time, use the DATA or EEPROM statement. Each WRITE is self-timed and takes about 10 milliseconds to execute on a PICmicro.

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. WRITE will not work on devices with on-chip I2C interfaced serial EEPROM like the 12CE67x and 16CE62x parts. Use the I2CWRITE instruction instead.

Example

WRITE 5,B0 ' Send value in B0 to EEPROM location 5

See Also

READ
I2CREAD
I2CWRITE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


WRITECODE

WRITECODE Address,Value

Write the word-sized Value to the code space at location Address. The PIC16F87x devices allow code to be read and written at run-time. While writing self-modifying code can be a dangerous technique, it does allow non-volatile data storage above 64 - 256 bytes. One must be very careful not to write over active program memory. The listing file may be examined to determine program addresses.

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.

Example

WRITECODE 100,W ' Send value in W to code space location 100

See Also

READCODE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


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.

DataPin is the automatically made an input to receive data from the X-10 interface. ZeroPin is automatically made an input to received the zero crossing timing from the X-10 interface. Both pins should be pulled up to 5 volts with 4.7K resistors. DataPin and ZeroPin 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). An optional Timeout and Label may be included to allow the program to continue if X-10 data is not received within a certain amount of time. Timeout is specified in AC power line half-cycles (approximately 8.33 milliseconds). 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.

If Var is word-sized, each House Code received is stored in the upper byte of the word. Each received Key Code is stored in the lower byte of the word. If Var is a byte, only the Key Code is stored. The House Code is a number between 0 and 15 that corresponds to the House Code set on the X-10 module A through P. 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 examples will clarify things. Key Code numbers 0-15 correspond to module numbers 1-16.

Example

housekey VAR WORD

' Get X-10 data
loop: XIN PORTA.2,PORTA.0,[housekey]

' Display X-10 data on LCD
LCDOUT $fe,1,"House=",#housekey.byte1, "Key=",#housekey.byte0

GOTO loop ' Do it forever

' Check for X-10 data, go to nodata if none
XIN PORTA.2,PORTA.0,1,nodata,[housekey]

See Also

XOUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


XOUT

XOUT DataPin,ZeroPin, [HouseCode\KeyCode{\Repeat}{,...}]

Send HouseCode followed by KeyCode, Repeat number of times in X-10 format. If the optional Repeat is left off, 2 times (the minimum) is assumed. Repeat is usually reserved for use with the Bright and Dim commands. XOUT is used to send control information to X-10 modules. These 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. Either the PL-513 for send only, or the TW-523 for two-way X-10 communications are required. These devices contain the power line interface and isolate the microcontroller from the AC line. Since the X-10 format is patented, these interfaces also cover the license fees.

DataPin is the automatically made an output to send data to the X-10 interface. ZeroPin is automatically made an input to received the zero crossing timing from the X-10 interface. It should be pulled up to 5 volts with a 4.7K resistor. DataPin and ZeroPin 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).
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.

HouseCode is a number between 0 and 15 that corresponds to the House Code set on the X-10 module A through P. The proper HouseCode must be sent as part of each command. 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:

INCLUDE "modedefs.bas"

to the top of the PicBasic Pro program. BS1DEFS.BAS and BS2DEFS.BAS already includes MODEDEFS.BAS. Do not include it again if one of these files is already included. The KeyCode numbers may be used without including this file.

KeyCode | KeyCode No. | Operation
unitOn | %10010 | Turn module on
unitOff | %11010 | Turn module off
unitsOff | %11100 | Turn all modules off
lightsOn | %10100 | Turn all light modules on
lightsOff | %10000 | Turn all light modules off
bright | %10110 | Brighten light module
dim | %11110 | Dim light module

Wiring to the X-10 interfaces requires 4 connections. Output from the X-10 interface (zero crossing and receive data) are open-collector and require a pull up resistor of around 4.7K to 5 volts. Wiring tables for each interface is shown below:

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

Example

house VAR BYTE
unit VAR BYTE

INCLUDE "modedefs.bas"

house = 0 ' Set house to 0 (A)
unit = 8 ' Set unit to 8 (9)
' Turn on unit 8 in house 0
XOUT PORTA.1,PORTA.0,[house\unit,house\unitOn]

' Turn off all the lights in house 0
XOUT PORTA.1,PORTA.0,[house\lightsOff]

' Blink light 0 on and off every 10 seconds
XOUT PORTA.1,PORTA.0,[house\0]

loop: XOUT PORTA.1,PORTA.0,[house\unitOn]
PAUSE 10000 ' Wait 10 seconds

XOUT PORTA.1,PORTA.0,[house\unitOff]
PAUSE 10000 ' Wait 10 seconds

GOTO loop

See Also

XIN

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Mecanique

Acknowledgments

This software uses the SynEdit syntax highlighter, an open source project under the Mozilla Public License (MPL). This is an excellent piece of software which I strongly recommend. The program also uses Coco/R for Delphi by Michael Reith for some of the syntax parsing. Again, this is a superb piece of software. MicroCode Studio was written entirely using Borland Delphi 4.

SynEdit Website
synedit.sourceforge.net

Coco/R for Delphi Website
www.tetzel.com

 Borland Website
www.borland.com


DEBUGIN

DEBUGIN {Timeout,Label,}[Item{,Item...}]

Receive one or more Items from a predefined pin at a predefined baud rate in standard asynchronous format using 8 data bits, no parity and 1 stop bit (8N1). The pin is automatically made an input. An optional Timeout and Label may be included to allow the program to continue if a character is not received within a certain amount of time. Timeout is specified in units of 1 millisecond. DEBUGIN supports the same data modifiers as SERIN2.

Modifier | Operation
BIN{1..16} | Receive binary digits
DEC{1..5} | Receive decimal digits
HEX{1..4} | Receive 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

DEBUGIN is one of several built-in asynchronous serial functions. It is the smallest of the software generated serial routines. It can be used to receive debugging information from a terminal program like Hyperterm or the Serial Communications Window in MicroCode Studio. It can also be used anytime serial input is desired on a fixed pin at a fixed baud rate. The serial pin and baud rate are specified using DEFINEs. For example,

' Set Debugin pin port
DEFINE DEBUGIN_REG PORTB

' Set Debugin pin bit
DEFINE DEBUGIN_BIT 0

' Set Debugin mode: 0 = true, 1 = inverted
DEFINE DEBUGIN_MODE 1

If any of these DEFINEs are not included in a program, the DEBUGIN port, pin or mode is set to the same values as they are for DEBUG. The DEBUGIN baud rate is always the same as DEBUG. It cannot be DEFINEd differently. DEBUGIN assumes a 4MHz oscillator when generating its bit timing. To maintain the proper baud rate timing with other oscillator values, be sure to DEFINE the OSC setting to any different oscillator value. While single-chip RS-232 level converters are common and inexpensive, thanks to current RS-232 implementation and the excellent I/O specifications of the PICmicro, most applications don't require level converters. Rather, inverted TTL (DEBUGIN_MODE = 1) can be used. A current limiting resistor is suggested (RS-232 is suppose to be short-tolerant).

See Also

DEBUG
SERIN2

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Mecanique

Purchasing

Thank you for evaluating the MicroCode Studio Integrated Development Environment (IDE) with the PICBasic PRO compiler demonstration. Purchasing the full version of PICBasic PRO will give you support for all of of Microchip's PICmicro® microcontrollers with no line limits for the code you write. Purchasing MicroCode Studio PLUS will give you In Circuit Debugging (ICD) support for many PICmicro® devices and bootloader software, which enables you to download your code directly to a development board (without the need of a programmer) using the serial port on your computer.

Tell me more about...

For more information about the compiler and IDE capabilities, visit the following online...

PICBasic PRO Compiler
MicroCode Studio IDE
In Circuit Debugging (ICD)
Bootloader Software

Where can I buy?

For a list of MicroCode Studio PLUS resellers, please visit

MicroCode Studio

You can purchase the full version of microEngineering Labs PICBASIC PRO from many locations throughout the world. For the most up to date list, you should check online here.


DISABLE DEBUG

DISABLE DEBUG processing following this instruction. The debug monitor will not be called between instructions until an ENABLE or ENABLE DEBUG is encountered. DISABLE DEBUG and ENABLE DEBUG are more like pseudo-ops in that they give the compiler directions, rather than actually generate code.

See Also

ENABLE
ENABLE DEBUG
ON DEBUG

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


DISABLE INTERRUPT

DISABLE INTERRUPT processing following this instruction. Interrupts can still occur but the BASIC interrupt handler in the PicBasic Pro program will not be executed until an ENABLE or ENABLE INTERRUPT is encountered. DISABLE INTERRUPT and ENABLE INTERRUPT are more like pseudo-ops in that they give the compiler directions, rather than actually generate code.

Example

DISABLE INTERRUPT ' Disable interrupts in handler
myint: led = 1 ' Turn on LED when interrupted
RESUME ' Return to main program
ENABLE INTERRUPT ' Enable interrupts after handler

See Also

ENABLE
ENABLE INTERRUPT
ON INTERRUPT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ENABLE DEBUG

ENABLE DEBUG processing that was previously DISABLEd following this instruction. DISABLE DEBUG and ENABLE DEBUG are more like pseudo-ops in that they give the compiler directions, rather than actually generate code.

Example

ENABLE DEBUG ' enable calls to the debug monitor

See Also

DISABLE
DISABLE DEBUG
ON DEBUG

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ENABLE INTERRUPT

ENABLE INTERRUPT processing that was previously DISABLEd following this instruction. DISABLE INTERRUPT and ENABLE INTERRUPT are more like pseudo-ops in that they give the compiler directions, rather than actually generate code.

Example

DISABLE INTERRUPT ' Disable interrupts in handler
myint: led = 1 ' Turn on LED when interrupted
RESUME ' Return to main program
ENABLE INTERRUPT ' Enable interrupts after handler

See Also

DISABLE
DISABLE INTERRUPT
ON INTERRUPT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


ICD Address Mismatch

MicroCode Studio is unable to run the ICD because the microcontroller is communicating different address information from those contained in the debug files.

To correct this problem, simply rebuild your project using either ICD Compile or ICD Compile and Program and then re-program you microcontroller.


ICD Build Required

MicroCode Studio is unable to run the ICD because the required debug files are missing.

To correct this problem, simply rebuild your project using either ICD Compile or ICD Compile and Program and then re-program you microcontroller.


ICD Chip ID

MicroCode Studio is unable to run the code on the host PIC microcontroller because it has a different ICD identification code.

Every time you program your target device with debugging information, a new ICD identification code is assigned. This is to ensure that the code on your microcontroller and the PICBasic code displayed in MicroCode Studio remain synchronised. The most likely cause of this error is that your project file has been changed.

To correct this problem, simply rebuild your project using either ICD Compile or ICD Compile and Program and then re-program you microcontroller.


ICD Chip ID

ICD Compiler Version

MicroCode Studio is unable to build ICD debug information.

In order to build debugging information, you need to ensure you are using version 2.20 or higher of the PICBasic PRO compiler. The ICD will not work with the standard PICBasic compiler.


ICD Connection Timeout

MicroCode Studio is unable to connect to the target PIC microcontroller that hosts the ICD code.

There are a number of possible reasons for this error.

Connection
ICD Build
Oscillator Setting
Disable Debug Directive
Bootloader

Connection

Your should ensure that power is being supplied to the target device and that the serial cable is connected properly. You should also make sure that the correct serial port has been set for use by the ICD. You can set the COM port from the drop down selection box, located on the main ICD toolbar.

ICD Build

You should also make sure that you have programmed the target device using the ICD Compile or ICD Compile and Program toolbar buttons. You cannot run the ICD if the source code has been compiled using the standard Compile or Compile and Program toolbar buttons.

Oscillator Setting

It is essential that your PICBasic code has the correct oscillator setting defined. By default, this is 4MHz. If your target device is running at a different speed, you must make sure the appropriate define is used in your PICBasic code. For example, if you have a PIC16F628 running at 10MHz, use the following statement at the beginning of your program:

DEFINE OSC 10

Failing to set the correct oscillator setting causes problems for the ICD. In short, if the setting in your code does not match the actual speed of your PIC microcontroller, the ICD will not work.

Disable Debug Directive

You can use the DISABLE DEBUG directive to increase the ICD execution speed or reduce the ICD code overhead. However, you must ensure that the ICD can take control of the target microcontroller within one second. If it cannot take control of the device within one second, a timeout error occurs. To resolve this problem, ensure that you have at least one PICBasic instruction at the beginning of your program that is enabled.

Bootloader

If you are using a bootloader, make sure you include

DEFINE LOADER_USED 1

for versions of PICBasic Pro 2.33 or higher. For earlier compilers, use

DEFINE ONINT_USED 1

You should ensure that you also reset the target device before running the ICD, in order that MicroCode Studio can take control of the microcontroller. If you are using the microEngineering Labs loader (meloader), you can do this automatically by checking Go (Run) After Programming from the meloader OPTIONS menu.


ICD Line Truncate

MicroCode Studio is unable to process one of the debug files due to line truncating.

When using some operating systems with the PICBasic default assembler, long path and filenames can result in important debugging information being lost. Under these circumstances, the ICD is unable to operate correctly. To correct this problem, ensure that the PICBasic filename and its associated path are no more than sixty characters in length.

You should not normally see this error if assembling using MPASM.


ICD Model Not Supported

The ICD model selected is not supported by this version of MicroCode Studio.

MicroCode Studio has one only ICD model available for use. If you would like to use additional ICD models, you should purchase MicroCode Studio Plus. For a list of available models, please read the ICD Models section.


ICD Sort Program

ICD Monitor Program

'*****************************************************************
'*  Name     : 18_ICD_PBPX                                       *
'*  Author   : David John Barker                                 *
'*  Notice   : Copyright (c) 2011 Mecanique                      *
'*           : All Rights Reserved                               *
'*  Date     : 10/06/11                                          *
'*  Modified :                                                   *
'*  Version  : 3.0                                               *
'*  Notes    : Debug monitor program for 18 series of MCU - may  *
'*           : need modifying for specific chip types            *
'*****************************************************************

' optional preprocessor defines - DO NOT EDIT OR DISABLE!!!...
#define _OSC_XX
#define _EXTENDED_ADDRESS
#define _EXTENDED_EEPROM
#define _NO_EEPROM

' ICD commands...
MCS_STEP      con $73 ' ascii 's'
MCS_DUMP      con $64 ' ascii 'd'
MCS_HANDSHAKE con $68 ' ascii 'h'
MCS_RESET     con $72 ' ascii 'r'
MCS_WRITE     con $77 ' ascii 'w'

'*****************************************************************
'*  BRG16   BRGH    USARTMODE   FORMULA                          *
'*  0       0       8 Bit       FOSC / (64 * (BAUDRATE + 1))     *
'*  0       1       8 Bit       FOSC / (16 * (BAUDRATE + 1))     *
'*  1       0       16 Bit      FOSC / (4 * (BAUDRATE + 1))      *
'*  1       1       16 Bit      FOSC / (4 * (BAUDRATE + 1))      *
'*****************************************************************

define HSER_RCSTA 90H           ' enable serial port and continuous receive
define HSER_TXSTA 24H           ' enable transmit, BRGH = 1

' OSC = 20
#ifdef _OSC_20
define HSER_BAUD  115200
define HSER_SPBRG (OSC * 1000000) / (16 * (HSER_BAUD + 1))
#define ICD_BAUDRATE_SET
#endif

' OSC = 64
#ifdef _OSC_64
BAUDCON.3 = 1                   ' enable 16 bit baud generator
define HSER_BAUD  115200        ' set the baudrate
define HSER_SPBRG (OSC * 1000000) / (4 * (HSER_BAUD + 1))
#define ICD_BAUDRATE_SET
#endif

' a specific baudrate has not been set (see above) so default
' to the "catch all" 19200 baud - if you are using OSC settings
' that are higher than 20, you may want to look at defining your own
' setting like those above...
#ifndef ICD_BAUDRATE_SET
define HSER_BAUD  19200
define HSER_SPBRG (OSC * 1000000) / (16 * (HSER_BAUD + 1))
#endif

' stack level and program address...
DEBUG_STACK     var     byte bank0 system
DEBUG_ADDRESS   var     word bank0 system
DEBUG_ADDRESSU  var     byte bank0 system

' reserve some variables
MCSByte1        var     byte bank0
MCSWord1        var     word bank0
MCSByte2        var     byte bank0
MCSByte3        var     byte bank0

' give them more user friendly names
MCSCommand      var     MCSByte1
MCSValue        var     MCSByte1
MCSAddr         var     MCSWord1
MCSAddrL        var     MCSWord1.byte0
MCSAddrH        var     MCSWord1.byte1
MCSBankStart    var     MCSByte2
MCSBankEnd      var     MCSByte3

' start stack level at 0...
DEBUG_STACK    = $00
DEBUG_ADDRESSU = $00

' ******************* USER INITIALISATION CODE *******************
' some devices have specific requirements - for example, making
' the USART pins digital - use this section to add your custom
' code...
' <== ADD CODE HERE
'*****************************************************************

' important - skip around the debug monitor...
goto MCSSkipMonitor

' the ON DEBUG command will execute this bit of code...
MCSMonitor:

   ' get debug address upper, high and low
   ' bytes - then send as three byte data packet
   #ifdef _EXTENDED_ADDRESS
   hserout [DEBUG_ADDRESSU, DEBUG_ADDRESS.byte1, DEBUG_ADDRESS.byte0]
   #else
   hserout [DEBUG_ADDRESS.byte1, DEBUG_ADDRESS.byte0]
   #endif

' main debug monitor loop to get command and execute
MCSMonitorLoop:

   ' wait for and then interpret command
   hserin [MCSCommand]
   if MCSCommand = MCS_STEP then
      goto MCSMonitorStep
   elseif MCSCommand = MCS_DUMP then
      goto MCSMonitorDump
   elseif MCSCommand = MCS_WRITE then
      goto MCSMonitorWrite
   elseif MCSCommand = MCS_HANDSHAKE then
      goto MCSMonitorHandshake
   elseif MCSCommand = MCS_RESET then
      goto MCSMonitorReset
   endif

   ' loop back...
   goto MCSMonitorLoop

' write recived data...
MCSMonitorWrite:
   hserin [MCSAddrH, MCSAddrL, MCSValue]

   ' no internal EEPROM, just write data value...
   #ifdef _NO_EEPROM
      FSR0H = MCSAddrH
      FSR0L = MCSAddrL
      INDF0 = MCSValue

   ' yes, device has internal EEPROM...
   #else

   ' if bit 7 of MCSAddrH is set then we will
   ' write to EEPROM, else we write to data RAM...
   if MCSAddrH.7 = 1 then

      ' if extended EEPROM, clear upper bit and use
      ' WORD address...
      #ifdef _EXTENDED_EEPROM
      MCSAddrH.7 = 0
      write MCSAddr, MCSValue

      ' it's not extended EEPROM, use single BYTE address
      #else
      write MCSAddrL, MCSValue
      #endif

   ' write data byte...
   else
      FSR0H = MCSAddrH
      FSR0L = MCSAddrL
      INDF0 = MCSValue
   endif
   #endif ' #define _NO_EEPROM

   ' acknowledge
   hserout [$FF]
   goto MCSMonitorLoop

' dump data block...
MCSMonitorDump:

   ' get bank start, end and high address
   hserin [MCSBankStart, MCSBankEnd, MCSAddrH]
   for MCSAddrL = MCSBankStart to MCSBankEnd

      ' no internal EEPROM, just read data value...
      #ifdef _NO_EEPROM
      FSR0H = MCSAddrH
      FSR0L = MCSAddrL
      MCSValue = INDF0

      ' yes, device has internal EEPROM...
      #else

      ' if bit 7 of MCSAddrH is set then we will
      ' read from EEPROM, else we read data RAM...
      if MCSAddrH.7 = 1 then

         ' if extended EEPROM, clear upper bit and use
         ' WORD address...
         #ifdef _EXTENDED_EEPROM
         MCSAddrH.7 = 0
         read MCSAddr, MCSValue

         ' it's not extended EEPROM, use single BYTE address
         #else
         read MCSAddrL, MCSValue
         #endif

      ' read a data byte...
      else
         FSR0H = MCSAddrH
         FSR0L = MCSAddrL
         MCSValue = INDF0
      endif
      #endif ' #define _NO_EEPROM

      ' output the byte value read...
      hserout [MCSValue]
   next MCSAddrL          ' next address
   goto MCSMonitorLoop    ' loop back to main monitor

' do handshake
MCSMonitorHandshake:
   hserout ["$CHIPID$"] ' *** do not change ***
   goto MCSMonitorLoop  ' loop back to main monitor

' start program over from reset address
MCSMonitorReset:
asm
   reset
endasm

' single step one program instruction - just go back to
' beginning and pump out address
MCSMonitorStep:
#ifdef _EXTENDED_ADDRESS
asm
   movf    DEBUG_ADDRESS + 2, W    ; Set PCLATU with upper byte of return address
   movwf   PCLATU
   movf    DEBUG_ADDRESS + 1, W    ; Set PCLATH with top byte of return address
   movwf   PCLATH
   movf    DEBUG_ADDRESS, W        ; Go back to main program
   movwf   PCL
endasm
#else
asm
   movf    DEBUG_ADDRESS + 1, W    ; Set PCLATH with top byte of return address
   movwf   PCLATH
   movf    DEBUG_ADDRESS, W        ; Go back to main program
   movwf   PCL
endasm
#endif

MCSSkipMonitor:
   on debug goto MCSMonitor


ICD Model Version

This version of MicroCode Studio is unable to load the ICD model file.

You should ensure you have the latest version of MicroCode Studio in order to run the selected ICD model. To get the latest version of MicroCode Studio, please visit the Mecanique website.


ICD Port

ICD Port Connection Failure

MicroCode Studio is unable to connect to the target PIC microcontroller using the assigned serial port.

You should ensure the correct serial port has been set for use by the ICD. You can set the COM port from the drop down selection box, located on the main ICD toolbar.


ICD Sort Program

Sort Program

'****************************************************************
'*  Name    : Sort.bas                                           *
'*  Author  : David John Barker                                  *
'*  Notice  : Copyright (c) 2001 Mecanique                       *
'*          : All Rights Reserved                                *
'*  Date    : 12/13/01                                           *
'*  Version : 1.0                                                *
'*  Notes   : ICD sample program                                 *
'*          : Sorts an array of n-elements using a simple       *
'*          : bubble sort algorithm                              *
'****************************************************************

' bootloader and OSC settings
DEFINE     LOADER_USED 1 ' remove if you dont use a bootloader!!
DEFINE     OSC 10         ' set the correct speed here!!

' constants
ArraySize     CON 10
True          CON 1
False         CON 0

' variables
Array         VAR WORD(ArraySize)
Index         VAR BYTE
InnerIndex    VAR BYTE
OuterIndex    VAR BYTE
ListSorted    VAR BYTE
RandomValue   VAR WORD
TmpValue      VAR WORD

ProgramStart:

   ' initialise the array with
   ' random values for sorting
   FOR Index = 0 TO ArraySize - 1
      RANDOM RandomValue
      Array(Index) = RandomValue
   NEXT Index

   ' sort the array - simple bubble sort
   ListSorted = False
   OuterIndex = 0

   WHILE NOT ListSorted AND (OuterIndex < ArraySize)
      ListSorted = True

      ' check for exchange
      FOR InnerIndex = 0 TO ArraySize - 2
         Index = InnerIndex + 1
         IF Array(InnerIndex) < Array(Index) THEN
            TmpValue = Array(InnerIndex)
            Array(InnerIndex) = Array(Index)
            Array(Index) = TmpValue
            ListSorted = False
         ENDIF
      NEXT
      OuterIndex = OuterIndex + 1
   WEND

   ' repeat forever
   GOTO ProgramStart


ICD System Error

MicroCode Studio has encountered a system error while trying to build or run the ICD.

You should not encounter this error under normal conditions. If the problem persists, please contact Mecanique stating the displayed error code.


LCDIN

LCDIN {Address,}[Var{,Var...}]

Read LCD RAM at Address and store data to 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. CG (character generator) RAM runs from address $40 to $7f. Display data RAM starts at address $80. See the data sheet for the specific LCD for these addresses and functions. It is necessary to connect the LCD read/write line to a PICmicro pin so that it may be controlled to select either a read (LCDIN) or write (LCDOUT) operation. Two DEFINEs control the pin address:

DEFINE LCD_RWREG PORTE ' LCD read/write pin port
DEFINE LCD_RWBIT 2 ' LCD read/write pin bit

See Also

LCDOUT

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Main Editor

The MicroCode Studio Editor

Overview

MicroCode Studio is a powerful, visual Integrated Development Environment (IDE) with In Circuit Debugging (ICD) capability designed specifically for microEngineering Labs PICBasic PRO compiler. The main studio editor provides full syntax highlighting of your code. You can change the colors and text attributes used by the syntax highlighter in the editor options window. When typing your code, a small hint window will sometimes appear showing the preferred syntax of certain keywords. When these appear, you can use you mouse button to click on the window to provide context sensitive help on that subject. Alternatively, when the cursor is near a keyword, just press F1 for help. The code explorer allows you to automatically jump to include files, symbols, defines, variables and labels that are contained within your source code. Full cut, copy, paste and undo is provided, together with search and replace features.

See Also

Menu Options
The Main Toolbar
The Edit Toolbar
The Compile and Program Toolbar
The ICD Toolbar
The Code Explorer
The Serial Communications Window
PICBasic Options
Editor Options
Installing a Programmer
Using the ICD


ON DEBUG

ON DEBUG GOTO Label

ON DEBUG allows a debug monitor program to be executed between each PicBasic instruction. The method by which this happens is similar to the method used by ON INTERRUPT GOTO. Once ON DEBUG GOTO is encountered, a call to the specified debug label is inserted before each PicBasic Pro instruction in the program. DISABLE DEBUG prevents the insertion of this call while ENABLE DEBUG resumes the insertion of the call. A monitor routine may be written that is activated before each instruction. This routine can send data to an LCD or to a serial comm program. Any program information may be displayed or even altered in this manner.

A word-sized system variable that resides in BANK0 is required to provide place to store the address the program was at before the monitor routine was called by ON DEBUG GOTO:

DEBUG_ADDRESS VAR WORD BANK0 SYSTEM

An Additional byte-sized variable may be used to return the level of the current program stack:

DEBUG_STACK VAR BYTE BANK0 SYSTEM

This level should never be greater than 4 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.

See Also

ENABLE DEBUG
DISABLE DEBUG
ENABLE
DISABLE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Ports and Other Registers

All of the PICmicro registers, including the ports, can be accessed just like any other byte-sized variable in PicBasic. This means that they can be read from, written to or used in equations directly:

Example

PORTA = %01010101 ' Write value to PORTA
anyvar = PORTB & $0f ' Isolate lower 4 bits of PORTB and place result in anyvar


Print Preview

The print preview dialog enables you to view and review your source code before outputting it to a printer. You can use the zoom feature to fit the document to the page, or zoom in or out in the range 25 to 200%. If you only want to print a certain number of pages, select the print option from the file menu. Using the print icon on the main toolbar will send all pages to the attached printer device. The 'show header / footer' button enables or disables printing of filename, page number, date and time on the program listing.


READCODE

READCODE Address,Var

Read the word-sized code at location Address into Var. The PIC16F87x devices allow code to be read and written at run-time. While writing self-modifying code can be a dangerous technique, it does allow non-volatile data storage above 64 - 256 bytes. One must be very careful not to write over active program memory. The listing file may be examined to determine program addresses.

Example

READCODE 100,W ' Put the code word at location 100 into W

See Also

WRITECODE

Copyright © 1999 microEngineering Labs, Inc.
All rights reserved.


Serial Control Characters

You can send special control characters in your serial message string, using either a decimal or hexadecimal notation. For example, if you want to send hello world followed by a carriage return and line feed character, you would use hello world#13#10 for decimal, or hello world$D$A for hex.

MicroCode Studio will only convert numbers in the range 0 to 255. For example, sending the message letter #9712345 will be interpreted as letter a12345. That is, only the #97 part has been converted, because #971 would be greater than 255.

If the characters do not form a legal number, the sequence is interpreted as normal characters. For example, hello world#here I am. If you don't want MicroCode Studio to interpret a control sequence, but rather send it as normal characters, then just use the tilda symbol (~) in front of the $ or # symbol. For example, letter ~#9712345 would be sent as letter #9712345.